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

// Stats for THIS restaurant only
$today = date('Y-m-d');

$total_orders   = $conn->prepare("SELECT COUNT(*) FROM orders WHERE restaurant_id=?"); $total_orders->bind_param("i",$__rid); $total_orders->execute(); $total_orders = $total_orders->get_result()->fetch_row()[0];
$today_orders   = $conn->prepare("SELECT COUNT(*) FROM orders WHERE restaurant_id=? AND DATE(created_at)=?"); $today_orders->bind_param("is",$__rid,$today); $today_orders->execute(); $today_orders = $today_orders->get_result()->fetch_row()[0];
$today_revenue  = $conn->prepare("SELECT COALESCE(SUM(total_amount),0) FROM orders WHERE restaurant_id=? AND payment_status='paid' AND DATE(created_at)=?"); $today_revenue->bind_param("is",$__rid,$today); $today_revenue->execute(); $today_revenue = $today_revenue->get_result()->fetch_row()[0];
$total_revenue  = $conn->prepare("SELECT COALESCE(SUM(total_amount),0) FROM orders WHERE restaurant_id=? AND payment_status='paid'"); $total_revenue->bind_param("i",$__rid); $total_revenue->execute(); $total_revenue = $total_revenue->get_result()->fetch_row()[0];
$menu_items_cnt = $conn->prepare("SELECT COUNT(*) FROM menu_items WHERE restaurant_id=? AND is_available=1"); $menu_items_cnt->bind_param("i",$__rid); $menu_items_cnt->execute(); $menu_items_cnt = $menu_items_cnt->get_result()->fetch_row()[0];
$staff_count    = $conn->prepare("SELECT COUNT(*) FROM users WHERE restaurant_id=? AND role IN('staff','waiter') AND status=1"); $staff_count->bind_param("i",$__rid); $staff_count->execute(); $staff_count = $staff_count->get_result()->fetch_row()[0];
$scans_today    = $conn->prepare("SELECT COUNT(*) FROM qr_scans WHERE restaurant_id=? AND DATE(scanned_at)=?"); $scans_today->bind_param("is",$__rid,$today); $scans_today->execute(); $scans_today = $scans_today->get_result()->fetch_row()[0];
$pending_cnt    = $__pending_orders;

// Live orders
$live_orders = $conn->prepare("SELECT o.*,u.name as customer_name,
    (SELECT COUNT(*) FROM order_items WHERE order_id=o.id) as item_count
    FROM orders o LEFT JOIN users u ON o.user_id=u.id
    WHERE o.restaurant_id=? AND o.order_status NOT IN('completed','cancelled')
    ORDER BY o.created_at DESC LIMIT 10");
$live_orders->bind_param("i",$__rid); $live_orders->execute();
$live_orders = $live_orders->get_result();

// Recent QR scans
$recent_scans = $conn->prepare("SELECT qs.*,u.name as customer_name FROM qr_scans qs LEFT JOIN users u ON qs.user_id=u.id WHERE qs.restaurant_id=? ORDER BY qs.scanned_at DESC LIMIT 8");
$recent_scans->bind_param("i",$__rid); $recent_scans->execute();
$recent_scans = $recent_scans->get_result();

// Last 7 days revenue
$weekly = $conn->prepare("SELECT DATE(created_at) as day, COALESCE(SUM(total_amount),0) as rev FROM orders WHERE restaurant_id=? AND payment_status='paid' AND created_at >= NOW()-INTERVAL 7 DAY GROUP BY DATE(created_at) ORDER BY day ASC");
$weekly->bind_param("i",$__rid); $weekly->execute();
$weekly_data = $weekly->get_result()->fetch_all(MYSQLI_ASSOC);
$days=[]; $revs=[];
for($i=6;$i>=0;$i--){ $d=date('Y-m-d',strtotime("-$i days")); $days[]=date('D',strtotime($d)); $revs[$d]=0; }
foreach($weekly_data as $wd){ $revs[$wd['day']]=$wd['rev']; }
$rev_vals = array_values($revs);
$max_rev = max(array_merge([1],$rev_vals));
?>

<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:26px;flex-wrap:wrap;gap:12px">
  <div>
    <h1 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em;margin-bottom:3px">Good <?php echo date('H')<12?'morning':(date('H')<18?'afternoon':'evening'); ?>, <?php echo htmlspecialchars(explode(' ',$__name)[0]); ?> 👋</h1>
    <p style="color:var(--text-muted);font-size:.85rem"><?php echo htmlspecialchars($__rest_name); ?> &bull; <?php echo date('l, F j, Y'); ?></p>
  </div>
  <div style="display:flex;gap:8px">
    <a href="orders.php" class="btn btn-primary btn-md">
      <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"/><rect x="9" y="3" width="6" height="4" rx="1"/></svg>
      Live Orders<?php if($pending_cnt>0) echo " ($pending_cnt)"; ?>
    </a>
  </div>
</div>

<!-- Stats Grid -->
<div class="grid-4" style="margin-bottom:24px">
  <?php
  $cards=[
    ['Today\'s Revenue','₦'.number_format($today_revenue,0),'#225AE3','#EEF3FD','M12 2v20M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6'],
    ['Today\'s Orders',$today_orders,'#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'],
    ['Pending Orders',$pending_cnt,'#F59E0B','#FFFBEB','M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z'],
    ['QR Scans Today',$scans_today,'#8B5CF6','#F5F3FF','M3 7V5a2 2 0 012-2h2M17 3h2a2 2 0 012 2v2M21 17v2a2 2 0 01-2 2h-2M7 21H5a2 2 0 01-2-2v-2 M9 9h6v6H9z'],
  ];
  foreach($cards as $i=>[$label,$val,$color,$bg,$icon]):
  ?>
  <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>

<!-- Secondary stats -->
<div class="grid-3" style="margin-bottom:24px">
  <div class="card" style="padding:18px 20px;display:flex;align-items:center;gap:14px">
    <div style="width:42px;height:42px;background:#F0FDF4;border-radius:12px;display:flex;align-items:center;justify-content:center;flex-shrink:0">
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#10B981" stroke-width="2" stroke-linecap="round"><path d="M12 2v20M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6"/></svg>
    </div>
    <div>
      <div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:3px">Total Revenue</div>
      <div style="font-size:1.25rem;font-weight:800;color:var(--success)">₦<?php echo number_format($total_revenue,0); ?></div>
    </div>
  </div>
  <div class="card" style="padding:18px 20px;display:flex;align-items:center;gap:14px">
    <div style="width:42px;height:42px;background:var(--primary-bg);border-radius:12px;display:flex;align-items:center;justify-content:center;flex-shrink:0">
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--primary)" stroke-width="2" stroke-linecap="round"><path d="M4 6h16M4 10h16M4 14h16M4 18h7"/></svg>
    </div>
    <div>
      <div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:3px">Menu Items</div>
      <div style="font-size:1.25rem;font-weight:800;color:var(--primary)"><?php echo $menu_items_cnt; ?></div>
    </div>
    <a href="menu.php" style="margin-left:auto;font-size:.75rem;color:var(--primary);font-weight:600">Manage →</a>
  </div>
  <div class="card" style="padding:18px 20px;display:flex;align-items:center;gap:14px">
    <div style="width:42px;height:42px;background:#FFFBEB;border-radius:12px;display:flex;align-items:center;justify-content:center;flex-shrink:0">
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#F59E0B" stroke-width="2" stroke-linecap="round"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/></svg>
    </div>
    <div>
      <div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:3px">Active Staff</div>
      <div style="font-size:1.25rem;font-weight:800;color:var(--warning)"><?php echo $staff_count; ?></div>
    </div>
    <?php if($is_admin): ?><a href="staff.php" style="margin-left:auto;font-size:.75rem;color:var(--primary);font-weight:600">Manage →</a><?php endif; ?>
  </div>
</div>

<!-- Revenue Chart + Live Orders -->
<div class="grid-2" style="margin-bottom:24px">

  <!-- 7-day Revenue Bar Chart -->
  <div class="card">
    <div class="card-header"><h3>Revenue — Last 7 Days</h3></div>
    <div class="card-body">
      <div style="display:flex;align-items:flex-end;gap:8px;height:120px;padding-bottom:8px">
        <?php foreach($rev_vals as $i=>$v):
          $h = $max_rev > 0 ? max(4, round(($v/$max_rev)*110)) : 4;
          $is_today = $i === 6;
        ?>
        <div style="flex:1;display:flex;flex-direction:column;align-items:center;gap:6px">
          <div style="font-size:.62rem;color:var(--text-muted);font-weight:600">₦<?php echo $v>0?number_format($v/1000,0).'k':'0'; ?></div>
          <div style="width:100%;height:<?php echo $h; ?>px;background:<?php echo $is_today?'var(--primary)':'var(--primary-bg)'; ?>;border-radius:6px 6px 0 0;transition:height .3s"></div>
          <div style="font-size:.68rem;color:<?php echo $is_today?'var(--primary)':'var(--text-muted)'; ?>;font-weight:<?php echo $is_today?'700':'500'; ?>"><?php echo $days[$i]; ?></div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>

  <!-- Recent QR Scans -->
  <div class="card">
    <div class="card-header">
      <h3>Recent QR Scans</h3>
      <a href="qr_scans.php" style="font-size:.75rem;color:var(--primary);font-weight:600">All scans →</a>
    </div>
    <?php if($recent_scans->num_rows===0): ?>
      <div style="padding:36px;text-align:center;color:var(--text-muted);font-size:.84rem">No scans yet today.</div>
    <?php else: ?>
      <?php while($s=$recent_scans->fetch_assoc()): ?>
      <div style="display:flex;align-items:center;gap:12px;padding:12px 20px;border-bottom:1px solid var(--border)">
        <div style="width:34px;height:34px;background:var(--primary-bg);border-radius:10px;display:flex;align-items:center;justify-content:center;flex-shrink:0">
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="var(--primary)" stroke-width="2" stroke-linecap="round"><path d="M3 7V5a2 2 0 012-2h2M17 3h2a2 2 0 012 2v2M21 17v2a2 2 0 01-2 2h-2M7 21H5a2 2 0 01-2-2v-2"/><rect x="7" y="7" width="10" height="10" rx="1"/></svg>
        </div>
        <div style="flex:1">
          <div style="font-size:.82rem;font-weight:600"><?php echo htmlspecialchars($s['customer_name']??'Guest'); ?></div>
          <div style="font-size:.7rem;color:var(--text-muted)"><?php echo date('g:i A', strtotime($s['scanned_at'])); ?></div>
        </div>
        <span class="badge badge-primary" style="font-size:.68rem">Scanned</span>
      </div>
      <?php endwhile; ?>
    <?php endif; ?>
  </div>
</div>

<!-- Live Orders Table -->
<div class="card">
  <div class="card-header">
    <h3>Live Orders</h3>
    <a href="orders.php" style="font-size:.75rem;color:var(--primary);font-weight:600">Manage all →</a>
  </div>
  <?php if($live_orders->num_rows===0): ?>
    <div style="padding:48px;text-align:center;color:var(--text-muted)">
      <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="var(--border)" stroke-width="1.5" stroke-linecap="round" style="margin:0 auto 12px;display:block"><path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"/><rect x="9" y="3" width="6" height="4" rx="1"/></svg>
      <p style="font-weight:700;font-size:.9rem;margin-bottom:4px">No active orders</p>
      <p style="font-size:.8rem">Orders from customers will appear here in real-time</p>
    </div>
  <?php else: ?>
    <div class="table-scroll">
<table class="data-table">
    <thead><tr><th>Order</th><th>Customer</th><th>Table</th><th>Items</th><th>Amount</th><th>Status</th><th>Time</th><th>Action</th></tr></thead>
    <tbody>
    <?php while($o=$live_orders->fetch_assoc()):
      $sc=['pending'=>'badge-warning','accepted'=>'badge-primary','preparing'=>'badge-primary','ready'=>'badge-success','served'=>'badge-info','completed'=>'badge-success','cancelled'=>'badge-error'];
    ?>
      <tr>
        <td style="font-weight:700;color:var(--primary)">#<?php echo str_pad($o['id'],4,'0',STR_PAD_LEFT); ?></td>
        <td style="font-size:.83rem"><?php echo htmlspecialchars($o['customer_name']??'Guest'); ?></td>
        <td style="font-size:.82rem"><?php echo $o['table_number']?'Table '.$o['table_number']:'—'; ?></td>
        <td style="font-weight:600"><?php echo $o['item_count']; ?></td>
        <td style="font-weight:700">₦<?php echo number_format($o['total_amount'],0); ?></td>
        <td><span class="badge <?php echo $sc[$o['order_status']]??'badge-muted'; ?>"><?php echo ucfirst($o['order_status']); ?></span></td>
        <td style="font-size:.75rem;color:var(--text-muted)"><?php echo date('g:i A',strtotime($o['created_at'])); ?></td>
        <td><a href="orders.php?id=<?php echo $o['id']; ?>" class="btn btn-primary btn-sm">View</a></td>
      </tr>
    <?php endwhile; ?>
    </tbody>
  </table>
</div>
  <?php endif; ?>
</div>

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