<?php
include('includes/db.php');

// Coletar título do sistema e outros dados
$tituloSistema = $pdo->query("SELECT titulo FROM configuracoes LIMIT 1")->fetchColumn();

// Coletar dados reais do banco
$hoje = date('Y-m-d');
$em5dias = date('Y-m-d', strtotime('+5 days'));

$totalClientes = $pdo->query("SELECT COUNT(*) FROM clientes")->fetchColumn();
$clientesAtivos = $pdo->query("SELECT COUNT(*) FROM clientes WHERE status = 'ativo'")->fetchColumn();
$vencendo = $pdo->query("SELECT COUNT(*) FROM clientes WHERE status = 'ativo' AND vencimento BETWEEN '$hoje' AND '$em5dias'")->fetchColumn();
$vencidos = $pdo->query("SELECT COUNT(*) FROM clientes WHERE status = 'ativo' AND vencimento < '$hoje'")->fetchColumn();
$receitaMensal = $pdo->query("SELECT SUM(preco) FROM clientes WHERE status = 'ativo'")->fetchColumn();
?>
<!DOCTYPE html>
<html lang="pt-br" class="dark">
<head>
  <meta charset="UTF-8">
  <title>Dashboard - <?= $tituloSistema ?></title>
  <script src="https://cdn.tailwindcss.com"></script>
  <script>
    tailwind.config = {
      darkMode: 'class',
    }
  </script>
  <script src="https://unpkg.com/@phosphor-icons/web"></script>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
</head>
<body class="bg-gray-100 dark:bg-gray-900 text-gray-800 dark:text-gray-100 transition duration-300">

<div class="flex min-h-screen">
  <!-- MENU LATERAL -->
  <aside id="menuLateral" class="fixed inset-y-0 left-0 w-64 bg-white dark:bg-gray-800 shadow-md transform -translate-x-full lg:translate-x-0 lg:relative transition-transform duration-300 z-50">
    <div class="p-6 text-2xl font-bold text-blue-600 dark:text-white"><?= $tituloSistema ?></div>
    <nav class="space-y-2 px-4 text-sm">
      <a href="dashboard.php" class="flex items-center gap-3 p-2 rounded-md bg-blue-100 dark:bg-blue-800 text-blue-600 dark:text-white font-medium">
  <i class="ph ph-gauge"></i> Dashboard
</a>

      <a href="clientes.php" class="flex items-center gap-3 p-2 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700">
        <i class="ph ph-users"></i> Clientes
      </a>

      <a href="configuracoes.php" class="flex items-center gap-3 p-2 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700">
        <i class="ph ph-gear"></i> Configurações
      </a>
      <a href="logout.php" class="flex items-center gap-3 p-2 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 text-red-600 dark:text-red-400 font-medium">
  <i class="ph ph-sign-out"></i> Sair
</a>


    </nav>
  </aside>

  <!-- CONTEÚDO PRINCIPAL -->
  <main class="flex-1 p-6">
    <!-- TOPO -->
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-xl font-semibold">Dashboard</h1>
      <div class="flex items-center gap-4">
        <button id="toggleTheme" class="w-10 h-10 rounded-full flex items-center justify-center transition bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600">
          <svg id="themeIcon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-6 h-6 text-yellow-500 dark:text-yellow-300 transition duration-300">
            <path fill-rule="evenodd" d="M12 2a1 1 0 011 1v1a1 1 0 11-2 0V3a1 1 0 011-1zm5.657 3.343a1 1 0 010 1.414L16.243 8.17a1 1 0 01-1.414-1.414l1.414-1.414a1 1 0 011.414 0zM21 11a1 1 0 110 2h-1a1 1 0 110-2h1zM5 11a1 1 0 100 2H4a1 1 0 100-2h1zm1.343-6.657a1 1 0 011.414 0l1.414 1.414A1 1 0 017.757 8.17L6.343 6.757a1 1 0 010-1.414zM12 20a1 1 0 011 1v1a1 1 0 11-2 0v-1a1 1 0 011-1zm6.657-2.343a1 1 0 00-1.414 0L16.243 18.17a1 1 0 001.414 1.414l1.414-1.414a1 1 0 000-1.414zM7.757 15.83a1 1 0 00-1.414 1.414l1.414 1.414a1 1 0 001.414-1.414L7.757 15.83zM12 6a6 6 0 000 12 6 6 0 000-12z" clip-rule="evenodd" />
          </svg>
        </button>
        <!-- BOTÃO MOBILE -->
<div class="lg:hidden mb-4">
  <button onclick="abrirMenu()" class="p-2 bg-blue-600 text-white rounded shadow">
    <i class="ph ph-list text-xl"></i>
  </button>
</div>


        <div class="w-9 h-9 rounded-full bg-gray-300 dark:bg-gray-600 flex items-center justify-center text-white font-bold">
          <img src="uploads/logo_1752262382.jpg" alt="Logo" class="w-8 h-8 rounded-full object-cover">
        </div>
      </div>
    </div>

    <!-- CARDS DE MÉTRICAS -->
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-4 mb-6">
      <div class="bg-white dark:bg-gray-800 p-4 rounded-lg shadow">
        <span class="text-sm text-gray-500 dark:text-gray-300">Total de Clientes</span>
        <div class="flex justify-between items-center">
          <span class="text-2xl font-bold"><?= $totalClientes ?></span>
          <i class="ph ph-users text-xl text-blue-600"></i>
        </div>
        <span class="text-green-600 text-sm">+0 Novos hoje</span>
      </div>
      <div class="bg-white dark:bg-gray-800 p-4 rounded-lg shadow">
        <span class="text-sm text-gray-500 dark:text-gray-300">Clientes Ativos</span>
        <div class="flex justify-between items-center">
          <span class="text-2xl font-bold"><?= $clientesAtivos ?></span>
          <i class="ph ph-check-circle text-xl text-green-600"></i>
        </div>
        <span class="text-gray-500 dark:text-gray-400 text-sm">
          <?= number_format(($clientesAtivos / max($totalClientes,1)) * 100, 1) ?>% do total
        </span>
      </div>
      <div class="bg-white dark:bg-gray-800 p-4 rounded-lg shadow">
        <span class="text-sm text-gray-500 dark:text-gray-300">Vencendo em Breve</span>
        <div class="flex justify-between items-center">
          <span class="text-2xl font-bold"><?= $vencendo ?></span>
          <i class="ph ph-clock text-xl text-yellow-500"></i>
        </div>
        <span class="text-yellow-600 text-sm">Próximos 5 dias</span>
      </div>
      <div class="bg-white dark:bg-gray-800 p-4 rounded-lg shadow">
        <span class="text-sm text-gray-500 dark:text-gray-300">Clientes Vencidos</span>
        <div class="flex justify-between items-center">
          <span class="text-2xl font-bold"><?= $vencidos ?></span>
          <i class="ph ph-x-circle text-xl text-red-500"></i>
        </div>
        <span class="text-red-600 text-sm">
          <?= number_format(($vencidos / max($totalClientes,1)) * 100, 1) ?>% do total
        </span>
      </div>
      <div class="bg-white dark:bg-gray-800 p-4 rounded-lg shadow">
        <span class="text-sm text-gray-500 dark:text-gray-300">Receita Mensal</span>
        <div class="flex justify-between items-center">
          <span class="text-2xl font-bold">R$ <?= number_format($receitaMensal, 2, ',', '.') ?></span>
          <i class="ph ph-credit-card text-xl text-green-600"></i>
        </div>
        <span class="text-green-600 text-sm">Lucro estimado</span>
      </div>
    </div>
    <!-- GRÁFICOS EM GRID -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
      <div class="bg-white dark:bg-gray-800 p-4 rounded-lg shadow">
        <h2 class="font-semibold mb-2">Evolução de Clientes</h2>
        <canvas id="graficoClientes"></canvas>
      </div>
      <div class="bg-white dark:bg-gray-800 p-4 rounded-lg shadow">
        <h2 class="font-semibold mb-2">Status dos Clientes</h2>
        <canvas id="graficoStatus"></canvas>
      </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
      <div class="bg-white dark:bg-gray-800 p-4 rounded-lg shadow">
        <h2 class="font-semibold mb-2">Serviços Ativos</h2>
        <canvas id="graficoServicos"></canvas>
      </div>
      <div class="bg-white dark:bg-gray-800 p-4 rounded-lg shadow">
        <h2 class="font-semibold mb-2">Planos Disponíveis</h2>
        <canvas id="graficoPlanos"></canvas>
      </div>
    </div>

    <div class="bg-white dark:bg-gray-800 p-4 rounded-lg shadow mb-6">
      <h2 class="font-semibold mb-2">Transações Recentes</h2>
      <canvas id="graficoTransacoes"></canvas>
    </div>
  </main>
</div>

<!-- SCRIPTS: Gráficos + Modo Escuro -->
<script>
  const toggleBtn = document.getElementById('toggleTheme');
  const html = document.documentElement;
  const icon = document.getElementById('themeIcon');

  // Verifica e aplica o tema salvo
  if (localStorage.getItem('modo') === 'light') {
    html.classList.remove('dark');
  } else {
    html.classList.add('dark');
  }

  // Alternar tema ao clicar
  toggleBtn.addEventListener('click', () => {
    html.classList.toggle('dark');
    const modoAtual = html.classList.contains('dark') ? 'dark' : 'light';
    localStorage.setItem('modo', modoAtual);

    // Troca de ícone (opcional: pode animar também)
    icon.classList.toggle('text-yellow-500');
    icon.classList.toggle('text-yellow-300');
  });

  // Gráfico: Evolução de Clientes
  new Chart(document.getElementById("graficoClientes"), {
    type: 'line',
    data: {
      labels: ["11/06", "14/06", "17/06", "20/06", "23/06", "02/07", "11/07"],
      datasets: [{
        label: "Clientes",
        data: [0, 2, 4, 3, 0, 9, 0],
        fill: false,
        borderColor: "#3B82F6",
        tension: 0.4
      }]
    },
    options: {
      responsive: true,
      plugins: { legend: { display: false } }
    }
  });

  // Gráfico: Status dos Clientes
  new Chart(document.getElementById("graficoStatus"), {
    type: 'pie',
    data: {
      labels: ["Ativos", "Vencendo", "Vencidos"],
      datasets: [{
        data: [<?= $clientesAtivos ?>, <?= $vencendo ?>, <?= $vencidos ?>],
        backgroundColor: ["#22c55e", "#facc15", "#ef4444"]
      }]
    },
    options: {
      plugins: {
        legend: { position: 'right' }
      }
    }
  });

  // Gráfico: Serviços Ativos
  new Chart(document.getElementById("graficoServicos"), {
    type: 'bar',
    data: {
      labels: ["Serviços"],
      datasets: [{
        label: "Serviços Ativos",
        data: [46], // valor fixo (ajustar se necessário)
        backgroundColor: "#3B82F6"
      }]
    },
    options: {
      responsive: true,
      plugins: { legend: { display: false } },
      scales: { y: { beginAtZero: true } }
    }
  });

  // Gráfico: Planos Disponíveis
  new Chart(document.getElementById("graficoPlanos"), {
    type: 'bar',
    data: {
      labels: ["Planos"],
      datasets: [{
        label: "Planos Disponíveis",
        data: [51], // valor fixo (ajustar se necessário)
        backgroundColor: "#10b981"
      }]
    },
    options: {
      responsive: true,
      plugins: { legend: { display: false } },
      scales: { y: { beginAtZero: true } }
    }
  });

  // Gráfico: Transações Recentes
  new Chart(document.getElementById("graficoTransacoes"), {
    type: 'line',
    data: {
      labels: ["11/06", "14/06", "17/06", "20/06", "23/06", "02/07", "11/07"],
      datasets: [
        {
          label: "Receitas",
          data: [100, 50, 75, 200, 180, 230, 0],
          borderColor: "#22c55e",
          backgroundColor: "rgba(34,197,94,0.2)",
          fill: true,
          tension: 0.4
        },
        {
          label: "Despesas",
          data: [30, 20, 10, 40, 30, 50, 0],
          borderColor: "#ef4444",
          backgroundColor: "rgba(239,68,68,0.1)",
          fill: true,
          tension: 0.4
        }
      ]
    },
    options: {
      responsive: true,
      plugins: { legend: { position: 'bottom' } }
    }
  });
</script>
<script>
function abrirMenu() {
  const menu = document.getElementById('menuLateral');
  menu.classList.toggle('-translate-x-full');
}
</script>

</body>
</html>