<?php
include "../db.php";

/* ================= API FOR CHARTS ================= */
if (isset($_GET['api']) && $_GET['api'] == '1') {
    header('Content-Type: application/json; charset=utf-8');

    $type = $_GET['type'] ?? 'day';
    $labels = $orders = $revenue = [];

    if ($type === 'day') {
        $stmt = $pdo->prepare("
            SELECT DATE(created_at) as label,
                   COUNT(*) AS orders,
                   IFNULL(SUM(total_amount),0) AS revenue
            FROM orders
            WHERE DATE(created_at) >= DATE_SUB(CURDATE(), INTERVAL 29 DAY)
            GROUP BY DATE(created_at)
            ORDER BY DATE(created_at) ASC
        ");
        $stmt->execute();
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $period = new DatePeriod(new DateTime('-29 days'), new DateInterval('P1D'), new DateTime('+1 day'));
        $map = [];
        foreach ($rows as $r) $map[$r['label']] = $r;

        foreach ($period as $dt) {
            $lab = $dt->format('Y-m-d');
            $labels[] = $lab;
            $orders[] = isset($map[$lab]) ? (int)$map[$lab]['orders'] : 0;
            $revenue[] = isset($map[$lab]) ? (float)$map[$lab]['revenue'] : 0;
        }
    } elseif ($type === 'week') {
        $stmt = $pdo->prepare("
            SELECT CONCAT(YEAR(created_at),'-W',LPAD(WEEK(created_at,1),2,'0')) as label,
                   COUNT(*) AS orders,
                   IFNULL(SUM(total_amount),0) AS revenue
            FROM orders
            WHERE DATE(created_at) >= DATE_SUB(CURDATE(), INTERVAL 12 WEEK)
            GROUP BY label
            ORDER BY label
        ");
        $stmt->execute();
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $map = [];
        foreach ($rows as $r) $map[$r['label']] = $r;

        $start = (new DateTime())->modify('monday this week');
        for ($i = 11; $i >= 0; $i--) {
            $dt = (clone $start)->modify("-$i weeks");
            $lab = $dt->format('Y') . '-W' . str_pad($dt->format('W'),2,'0',STR_PAD_LEFT);
            $labels[] = $lab;
            $orders[] = $map[$lab]['orders'] ?? 0;
            $revenue[] = $map[$lab]['revenue'] ?? 0;
        }
    } else {
        $stmt = $pdo->prepare("
            SELECT DATE_FORMAT(created_at,'%Y-%m') as label,
                   COUNT(*) AS orders,
                   IFNULL(SUM(total_amount),0) AS revenue
            FROM orders
            WHERE DATE(created_at) >= DATE_SUB(CURDATE(), INTERVAL 11 MONTH)
            GROUP BY label
            ORDER BY label
        ");
        $stmt->execute();
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $map = [];
        foreach ($rows as $r) $map[$r['label']] = $r;

        $start = new DateTime('first day of this month');
        for ($i = 11; $i >= 0; $i--) {
            $dt = (clone $start)->modify("-$i months");
            $lab = $dt->format('Y-m');
            $labels[] = $lab;
            $orders[] = $map[$lab]['orders'] ?? 0;
            $revenue[] = $map[$lab]['revenue'] ?? 0;
        }
    }

    echo json_encode(compact('labels','orders','revenue'));
    exit;
}

/* ================= PAGE DATA ================= */
$totalProducts = (int)$pdo->query("SELECT COUNT(*) FROM products")->fetchColumn();
$totalOrders   = (int)$pdo->query("SELECT COUNT(*) FROM orders")->fetchColumn();
$totalUsers    = (int)$pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
$totalRevenue  = (float)$pdo->query("SELECT IFNULL(SUM(total_amount),0) FROM orders WHERE payment_status='paid'")->fetchColumn();

$recentOrders = $pdo->query("
    SELECT id, first_name, last_name, total_amount, payment_status, created_at
    FROM orders
    ORDER BY created_at DESC LIMIT 8
")->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Admin Dashboard</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
:root{
  --primary:#0b4f27;
  --primary-dark:#083a1d;
  --bg:#f3f4f6;
  --card-bg:#ffffff;
  --text-dark:#1f2937;
  --text-muted:#6b7280;
}

body{
  background:var(--bg);
  color:var(--text-dark);
  font-family:'Poppins',sans-serif;
}

/* TOP BAR */
.topbar{
  background:#fff;
  padding:14px 22px;
  border-bottom:1px solid #e5e7eb;
}
.brand{
  color:var(--primary);
  font-weight:700;
}
.small-muted{
  color:var(--text-muted);
  font-size:13px;
}

/* CARDS */
.stat-card,.chart-card{
  background:var(--card-bg);
  border-radius:12px;
  padding:16px;
  box-shadow:0 8px 20px rgba(0,0,0,.05);
}
.stat-card{ border-left:6px solid var(--primary); }
.stat-card h3{ color:var(--primary); }

/* BUTTONS */
.btn-ghost{
  background:transparent;
  border:1px solid #d1d5db;
  color:var(--text-dark);
}
.controls .btn.active{
  background:var(--primary);
  color:#fff;
  border-color:var(--primary);
}

/* TABLE */
table th{ font-size:14px; }
table td{ font-size:14px; }

/* BADGES */
.badge-paid{
  background:#d1fae5;
  color:#065f46;
  padding:6px 10px;
  border-radius:8px;
  font-weight:600;
}
.badge-pending{
  background:#e5e7eb;
  color:#374151;
  padding:6px 10px;
  border-radius:8px;
  font-weight:600;
}

a.card-link{
  color:var(--primary);
  font-weight:500;
  text-decoration:none;
}
</style>
</head>

<body>

<div class="container-fluid mt-4">

<!-- STATS -->
<div class="row g-3">
<?php
$stats = [
  ["Total Products",$totalProducts],
  ["Total Orders",$totalOrders],
  ["Total Users",$totalUsers],
  ["Total Revenue","₹".number_format($totalRevenue,2)]
];
foreach($stats as $s):
?>
<div class="col-md-3">
  <div class="stat-card">
    <small class="small-muted"><?= $s[0] ?></small>
    <h3 class="m-0"><?= $s[1] ?></h3>
  </div>
</div>
<?php endforeach; ?>
</div>

<!-- CONTROLS -->
<div class="row mt-4">
  <div class="col-md-8 controls">
    <div class="btn-group">
      <button class="btn btn-ghost view-btn active" data-type="day">Day</button>
      <button class="btn btn-ghost view-btn" data-type="week">Week</button>
      <button class="btn btn-ghost view-btn" data-type="month">Month</button>
    </div>
  </div>
</div>

<!-- CHARTS -->
<div class="row mt-3 g-3">
  <div class="col-lg-8">
    <div class="chart-card">
      <h6>Orders Overview</h6>
      <canvas id="ordersChart" height="120"></canvas>
    </div>
    <div class="chart-card mt-3">
      <h6>Revenue Overview</h6>
      <canvas id="revenueChart" height="120"></canvas>
    </div>
  </div>

  <div class="col-lg-4">
    <div class="chart-card">
      <h6>Recent Orders</h6>
      <table class="table table-borderless">
        <?php foreach($recentOrders as $r): ?>
        <tr>
          <td><?= $r['id'] ?></td>
          <td><?= htmlspecialchars($r['first_name'].' '.$r['last_name']) ?></td>
          <td>₹<?= number_format($r['total_amount'],2) ?></td>
          <td><?= $r['payment_status']=='paid'
              ? '<span class="badge-paid">PAID</span>'
              : '<span class="badge-pending">PENDING</span>' ?></td>
        </tr>
        <?php endforeach; ?>
      </table>
    </div>
  </div>
</div>

</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
let currentType='day';
let ordersChart,revenueChart;

async function loadData(){
  const res=await fetch(`dashboard.php?api=1&type=${currentType}`);
  const d=await res.json();

  if(ordersChart) ordersChart.destroy();
  if(revenueChart) revenueChart.destroy();

  ordersChart=new Chart(ordersChartCtx,{
    type:'line',
    data:{labels:d.labels,datasets:[{data:d.orders,borderColor:'#0b4f27',fill:true}]}
  });

  revenueChart=new Chart(revenueChartCtx,{
    type:'bar',
    data:{labels:d.labels,datasets:[{data:d.revenue,backgroundColor:'#0b4f27'}]}
  });
}

const ordersChartCtx=document.getElementById('ordersChart').getContext('2d');
const revenueChartCtx=document.getElementById('revenueChart').getContext('2d');

document.querySelectorAll('.view-btn').forEach(b=>{
  b.onclick=()=>{ 
    document.querySelectorAll('.view-btn').forEach(x=>x.classList.remove('active'));
    b.classList.add('active');
    currentType=b.dataset.type;
    loadData();
  };
});

loadData();
</script>

</body>
</html>
