<?php
session_start();
$page_title = 'Analytics';
$active_nav = 'analytics';
include("includes/header.php");

// ── Date range (default: last 30 days) ──────────────────────────────────────
$date_from = $_GET['date_from'] ?? date('Y-m-d', strtotime('-29 days'));
$date_to   = $_GET['date_to']   ?? date('Y-m-d');
// Guard against an inverted range
if ($date_from > $date_to) { [$date_from, $date_to] = [$date_to, $date_from]; }

// ── Summary metrics (paid orders within range) ──────────────────────────────
$sum = $conn->prepare("SELECT
    COALESCE(SUM(total_amount),0) as revenue,
    COUNT(*) as paid_orders,
    COALESCE(AVG(total_amount),0) as avg_order
    FROM orders WHERE restaurant_id=? AND payment_status='paid' AND DATE(created_at) BETWEEN ? AND ?");
$sum->bind_param("iss",$__rid,$date_from,$date_to); $sum->execute();
$summary = $sum->get_result()->fetch_assoc();

// All orders placed in range (any payment status), excluding cancelled for the "total orders" headline
$all_orders = $conn->prepare("SELECT COUNT(*) FROM orders WHERE restaurant_id=? AND DATE(created_at) BETWEEN ? AND ?");
$all_orders->bind_param("iss",$__rid,$date_from,$date_to); $all_orders->execute();
$total_orders_count = (int)$all_orders->get_result()->fetch_row()[0];

// Total items sold (paid orders)
$items_sold = $conn->prepare("SELECT COALESCE(SUM(oi.quantity),0)
    FROM order_items oi JOIN orders o ON oi.order_id=o.id
    WHERE o.restaurant_id=? AND o.payment_status='paid' AND DATE(o.created_at) BETWEEN ? AND ?");
$items_sold->bind_param("iss",$__rid,$date_from,$date_to); $items_sold->execute();
$total_items_sold = (int)$items_sold->get_result()->fetch_row()[0];

// ── Revenue trend (daily, paid orders) ───────────────────────────────────────
$trend = $conn->prepare("SELECT DATE(created_at) as day, COALESCE(SUM(total_amount),0) as rev, COUNT(*) as cnt
    FROM orders WHERE restaurant_id=? AND payment_status='paid' AND DATE(created_at) BETWEEN ? AND ?
    GROUP BY DATE(created_at) ORDER BY day ASC");
$trend->bind_param("iss",$__rid,$date_from,$date_to); $trend->execute();
$trend_rows = $trend->get_result()->fetch_all(MYSQLI_ASSOC);
$trend_map = [];
foreach($trend_rows as $r){ $trend_map[$r['day']] = ['rev'=>(float)$r['rev'],'cnt'=>(int)$r['cnt']]; }

$trend_labels = []; $trend_revenue = []; $trend_orders = [];
$cursor = strtotime($date_from); $end = strtotime($date_to);
$day_span = (int)round(($end - $cursor) / 86400);
while ($cursor <= $end) {
    $d = date('Y-m-d', $cursor);
    $trend_labels[]  = $day_span > 60 ? date('M j', $cursor) : date('D j', $cursor);
    $trend_revenue[] = $trend_map[$d]['rev'] ?? 0;
    $trend_orders[]  = $trend_map[$d]['cnt'] ?? 0;
    $cursor += 86400;
}

// ── Order status breakdown (all orders in range) ────────────────────────────
$status_q = $conn->prepare("SELECT order_status, COUNT(*) as cnt FROM orders
    WHERE restaurant_id=? AND DATE(created_at) BETWEEN ? AND ? GROUP BY order_status");
$status_q->bind_param("iss",$__rid,$date_from,$date_to); $status_q->execute();
$status_rows = $status_q->get_result()->fetch_all(MYSQLI_ASSOC);
$status_labels = ['pending'=>'Pending','accepted'=>'Accepted','preparing'=>'Preparing','ready'=>'Ready','served'=>'Served','completed'=>'Completed','cancelled'=>'Cancelled'];
$status_colors = ['pending'=>'#F59E0B','confirmed'=>'#225AE3','preparing'=>'#8B5CF6','ready'=>'#06B6D4','completed'=>'#10B981','cancelled'=>'#EF4444'];
$status_data = [];
foreach($status_rows as $r){
    $key = $r['order_status'];
    $status_data[] = ['label'=>$status_labels[$key]??ucfirst($key),'value'=>(int)$r['cnt'],'color'=>$status_colors[$key]??'#94A3B8'];
}

// ── Top-selling items (paid orders) ─────────────────────────────────────────
$top_items = $conn->prepare("SELECT oi.item_name, SUM(oi.quantity) as qty, SUM(oi.price*oi.quantity) as revenue
    FROM order_items oi JOIN orders o ON oi.order_id=o.id
    WHERE o.restaurant_id=? AND o.payment_status='paid' AND DATE(o.created_at) BETWEEN ? AND ?
    GROUP BY oi.item_name ORDER BY qty DESC LIMIT 10");
$top_items->bind_param("iss",$__rid,$date_from,$date_to); $top_items->execute();
$top_items_rows = $top_items->get_result()->fetch_all(MYSQLI_ASSOC);
$max_qty = 0; foreach($top_items_rows as $ti){ $max_qty = max($max_qty,(int)$ti['qty']); }

// ── Peak hours (all orders in range, by hour of day) ────────────────────────
$hours_q = $conn->prepare("SELECT HOUR(created_at) as hr, COUNT(*) as cnt FROM orders
    WHERE restaurant_id=? AND DATE(created_at) BETWEEN ? AND ? GROUP BY HOUR(created_at)");
$hours_q->bind_param("iss",$__rid,$date_from,$date_to); $hours_q->execute();
$hours_rows = $hours_q->get_result()->fetch_all(MYSQLI_ASSOC);
$hours_map = []; foreach($hours_rows as $hr){ $hours_map[(int)$hr['hr']] = (int)$hr['cnt']; }
$hour_labels = []; $hour_data = [];
for($h=0;$h<24;$h++){
    $hour_labels[] = date('g A', mktime($h,0,0));
    $hour_data[] = $hours_map[$h] ?? 0;
}

// Quick range presets
$presets = [
    '7'  => ['label'=>'7 Days',  'from'=>date('Y-m-d',strtotime('-6 days'))],
    '30' => ['label'=>'30 Days', 'from'=>date('Y-m-d',strtotime('-29 days'))],
    '90' => ['label'=>'90 Days', 'from'=>date('Y-m-d',strtotime('-89 days'))],
];
?>
<!-- Chart.js for analytics visualisations -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.4/chart.umd.min.js"></script>
<style>
.chart-card{padding:0}
.chart-card .card-header{margin-bottom:0}
.chart-wrap{padding:18px 20px}
.range-form{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
.range-form input[type=date]{height:38px;border:1.5px solid var(--border);border-radius:10px;background:var(--white);padding:0 10px;font-size:.82rem;font-family:var(--font);outline:none}
.range-presets{display:flex;gap:6px;flex-wrap:wrap}
.range-preset{padding:7px 12px;border-radius:8px;font-size:.75rem;font-weight:700;border:1.5px solid var(--border);background:var(--white);color:var(--text-muted);text-decoration:none;transition:all .2s}
.range-preset.on,.range-preset:hover{background:var(--primary);color:#fff;border-color:var(--primary)}
.top-item-row{display:flex;align-items:center;gap:12px;padding:12px 20px;border-bottom:1px solid var(--border)}
.top-item-row:last-child{border-bottom:none}
.top-item-rank{width:26px;height:26px;border-radius:8px;background:var(--primary-bg);color:var(--primary);font-size:.72rem;font-weight:800;display:flex;align-items:center;justify-content:center;flex-shrink:0}
.top-item-bar-track{height:6px;border-radius:4px;background:var(--bg);overflow:hidden;margin-top:6px}
.top-item-bar-fill{height:100%;background:linear-gradient(90deg,var(--primary),var(--primary-light));border-radius:4px}
@media(max-width:1024px){.chart-wrap canvas{max-width:100%!important}}
</style>

<div style="display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:22px;flex-wrap:wrap;gap:14px">
  <div>
    <h1 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em;margin-bottom:3px">Analytics</h1>
    <p style="color:var(--text-muted);font-size:.85rem"><?php echo htmlspecialchars($__rest_name); ?> &bull; <?php echo date('M j', strtotime($date_from)); ?> – <?php echo date('M j, Y', strtotime($date_to)); ?></p>
  </div>
  <form method="GET" class="range-form">
    <div class="range-presets">
      <?php foreach($presets as $days=>$p):
        $is_on = ($date_from===$p['from'] && $date_to===date('Y-m-d'));
      ?>
        <a href="?date_from=<?php echo $p['from']; ?>&date_to=<?php echo date('Y-m-d'); ?>" class="range-preset <?php echo $is_on?'on':''; ?>"><?php echo $p['label']; ?></a>
      <?php endforeach; ?>
    </div>
    <input type="date" name="date_from" value="<?php echo htmlspecialchars($date_from); ?>" max="<?php echo date('Y-m-d'); ?>">
    <span style="color:var(--text-muted);font-size:.8rem">to</span>
    <input type="date" name="date_to" value="<?php echo htmlspecialchars($date_to); ?>" max="<?php echo date('Y-m-d'); ?>">
    <button type="submit" class="btn btn-primary btn-md">Apply</button>
  </form>
</div>

<!-- Summary cards -->
<div class="grid-4" style="margin-bottom:24px">
  <?php
  $cards=[
    ['Revenue','₦'.number_format($summary['revenue'],0),'#225AE3','#EEF3FD','M12 2v20M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6'],
    ['Total Orders',number_format($total_orders_count),'#10B981','#F0FDF4','M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2 M9 3h6v4H9z'],
    ['Avg. Order Value','₦'.number_format($summary['avg_order'],0),'#F59E0B','#FFFBEB','M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z'],
    ['Items Sold',number_format($total_items_sold),'#8B5CF6','#F5F3FF','M4 6h16M4 10h16M4 14h16M4 18h7'],
  ];
  foreach($cards as $c):
    [$label,$val,$color,$bg,$icon]=$c;
  ?>
  <div class="card" style="padding:20px;border-top:3px solid <?php echo $color; ?>">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:12px">
      <span style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted)"><?php echo $label; ?></span>
      <div style="width:34px;height:34px;background:<?php echo $bg; ?>;border-radius:10px;display:flex;align-items:center;justify-content:center">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="<?php echo $color; ?>" stroke-width="2" stroke-linecap="round"><path d="<?php echo $icon; ?>"/></svg>
      </div>
    </div>
    <div style="font-size:1.65rem;font-weight:800;letter-spacing:-.03em;color:<?php echo $color; ?>"><?php echo $val; ?></div>
  </div>
  <?php endforeach; ?>
</div>

<!-- Revenue trend + Order status -->
<div class="grid-2" style="margin-bottom:24px;align-items:stretch">
  <div class="card chart-card">
    <div class="card-header"><h3>Revenue Trend</h3><span style="font-size:.72rem;color:var(--text-muted)"><?php echo count($trend_labels); ?> days</span></div>
    <div class="chart-wrap"><canvas id="revenueChart" height="220"></canvas></div>
  </div>
  <div class="card chart-card">
    <div class="card-header"><h3>Order Status Breakdown</h3></div>
    <?php if(empty($status_data)): ?>
      <div style="padding:48px;text-align:center;color:var(--text-muted);font-size:.84rem">No orders in this period.</div>
    <?php else: ?>
    <div class="chart-wrap" style="display:flex;align-items:center;gap:18px;flex-wrap:wrap;justify-content:center">
      <div style="flex-shrink:0;width:180px;height:180px"><canvas id="statusChart"></canvas></div>
      <div style="flex:1;min-width:140px">
        <?php foreach($status_data as $sd): ?>
        <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;font-size:.8rem">
          <span style="width:10px;height:10px;border-radius:3px;background:<?php echo $sd['color']; ?>;flex-shrink:0"></span>
          <span style="flex:1;color:var(--text-muted)"><?php echo htmlspecialchars($sd['label']); ?></span>
          <span style="font-weight:700"><?php echo $sd['value']; ?></span>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>
  </div>
</div>

<!-- Top items + Peak hours -->
<div class="grid-2" style="align-items:stretch">
  <div class="card chart-card">
    <div class="card-header"><h3>Top-Selling Items</h3><a href="menu.php" style="font-size:.75rem;color:var(--primary);font-weight:600">Manage menu →</a></div>
    <?php if(empty($top_items_rows)): ?>
      <div style="padding:48px;text-align:center;color:var(--text-muted);font-size:.84rem">No paid orders in this period yet.</div>
    <?php else: ?>
      <?php foreach($top_items_rows as $i=>$ti):
        $pct = $max_qty>0 ? round(($ti['qty']/$max_qty)*100) : 0;
      ?>
      <div class="top-item-row">
        <div class="top-item-rank">#<?php echo $i+1; ?></div>
        <div style="flex:1;min-width:0">
          <div style="display:flex;justify-content:space-between;gap:10px">
            <span style="font-weight:700;font-size:.85rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?php echo htmlspecialchars($ti['item_name']); ?></span>
            <span style="font-weight:700;font-size:.85rem;color:var(--primary);white-space:nowrap">₦<?php echo number_format($ti['revenue'],0); ?></span>
          </div>
          <div class="top-item-bar-track"><div class="top-item-bar-fill" style="width:<?php echo $pct; ?>%"></div></div>
          <div style="font-size:.7rem;color:var(--text-muted);margin-top:4px"><?php echo (int)$ti['qty']; ?> sold</div>
        </div>
      </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>

  <div class="card chart-card">
    <div class="card-header"><h3>Peak Order Hours</h3><span style="font-size:.72rem;color:var(--text-muted)">Orders by hour of day</span></div>
    <div class="chart-wrap"><canvas id="hoursChart" height="220"></canvas></div>
  </div>
</div>

<script>
const trendLabels  = <?php echo json_encode($trend_labels); ?>;
const trendRevenue = <?php echo json_encode($trend_revenue); ?>;
const statusData   = <?php echo json_encode($status_data); ?>;
const hourLabels   = <?php echo json_encode($hour_labels); ?>;
const hourData     = <?php echo json_encode($hour_data); ?>;

Chart.defaults.font.family = "'Plus Jakarta Sans', sans-serif";
Chart.defaults.color = '#64748B';

new Chart(document.getElementById('revenueChart'), {
  type: 'line',
  data: {
    labels: trendLabels,
    datasets: [{
      label: 'Revenue (₦)',
      data: trendRevenue,
      borderColor: '#225AE3',
      backgroundColor: 'rgba(34,90,227,.1)',
      fill: true,
      tension: .35,
      pointRadius: trendLabels.length > 14 ? 0 : 3,
      pointBackgroundColor: '#225AE3',
      borderWidth: 2.5
    }]
  },
  options: {
    responsive: true,
    maintainAspectRatio: false,
    plugins: { legend: { display: false } },
    scales: {
      y: { beginAtZero: true, grid: { color: '#F1F5F9' }, ticks: { callback: v => '₦' + (v>=1000 ? (v/1000)+'k' : v) } },
      x: { grid: { display: false } }
    }
  }
});

if (statusData.length) {
  new Chart(document.getElementById('statusChart'), {
    type: 'doughnut',
    data: {
      labels: statusData.map(s=>s.label),
      datasets: [{ data: statusData.map(s=>s.value), backgroundColor: statusData.map(s=>s.color), borderWidth: 0 }]
    },
    options: {
      responsive: true, maintainAspectRatio: false, cutout: '68%',
      plugins: { legend: { display: false } }
    }
  });
}

new Chart(document.getElementById('hoursChart'), {
  type: 'bar',
  data: {
    labels: hourLabels,
    datasets: [{ label: 'Orders', data: hourData, backgroundColor: '#4f79ea', borderRadius: 4, maxBarThickness: 22 }]
  },
  options: {
    responsive: true,
    maintainAspectRatio: false,
    plugins: { legend: { display: false } },
    scales: {
      y: { beginAtZero: true, grid: { color: '#F1F5F9' }, ticks: { precision: 0 } },
      x: { grid: { display: false }, ticks: { autoSkip: true, maxTicksLimit: 12 } }
    }
  }
});
</script>

<?php include("includes/footer.php"); ?>
