<?php
// admin/index.php - Admin Dashboard
require_once 'header.php';
require_once '../analytics.php';

$analytics = load_analytics_data();

// Generate last 7 days dates
$dates = array();
for ($i = 6; $i >= 0; $i--) {
    $dates[] = date('Y-m-d', strtotime("-$i days"));
}

$today = date('Y-m-d');
$today_stats = isset($analytics[$today]) ? $analytics[$today] : array('visitors' => 0, 'order_requests' => 0, 'items_sold' => 0, 'amount_sold' => 0.0);

// Extrapolate totals
$total_visitors = 0;
$total_items_sold = 0;
$total_revenue = 0.0;
$total_orders = 0;

foreach ($analytics as $date => $stats) {
    $total_visitors += isset($stats['visitors']) ? $stats['visitors'] : 0;
    $total_items_sold += isset($stats['items_sold']) ? $stats['items_sold'] : 0;
    $total_revenue += isset($stats['amount_sold']) ? $stats['amount_sold'] : 0.0;
    $total_orders += isset($stats['order_requests']) ? $stats['order_requests'] : 0;
}

// Build 7-day trend arrays
$visitor_trend = array();
$order_trend = array();
$sold_trend = array();

foreach ($dates as $date) {
    $visitor_trend[] = isset($analytics[$date]['visitors']) ? $analytics[$date]['visitors'] : 0;
    $order_trend[] = isset($analytics[$date]['order_requests']) ? $analytics[$date]['order_requests'] : 0;
    $sold_trend[] = isset($analytics[$date]['items_sold']) ? $analytics[$date]['items_sold'] : 0;
}

// Inline SVG chart helper
function render_trend_chart($data) {
    $width = 240;
    $height = 60;
    $count = count($data);
    if ($count < 2) return '';
    
    $max = max($data);
    $min = min($data);
    $range = $max - $min;
    if ($range == 0) $range = 1;
    
    $points = array();
    $step_x = $width / ($count - 1);
    
    $path = "";
    $fill = "M 0,$height";
    
    foreach ($data as $idx => $val) {
        $x = $idx * $step_x;
        // Keep points within 5 to height-5 padding bounds
        $y = $height - 8 - (($val - $min) / $range) * ($height - 16);
        $points[] = "$x,$y";
        $fill .= " L $x,$y";
    }
    
    $path = "M " . implode(" L ", $points);
    $fill .= " L $width,$height Z";
    
    $svg = '<svg viewBox="0 0 ' . $width . ' ' . $height . '" width="100%" height="' . $height . '" preserveAspectRatio="none">';
    $svg .= '<defs>';
    $svg .= '<linearGradient id="chart-grad" x1="0" y1="0" x2="0" y2="1">';
    $svg .= '  <stop offset="0%" stop-color="var(--text-primary)" stop-opacity="0.15"/>';
    $svg .= '  <stop offset="100%" stop-color="var(--text-primary)" stop-opacity="0.0"/>';
    $svg .= '</linearGradient>';
    $svg .= '</defs>';
    $svg .= '<path d="' . $fill . '" fill="url(#chart-grad)"/>';
    $svg .= '<path d="' . $path . '" fill="none" stroke="var(--text-primary)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>';
    $svg .= '</svg>';
    return $svg;
}
?>

<div class="container">
  <!-- Welcome and quick details -->
  <div style="margin-bottom: 32px;">
    <h1 style="font-size: 28px; font-weight: 600; letter-spacing: -0.02em;">Dashboard</h1>
    <p style="color: var(--text-secondary); font-size: 14px;">Real-time overview of your store's sales and engagement metrics.</p>
  </div>
  
  <!-- Metrics Dashboard Grid -->
  <div class="metrics-grid">
    <!-- Card 1: Daily Visitors -->
    <div class="card-glass metric-card">
      <div class="metric-header">
        <span class="metric-title">Today's Visitors</span>
        <span style="font-size: 11px; color: var(--text-secondary); background: var(--bg-secondary); padding: 2px 6px; border-radius: 4px;">Session Log</span>
      </div>
      <div>
        <div class="metric-value"><?php echo number_format($today_stats['visitors']); ?></div>
        <div style="font-size: 12px; color: var(--text-secondary); margin-top: 2px;">
          Total logged: <?php echo number_format($total_visitors); ?>
        </div>
      </div>
      <div class="metric-chart">
        <?php echo render_trend_chart($visitor_trend); ?>
      </div>
    </div>
    
    <!-- Card 2: Items Sold -->
    <div class="card-glass metric-card">
      <div class="metric-header">
        <span class="metric-title">Items Sold Today</span>
        <span style="font-size: 11px; color: var(--text-secondary); background: var(--bg-secondary); padding: 2px 6px; border-radius: 4px;">Completed Orders</span>
      </div>
      <div>
        <div class="metric-value"><?php echo number_format($today_stats['items_sold']); ?></div>
        <div style="font-size: 12px; color: var(--text-secondary); margin-top: 2px;">
          Revenue: $<?php echo number_format($today_stats['amount_sold'], 2); ?>
        </div>
      </div>
      <div class="metric-chart">
        <?php echo render_trend_chart($sold_trend); ?>
      </div>
    </div>
    
    <!-- Card 3: Order Requests -->
    <div class="card-glass metric-card">
      <div class="metric-header">
        <span class="metric-title">Order Requests Today</span>
        <span style="font-size: 11px; color: var(--text-secondary); background: var(--bg-secondary); padding: 2px 6px; border-radius: 4px;">Checkout Hits</span>
      </div>
      <div>
        <div class="metric-value"><?php echo number_format($today_stats['order_requests']); ?></div>
        <div style="font-size: 12px; color: var(--text-secondary); margin-top: 2px;">
          Total attempts: <?php echo number_format($total_orders); ?>
        </div>
      </div>
      <div class="metric-chart">
        <?php echo render_trend_chart($order_trend); ?>
      </div>
    </div>
  </div>
  
  <!-- Analytics Details Callout -->
  <div class="card-glass">
    <h2 style="font-size: 18px; font-weight: 600; margin-bottom: 12px;">Analytics Log Summary</h2>
    <div class="admin-table-container">
      <table class="admin-table">
        <thead>
          <tr>
            <th>Date</th>
            <th>Visitors</th>
            <th>Checkout Attempts</th>
            <th>Items Sold</th>
            <th>Estimated Sales</th>
          </tr>
        </thead>
        <tbody>
          <?php 
          // Reverse dates to show latest first
          $display_dates = array_reverse($dates);
          foreach ($display_dates as $date): 
            $day_data = isset($analytics[$date]) ? $analytics[$date] : array('visitors' => 0, 'order_requests' => 0, 'items_sold' => 0, 'amount_sold' => 0.0);
          ?>
            <tr>
              <td><strong><?php echo date('M d, Y', strtotime($date)); ?></strong><?php echo $date === $today ? ' <span style="font-size: 10px; font-weight:600; background: var(--border-color); padding: 1px 4px; border-radius:3px;">TODAY</span>' : ''; ?></td>
              <td><?php echo number_format($day_data['visitors']); ?></td>
              <td><?php echo number_format($day_data['order_requests']); ?></td>
              <td><?php echo number_format($day_data['items_sold']); ?></td>
              <td>$<?php echo number_format($day_data['amount_sold'], 2); ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
  
</div>

<?php
require_once 'footer.php';
?>
