<?php
$dashboard = $dashboard ?? [];
$periodOptions = (array) ($dashboard['periodOptions'] ?? []);
$filters = (array) ($dashboard['filters'] ?? []);
$branches = (array) ($dashboard['branches'] ?? []);
$summary = (array) ($dashboard['summary'] ?? []);
$topProducts = (array) ($dashboard['topProducts'] ?? []);
$topProduct = $dashboard['topProduct'] ?? null;
$paymentMethods = (array) ($dashboard['paymentMethods'] ?? []);
$profitByBranch = (array) ($dashboard['profitByBranch'] ?? []);
$trend = (array) ($dashboard['trend'] ?? []);
$trendMaxSales = (float) ($dashboard['trendMaxSales'] ?? 0);
$trendMaxProfit = (float) ($dashboard['trendMaxProfit'] ?? 0);
$variations = (array) ($dashboard['variations'] ?? []);
$today = (array) ($dashboard['today'] ?? []);
$canViewFinancials = (bool) ($dashboard['canViewFinancials'] ?? false);

$topUnitsTotal = array_reduce($topProducts, static function (float $carry, array $row): float {
    return $carry + (float) ($row['cantidad'] ?? 0);
}, 0.0);
$paymentAmountTotal = array_reduce($paymentMethods, static function (float $carry, array $row): float {
    return $carry + (float) ($row['monto_total'] ?? 0);
}, 0.0);

$formatVariation = static function (?float $value): array {
    if ($value === null) {
        return ['label' => 'Nuevo', 'class' => 'is-neutral'];
    }
    if (abs($value) < 0.05) {
        return ['label' => '0%', 'class' => 'is-neutral'];
    }

    $rounded = number_format(abs($value), 1, ',', '.');
    if ($value > 0) {
        return ['label' => '+' . $rounded . '%', 'class' => 'is-up'];
    }
    return ['label' => '-' . $rounded . '%', 'class' => 'is-down'];
};

$normalizeMethod = static function (string $value): string {
    $clean = str_replace(['_', '-'], ' ', trim($value));
    if ($clean === '') {
        return 'Sin definir';
    }
    return ucwords(strtolower($clean));
};

$salesTrend = $formatVariation((float) ($variations['ventas_total'] ?? 0));
$profitTrend = $formatVariation((float) ($variations['utilidad_estimada'] ?? 0));
$profitPerSaleTrend = $formatVariation((float) ($variations['utilidad_por_venta'] ?? 0));
$countTrend = $formatVariation((float) ($variations['ventas_count'] ?? 0));
$neutralTrend = ['label' => 'Info', 'class' => 'is-neutral'];
$profitPerSale = ((float) ($summary['ventas_count'] ?? 0)) > 0
    ? ((float) ($summary['utilidad_estimada'] ?? 0) / (float) ($summary['ventas_count'] ?? 0))
    : 0.0;
?>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-body">
        <div class="vx-dashboard-hero-head">
            <div>
                <h2 class="h5 mb-1">Pulso comercial en tiempo real</h2>
                <?php if ($canViewFinancials): ?>
                    <p class="text-muted mb-0">Ventas, utilidad estimada y desempeño de productos con filtros dinámicos por fecha y sucursal.</p>
                <?php else: ?>
                    <p class="text-muted mb-0">Vista operativa para el equipo: ventas, transacciones y actividad diaria sin datos financieros sensibles.</p>
                <?php endif; ?>
            </div>
            <?php if ($canViewFinancials && has_permission('reportes.ver')): ?>
                <a class="btn btn-light" href="<?= e(url('reportes')) ?>">
                    <i class="bx bx-line-chart me-1"></i>Reporte completo
                </a>
            <?php endif; ?>
        </div>

        <form method="get" action="<?= e(url('dashboard')) ?>" class="row g-2 mt-1">
            <div class="col-md-3 col-lg-2">
                <label class="form-label">Periodo</label>
                <select class="form-select" name="periodo">
                    <?php foreach ($periodOptions as $key => $label): ?>
                        <option value="<?= e((string) $key) ?>" <?= (string) ($filters['periodo'] ?? '30d') === (string) $key ? 'selected' : '' ?>>
                            <?= e((string) $label) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3 col-lg-2">
                <label class="form-label">Desde</label>
                <input type="date" class="form-control" name="fecha_desde" value="<?= e((string) ($filters['fecha_desde'] ?? '')) ?>">
            </div>
            <div class="col-md-3 col-lg-2">
                <label class="form-label">Hasta</label>
                <input type="date" class="form-control" name="fecha_hasta" value="<?= e((string) ($filters['fecha_hasta'] ?? '')) ?>">
            </div>
            <div class="col-md-3 col-lg-3">
                <label class="form-label">Sucursal</label>
                <select class="form-select" name="sucursal_id">
                    <option value="0">Todas las sucursales</option>
                    <?php foreach ($branches as $branch): ?>
                        <option value="<?= e((string) ($branch['id'] ?? 0)) ?>" <?= (int) ($filters['sucursal_id'] ?? 0) === (int) ($branch['id'] ?? 0) ? 'selected' : '' ?>>
                            <?= e((string) ($branch['nombre'] ?? 'Sucursal')) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-12 col-lg-3">
                <label class="form-label d-none d-lg-block">&nbsp;</label>
                <div class="vx-dashboard-filter-actions">
                    <button class="btn btn-primary vx-dashboard-filter-btn" type="submit">
                        <i class="bx bx-search-alt me-1"></i>Actualizar
                    </button>
                    <a class="btn btn-light vx-dashboard-filter-btn" href="<?= e(url('dashboard')) ?>">Limpiar</a>
                </div>
                <div class="vx-dashboard-filter-range">
                    Rango activo: <?= e((string) ($filters['fecha_desde'] ?? '')) ?> - <?= e((string) ($filters['fecha_hasta'] ?? '')) ?>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="vx-kpi-grid mb-3">
    <article class="card vx-kpi-card">
        <div class="card-body">
            <div class="vx-kpi-head">
                <span class="vx-kpi-icon"><i class="bx bx-wallet"></i></span>
                <span class="vx-kpi-title">Ventas del periodo</span>
                <span class="vx-kpi-trend <?= e($salesTrend['class']) ?>"><?= e($salesTrend['label']) ?></span>
            </div>
            <p class="vx-kpi-value mb-0"><?= e(money((float) ($summary['ventas_total'] ?? 0))) ?></p>
            <small class="text-muted">Hoy: <?= e(money((float) ($today['ventas_total'] ?? 0))) ?></small>
        </div>
    </article>

    <article class="card vx-kpi-card">
        <div class="card-body">
            <div class="vx-kpi-head">
                <?php if ($canViewFinancials): ?>
                    <span class="vx-kpi-icon"><i class="bx bx-trending-up"></i></span>
                    <span class="vx-kpi-title">Ganancia estimada</span>
                    <span class="vx-kpi-trend <?= e($profitTrend['class']) ?>"><?= e($profitTrend['label']) ?></span>
                <?php else: ?>
                    <span class="vx-kpi-icon"><i class="bx bx-group"></i></span>
                    <span class="vx-kpi-title">Clientes activos</span>
                    <span class="vx-kpi-trend <?= e($neutralTrend['class']) ?>"><?= e($neutralTrend['label']) ?></span>
                <?php endif; ?>
            </div>
            <?php if ($canViewFinancials): ?>
                <p class="vx-kpi-value mb-0"><?= e(money((float) ($summary['utilidad_estimada'] ?? 0))) ?></p>
                <small class="text-muted">Ventas menos costo de producto</small>
            <?php else: ?>
                <p class="vx-kpi-value mb-0"><?= e(number_format((int) ($today['clientes_total'] ?? 0), 0, ',', '.')) ?></p>
                <small class="text-muted">Total clientes registrados en la empresa</small>
            <?php endif; ?>
        </div>
    </article>

    <article class="card vx-kpi-card">
        <div class="card-body">
            <div class="vx-kpi-head">
                <?php if ($canViewFinancials): ?>
                    <span class="vx-kpi-icon"><i class="bx bx-line-chart"></i></span>
                    <span class="vx-kpi-title">Utilidad por venta</span>
                    <span class="vx-kpi-trend <?= e($profitPerSaleTrend['class']) ?>"><?= e($profitPerSaleTrend['label']) ?></span>
                <?php else: ?>
                    <span class="vx-kpi-icon"><i class="bx bx-box"></i></span>
                    <span class="vx-kpi-title">Productos activos</span>
                    <span class="vx-kpi-trend <?= e($neutralTrend['class']) ?>"><?= e($neutralTrend['label']) ?></span>
                <?php endif; ?>
            </div>
            <?php if ($canViewFinancials): ?>
                <p class="vx-kpi-value mb-0"><?= e(money($profitPerSale)) ?></p>
                <small class="text-muted">Ganancia promedio por transacción</small>
            <?php else: ?>
                <p class="vx-kpi-value mb-0"><?= e(number_format((int) ($today['productos_total'] ?? 0), 0, ',', '.')) ?></p>
                <small class="text-muted">Stock bajo: <?= e(number_format((int) ($today['stock_bajo'] ?? 0), 0, ',', '.')) ?></small>
            <?php endif; ?>
        </div>
    </article>

    <article class="card vx-kpi-card">
        <div class="card-body">
            <div class="vx-kpi-head">
                <span class="vx-kpi-icon"><i class="bx bx-store-alt"></i></span>
                <span class="vx-kpi-title">Transacciones</span>
                <span class="vx-kpi-trend <?= e($countTrend['class']) ?>"><?= e($countTrend['label']) ?></span>
            </div>
            <p class="vx-kpi-value mb-0"><?= e(number_format((float) ($summary['ventas_count'] ?? 0), 0, ',', '.')) ?></p>
            <small class="text-muted">Clientes: <?= e(number_format((int) ($today['clientes_total'] ?? 0), 0, ',', '.')) ?> · Stock bajo: <?= e(number_format((int) ($today['stock_bajo'] ?? 0), 0, ',', '.')) ?></small>
        </div>
    </article>
</div>

<div class="row g-3 mb-3">
    <div class="col-xl-8">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <div class="vx-dash-card-head">
                    <h3 class="h6 mb-0">Tendencia diaria</h3>
                    <small class="text-muted">Ultimos <?= e((string) count($trend)) ?> dias del rango</small>
                </div>

                <?php if ($trend === []): ?>
                    <div class="vx-empty-state">No hay ventas en el rango seleccionado.</div>
                <?php else: ?>
                    <div class="vx-trend-chart">
                        <?php foreach ($trend as $row): ?>
                            <?php
                            $sales = (float) ($row['ventas_total'] ?? 0);
                            $profit = max(0.0, (float) ($row['utilidad_total'] ?? 0));
                            $salesHeight = $trendMaxSales > 0 ? max(8, (int) round(($sales / $trendMaxSales) * 100)) : 8;
                            $profitHeight = $trendMaxProfit > 0 ? max(6, (int) round(($profit / $trendMaxProfit) * 100)) : 6;
                            ?>
                            <div class="vx-trend-col" title="<?= e((string) ($row['fecha'] ?? '')) ?> · Ventas <?= e(money($sales)) ?><?= $canViewFinancials ? ' · Ganancia ' . e(money($profit)) : '' ?>">
                                <div class="vx-trend-bars">
                                    <span class="vx-trend-bar is-sales" style="height: <?= e((string) $salesHeight) ?>%"></span>
                                    <?php if ($canViewFinancials): ?>
                                        <span class="vx-trend-bar is-profit" style="height: <?= e((string) $profitHeight) ?>%"></span>
                                    <?php endif; ?>
                                </div>
                                <small><?= e((string) ($row['label'] ?? '')) ?></small>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <div class="vx-trend-legend">
                        <span><i class="dot is-sales"></i>Ventas</span>
                        <?php if ($canViewFinancials): ?>
                            <span><i class="dot is-profit"></i>Ganancia</span>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="col-xl-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <div class="vx-dash-card-head">
                    <h3 class="h6 mb-0">Producto mas vendido</h3>
                    <small class="text-muted">Ranking dinamico</small>
                </div>

                <?php if (!is_array($topProduct)): ?>
                    <div class="vx-empty-state">Aun no hay ventas de productos para mostrar.</div>
                <?php else: ?>
                    <div class="vx-top-main">
                        <strong><?= e((string) ($topProduct['nombre'] ?? 'Producto')) ?></strong>
                        <div class="vx-top-main-stats">
                            <span>Unidades: <b><?= e(number_format((float) ($topProduct['cantidad'] ?? 0), 0, ',', '.')) ?></b></span>
                            <span>Vendido: <b><?= e(money((float) ($topProduct['total_vendido'] ?? 0))) ?></b></span>
                            <?php if ($canViewFinancials): ?>
                                <span>Ganancia: <b><?= e(money((float) ($topProduct['utilidad_estimada'] ?? 0))) ?></b></span>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>

                <ul class="vx-top-list">
                    <?php if ($topProducts === []): ?>
                        <li class="vx-empty-state">Sin top de productos para este periodo.</li>
                    <?php endif; ?>
                    <?php foreach ($topProducts as $row): ?>
                        <?php
                        $units = (float) ($row['cantidad'] ?? 0);
                        $percent = $topUnitsTotal > 0 ? round(($units / $topUnitsTotal) * 100, 1) : 0;
                        ?>
                        <li>
                            <div class="vx-top-list-row">
                                <span class="vx-top-list-name"><?= e((string) ($row['nombre'] ?? 'Producto')) ?></span>
                                <span class="vx-top-list-value"><?= e(number_format($units, 0, ',', '.')) ?> u.</span>
                            </div>
                            <div class="vx-top-list-progress"><span style="width: <?= e((string) $percent) ?>%"></span></div>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </div>
    </div>
</div>

<div class="row g-3">
    <div class="col-xl-5">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <div class="vx-dash-card-head">
                    <h3 class="h6 mb-0">Metodos de pago</h3>
                    <small class="text-muted">Participacion por monto</small>
                </div>

                <ul class="vx-payment-list">
                    <?php if ($paymentMethods === []): ?>
                        <li class="vx-empty-state">No hay pagos registrados en el rango actual.</li>
                    <?php endif; ?>
                    <?php foreach ($paymentMethods as $row): ?>
                        <?php
                        $amount = (float) ($row['monto_total'] ?? 0);
                        $percent = $paymentAmountTotal > 0 ? round(($amount / $paymentAmountTotal) * 100, 1) : 0;
                        ?>
                        <li>
                            <div class="vx-payment-row">
                                <span><?= e($normalizeMethod((string) ($row['metodo_pago'] ?? ''))) ?></span>
                                <b><?= e(money($amount)) ?></b>
                            </div>
                            <div class="vx-payment-progress"><span style="width: <?= e((string) $percent) ?>%"></span></div>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </div>
    </div>

    <div class="col-xl-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <div class="vx-dash-card-head">
                    <h3 class="h6 mb-0"><?= $canViewFinancials ? 'Ganancia por sucursal' : 'Ventas por sucursal' ?></h3>
                    <small class="text-muted">Top del periodo</small>
                </div>

                <div class="vx-branch-compact-list">
                    <?php if ($profitByBranch === []): ?>
                        <div class="vx-empty-state">No hay registros por sucursal.</div>
                    <?php endif; ?>
                    <?php foreach ($profitByBranch as $row): ?>
                        <article>
                            <div>
                                <strong><?= e((string) ($row['sucursal'] ?? 'Sin sucursal')) ?></strong>
                                <small><?= e((string) number_format((float) ($row['ventas_count'] ?? 0), 0, ',', '.')) ?> ventas</small>
                            </div>
                            <div class="text-end">
                                <?php if ($canViewFinancials): ?>
                                    <strong><?= e(money((float) ($row['utilidad_total'] ?? 0))) ?></strong>
                                    <small><?= e(money((float) ($row['ventas_total'] ?? 0))) ?> vendido</small>
                                <?php else: ?>
                                    <strong><?= e(money((float) ($row['ventas_total'] ?? 0))) ?></strong>
                                    <small>Total vendido</small>
                                <?php endif; ?>
                            </div>
                        </article>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <div class="vx-dash-card-head">
                    <h3 class="h6 mb-0">Accesos rapidos</h3>
                    <small class="text-muted">Operaciones clave</small>
                </div>
                <div class="d-grid gap-2">
                    <a class="btn btn-primary" href="<?= e(url('pos')) ?>"><i class="bx bx-cart-add me-1"></i>Nueva venta</a>
                    <a class="btn btn-light" href="<?= e(url('ventas')) ?>"><i class="bx bx-receipt me-1"></i>Historial ventas</a>
                    <a class="btn btn-light" href="<?= e(url('clientes')) ?>"><i class="bx bx-user me-1"></i>Clientes</a>
                    <a class="btn btn-light" href="<?= e(url('inventario')) ?>"><i class="bx bx-box me-1"></i>Inventario</a>
                    <a class="btn btn-light" href="<?= e(url('caja')) ?>"><i class="bx bx-wallet me-1"></i>Estado caja</a>
                </div>
            </div>
        </div>
    </div>
</div>
