<!DOCTYPE html>
<html lang="pt-BR">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $pageTitle ?? 'Painel de Revendas' ?> | Aurion ERP</title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet">

    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
</head>

<body style="background-color: #f8f9fa; font-family: 'Inter', sans-serif;">

    <!-- Navbar -->
    <nav class="navbar navbar-expand-lg navbar-dark" style="background-color: #1e293b;">
        <div class="container-fluid">
            <a class="navbar-brand d-flex align-items-center" href="./">
                <img src="storage/uploads/logo.png" alt="Systhema"
                    style="height: 45px; width: auto; object-fit: contain; transform: scale(2); transform-origin: left center;">
            </a>

            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="revenda">
                            <i class="bi bi-house me-1"></i>Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="revenda/comissoes">
                            <i class="bi bi-trophy me-1"></i>Comissões
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="revenda/clientes">
                            <i class="bi bi-people me-1"></i>Clientes
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="revenda/vendas">
                            <i class="bi bi-cart me-1"></i>Vendas
                        </a>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                            <i class="bi bi-person-circle me-1"></i><?= $user['name'] ?? 'Revendedor' ?>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="<?= url('/revenda/logout') ?>">
                                    <i class="bi bi-box-arrow-right me-1"></i>Logout
                                </a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container-fluid" style="margin-top: 2rem;">
        <!-- Header do Painel -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="h3 mb-0 text-gray-800">
                    <i class="bi bi-graph-up me-2"></i>Painel de Revendas
                    <?php if (isset($isDemo) && $isDemo): ?>
                        <span class="badge bg-warning text-dark ms-2">
                            <i class="bi bi-info-circle me-1"></i>Demonstração
                        </span>
                    <?php endif; ?>
                </h1>
                <p class="text-muted">
                    <?php if (isset($isDemo) && $isDemo): ?>
                        Dados de demonstração - Faça login para ver seus dados reais
                    <?php else: ?>
                        Acompanhe suas vendas, comissões e clientes
                    <?php endif; ?>
                </p>
            </div>
            <div>
                <span class="badge bg-primary fs-6">
                    <i class="bi bi-calendar3 me-1"></i>
                    <?= date('M/Y') ?>
                </span>
            </div>
        </div>

        <?php if (isset($isDemo) && $isDemo): ?>
            <!-- Alerta de Demonstração -->
            <div class="alert alert-info alert-dismissible fade show" role="alert">
                <i class="bi bi-info-circle me-2"></i>
                <strong>Modo Demonstração:</strong> Você está visualizando dados de exemplo.
                <a href="login" class="alert-link">Faça login</a> para acessar seus dados reais.
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Cards de Estatísticas -->
        <div class="row mb-4">
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-primary shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                    Total de Clientes
                                </div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">
                                    <?= number_format($stats['totalClientes'] ?? 0) ?>
                                </div>
                            </div>
                            <div class="col-auto">
                                <i class="bi bi-people-fill fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-success shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                    Vendas Este Mês
                                </div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">
                                    <?= number_format($stats['vendasMes'] ?? 0) ?>
                                </div>
                            </div>
                            <div class="col-auto">
                                <i class="bi bi-cart-check-fill fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-info shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                    Faturamento
                                </div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">
                                    R$ <?= number_format($stats['valorVendasMes'] ?? 0, 2, ',', '.') ?>
                                </div>
                            </div>
                            <div class="col-auto">
                                <i class="bi bi-currency-dollar fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-warning shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                    Comissões
                                </div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">
                                    R$ <?= number_format($stats['comissoesMes'] ?? 0, 2, ',', '.') ?>
                                </div>
                            </div>
                            <div class="col-auto">
                                <i class="bi bi-trophy-fill fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Barra de Progresso da Meta -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card shadow">
                    <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                        <h6 class="m-0 font-weight-bold text-primary">Meta Mensal</h6>
                        <span class="badge bg-primary">
                            <?= number_format($stats['percentualMeta'] ?? 0, 1) ?>%
                        </span>
                    </div>
                    <div class="card-body">
                        <div class="progress mb-3">
                            <div class="progress-bar" role="progressbar"
                                style="width: <?= min(100, $stats['percentualMeta'] ?? 0) ?>%"
                                aria-valuenow="<?= $stats['percentualMeta'] ?? 0 ?>" aria-valuemin="0"
                                aria-valuemax="100">
                            </div>
                        </div>
                        <div class="row text-center">
                            <div class="col">
                                <small class="text-muted">Realizado</small>
                                <div class="font-weight-bold">
                                    R$ <?= number_format($stats['valorVendasMes'] ?? 0, 2, ',', '.') ?>
                                </div>
                            </div>
                            <div class="col">
                                <small class="text-muted">Meta</small>
                                <div class="font-weight-bold">
                                    R$ <?= number_format($stats['metaMes'] ?? 0, 2, ',', '.') ?>
                                </div>
                            </div>
                            <div class="col">
                                <small class="text-muted">Restante</small>
                                <div
                                    class="font-weight-bold text-<?= ($stats['metaMes'] - $stats['valorVendasMes']) > 0 ? 'danger' : 'success' ?>">
                                    R$
                                    <?= number_format(max(0, ($stats['metaMes'] ?? 0) - ($stats['valorVendasMes'] ?? 0)), 2, ',', '.') ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Gráfico de Comissões -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card shadow">
                    <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                        <h6 class="m-0 font-weight-bold text-primary">Comissões por Período</h6>
                    </div>
                    <div class="card-body">
                        <canvas id="comissoesChart" height="100"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- Tabelas de Dados Recentes -->
        <div class="row">
            <!-- Clientes Recentes -->
            <div class="col-lg-6 mb-4">
                <div class="card shadow">
                    <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                        <h6 class="m-0 font-weight-bold text-primary">Clientes Recentes</h6>
                        <a href="revenda/clientes" class="btn btn-sm btn-primary">
                            <i class="bi bi-eye me-1"></i>Ver Todos
                        </a>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($clientesRecentes)): ?>
                            <div class="table-responsive">
                                <table class="table table-sm">
                                    <thead>
                                        <tr>
                                            <th>Cliente</th>
                                            <th>Vendas</th>
                                            <th>Valor Total</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($clientesRecentes as $cliente): ?>
                                            <tr>
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <div
                                                            class="avatar-sm bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-2">
                                                            <?= strtoupper(substr($cliente['name'], 0, 1)) ?>
                                                        </div>
                                                        <div>
                                                            <div class="font-weight-bold">
                                                                <?= htmlspecialchars($cliente['name']) ?>
                                                            </div>
                                                            <small class="text-muted">
                                                                <?= date('d/m/Y', strtotime($cliente['created_at'])) ?>
                                                            </small>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td>
                                                    <span class="badge bg-info">
                                                        <?= $cliente['total_vendas'] ?? 0 ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <span class="font-weight-bold">
                                                        R$
                                                        <?= number_format($cliente['valor_total_vendas'] ?? 0, 2, ',', '.') ?>
                                                    </span>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="text-center py-4">
                                <i class="bi bi-person-x display-4 text-muted"></i>
                                <p class="text-muted mt-2">Nenhum cliente encontrado</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Vendas Recentes -->
            <div class="col-lg-6 mb-4">
                <div class="card shadow">
                    <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                        <h6 class="m-0 font-weight-bold text-primary">Vendas Recentes</h6>
                        <a href="revenda/vendas" class="btn btn-sm btn-primary">
                            <i class="bi bi-eye me-1"></i>Ver Todas
                        </a>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($vendasRecentes)): ?>
                            <div class="table-responsive">
                                <table class="table table-sm">
                                    <thead>
                                        <tr>
                                            <th>Venda</th>
                                            <th>Cliente</th>
                                            <th>Valor</th>
                                            <th>Comissão</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($vendasRecentes as $venda): ?>
                                            <tr>
                                                <td>
                                                    <div>
                                                        <div class="font-weight-bold">#<?= $venda['id'] ?></div>
                                                        <small class="text-muted">
                                                            <?= date('d/m/Y H:i', strtotime($venda['created_at'])) ?>
                                                        </small>
                                                    </div>
                                                </td>
                                                <td>
                                                    <span class="font-weight-bold">
                                                        <?= htmlspecialchars($venda['cliente_nome'] ?? 'N/A') ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <span class="font-weight-bold text-success">
                                                        R$ <?= number_format($venda['total'], 2, ',', '.') ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <span class="font-weight-bold text-warning">
                                                        R$ <?= number_format($venda['comissao'] ?? 0, 2, ',', '.') ?>
                                                    </span>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="text-center py-4">
                                <i class="bi bi-cart-x display-4 text-muted"></i>
                                <p class="text-muted mt-2">Nenhuma venda encontrada</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            // Dados para o gráfico de comissões
            const comissoesData = <?= json_encode($comissoes ?? []) ?>;

            const labels = comissoesData.map(item => {
                const [year, month] = item.periodo.split('-');
                return new Date(year, month - 1).toLocaleDateString('pt-BR', {
                    month: 'short',
                    year: 'numeric'
                });
            }).reverse();

            const valores = comissoesData.map(item => parseFloat(item.comissao_total || 0)).reverse();

            // Gráfico de comissões
            const ctx = document.getElementById('comissoesChart').getContext('2d');
            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Comissões (R$)',
                        data: valores,
                        borderColor: 'rgb(54, 162, 235)',
                        backgroundColor: 'rgba(54, 162, 235, 0.1)',
                        tension: 0.4,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function (value) {
                                    return 'R$ ' + value.toLocaleString('pt-BR');
                                }
                            }
                        }
                    },
                    plugins: {
                        tooltip: {
                            callbacks: {
                                label: function (context) {
                                    return 'Comissões: R$ ' + context.parsed.y.toLocaleString('pt-BR', {
                                        minimumFractionDigits: 2,
                                        maximumFractionDigits: 2
                                    });
                                }
                            }
                        }
                    }
                }
            });
        });
    </script>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

</body>

</html>

<style>
    .border-left-primary {
        border-left: 0.25rem solid #4e73df !important;
    }

    .border-left-success {
        border-left: 0.25rem solid #1cc88a !important;
    }

    .border-left-info {
        border-left: 0.25rem solid #36b9cc !important;
    }

    .border-left-warning {
        border-left: 0.25rem solid #f6c23e !important;
    }

    .avatar-sm {
        width: 32px;
        height: 32px;
        font-size: 0.875rem;
    }

    .text-xs {
        font-size: 0.7rem;
    }

    .font-weight-bold {
        font-weight: 700 !important;
    }

    .text-gray-800 {
        color: #5a5c69 !important;
    }

    .text-gray-300 {
        color: #dddfeb !important;
    }

    .text-primary {
        color: #4e73df !important;
    }

    .text-success {
        color: #1cc88a !important;
    }

    .text-info {
        color: #36b9cc !important;
    }

    .text-warning {
        color: #f6c23e !important;
    }

    .text-danger {
        color: #e74a3b !important;
    }

    .text-muted {
        color: #858796 !important;
    }

    .shadow {
        box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15) !important;
    }

    .card {
        position: relative;
        display: flex;
        flex-direction: column;
        min-width: 0;
        word-wrap: break-word;
        background-color: #fff;
        background-clip: border-box;
        border: 1px solid #e3e6f0;
        border-radius: 0.35rem;
    }

    .card-header {
        padding: 0.75rem 1.25rem;
        margin-bottom: 0;
        background-color: #f8f9fc;
        border-bottom: 1px solid #e3e6f0;
    }

    .card-body {
        flex: 1 1 auto;
        padding: 1.25rem;
    }

    .progress {
        display: flex;
        height: 1rem;
        overflow: hidden;
        font-size: 0.75rem;
        background-color: #eaecf4;
        border-radius: 0.35rem;
    }

    .progress-bar {
        display: flex;
        flex-direction: column;
        justify-content: center;
        color: #fff;
        text-align: center;
        white-space: nowrap;
        background-color: #4e73df;
        transition: width 0.6s ease;
    }
</style>