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

// Platform stats
$stats = [];

$stats['restaurants']       = $conn->query("SELECT COUNT(*) FROM restaurants WHERE status=1")->fetch_row()[0];
$stats['customers']         = $conn->query("SELECT COUNT(*) FROM users WHERE role='customer' AND status=1")->fetch_row()[0];
$stats['total_orders']      = $conn->query("SELECT COUNT(*) FROM orders")->fetch_row()[0];
$stats['pending_orders']    = $conn->query("SELECT COUNT(*) FROM orders WHERE order_status='pending'")->fetch_row()[0];
$stats['revenue']           = $conn->query("SELECT COALESCE(SUM(total_amount),0) FROM orders WHERE payment_status='paid'")->fetch_row()[0];
$stats['wallet_total']      = $conn->query("SELECT COALESCE(SUM(balance),0) FROM wallets")->fetch_row()[0];
$stats['withdrawals_pending']= $conn->query("SELECT COUNT(*) FROM withdrawals WHERE status='pending'")->fetch_row()[0];
$stats['today_orders']      = $conn->query("SELECT COUNT(*) FROM orders WHERE DATE(created_at)=CURDATE()")->fetch_row()[0];

// Super admin wallet
$sa_wallet = $conn->query("SELECT balance FROM wallets WHERE user_id={$uid} AND wallet_type='super_admin' LIMIT 1")->fetch_row();
$stats['sa_wallet_balance'] = $sa_wallet ? (float)$sa_wallet[0] : 0.00;

// Today's commission
$stats['today_commission'] = $conn->query(
    "SELECT COALESCE(SUM(amount),0) FROM wallet_transactions
     WHERE user_id={$uid} AND wallet_type='super_admin' AND type='credit' AND DATE(created_at)=CURDATE()"
)->fetch_row()[0];

// Recent restaurants
$recent_restaurants = $conn->query("
    SELECT r.*, u.name as admin_name,
           (SELECT COUNT(*) FROM orders o WHERE o.restaurant_id=r.id) as order_count,
           COALESCE((SELECT w.balance FROM wallets w WHERE w.restaurant_id=r.id AND w.wallet_type='restaurant' LIMIT 1),0) as wallet_balance
    FROM restaurants r
    LEFT JOIN users u ON u.restaurant_id=r.id AND u.role='restaurant_admin'
    ORDER BY r.created_at DESC LIMIT 5
");

// Recent orders (all restaurants)
$recent_orders = $conn->query("
    SELECT o.*, u.name as customer_name, r.name as restaurant_name
    FROM orders o
    LEFT JOIN users u ON o.user_id=u.id
    LEFT JOIN restaurants r ON o.restaurant_id=r.id
    ORDER BY o.created_at DESC LIMIT 8
");

// Recent transactions
$recent_txns = $conn->query("
    SELECT wt.*, u.name as user_name
    FROM wallet_transactions wt
    LEFT JOIN users u ON wt.user_id=u.id
    ORDER BY wt.created_at DESC LIMIT 6
");
?>

<!-- Page Header -->
<div style="display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:28px;flex-wrap:wrap;gap:16px">
  <div>
    <h1 style="font-size:1.5rem;font-weight:800;letter-spacing:-.03em;margin-bottom:4px">
      Welcome back, <?php echo htmlspecialchars(explode(' ',$__name)[0]); ?> 👋
    </h1>
    <p style="color:var(--text-muted);font-size:.875rem">
      Here's your platform overview — <?php echo date('l, F j, Y'); ?>
    </p>
  </div>
  <a href="restaurants.php?action=create" class="btn btn-primary btn-md">
    <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v8M8 12h8"/></svg>
    Add Restaurant
  </a>
</div>

<!-- Super Admin Wallet Banner -->
<a href="my_wallet.php" style="display:block;text-decoration:none;margin-bottom:24px">
  <div style="background:linear-gradient(135deg,#225AE3 0%,#4f79ea 50%,#7c9ef0 100%);border-radius:16px;padding:20px 28px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:16px;position:relative;overflow:hidden;cursor:pointer;transition:opacity .2s" onmouseover="this.style.opacity='.92'" onmouseout="this.style.opacity='1'">
    <div style="position:absolute;top:-20px;right:-10px;width:130px;height:130px;background:rgba(255,255,255,.07);border-radius:50%"></div>
    <div style="position:absolute;bottom:-30px;left:30%;width:160px;height:160px;background:rgba(255,255,255,.05);border-radius:50%"></div>
    <div style="display:flex;align-items:center;gap:16px;position:relative;z-index:1">
      <div style="width:48px;height:48px;background:rgba(255,255,255,.2);border-radius:14px;display:flex;align-items:center;justify-content:center;flex-shrink:0">
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round"><path d="M21 12V7H5a2 2 0 010-4h15a1 1 0 011 1v4"/><path d="M3 5v14a2 2 0 002 2h16v-5"/><path d="M18 12a2 2 0 000 4h4v-4z"/></svg>
      </div>
      <div>
        <div style="font-size:.72rem;font-weight:700;color:rgba(255,255,255,.75);text-transform:uppercase;letter-spacing:.1em;margin-bottom:3px">Platform Wallet (10% Commission)</div>
        <div style="font-size:1.8rem;font-weight:800;color:#fff;letter-spacing:-.03em">₦<?php echo number_format($stats['sa_wallet_balance'], 2); ?></div>
      </div>
    </div>
    <div style="display:flex;gap:16px;position:relative;z-index:1;flex-wrap:wrap">
      <div style="background:rgba(255,255,255,.15);border-radius:10px;padding:10px 16px;text-align:center">
        <div style="font-size:.65rem;color:rgba(255,255,255,.7);font-weight:600;text-transform:uppercase;letter-spacing:.08em;margin-bottom:2px">Today</div>
        <div style="font-size:1rem;font-weight:800;color:#fff">+₦<?php echo number_format($stats['today_commission'], 2); ?></div>
      </div>
      <div style="background:rgba(255,255,255,.15);border-radius:10px;padding:10px 16px;display:flex;align-items:center;gap:8px">
        <span style="font-size:.85rem;font-weight:700;color:#fff">Manage Wallet</span>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2.5" stroke-linecap="round"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
      </div>
    </div>
  </div>
</a>

<!-- Stats Grid -->
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:28px">
  <?php
  $stat_cards = [
    ['label'=>'Total Restaurants','value'=>$stats['restaurants'],'fmt'=>'num','color'=>'#225AE3','bg'=>'#EEF3FD','icon'=>'M3 11l19-9-9 19-2-8-8-2z'],
    ['label'=>'Total Customers','value'=>$stats['customers'],'fmt'=>'num','color'=>'#10B981','bg'=>'#F0FDF4','icon'=>'M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2 M9 7a4 4 0 100 8 4 4 0 000-8z'],
    ['label'=>'Total Orders','value'=>$stats['total_orders'],'fmt'=>'num','color'=>'#F59E0B','bg'=>'#FFFBEB','icon'=>'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2 M9 3a2 2 0 012-2h2a2 2 0 012 2'],
    ['label'=>'Platform Revenue','value'=>$stats['revenue'],'fmt'=>'money','color'=>'#8B5CF6','bg'=>'#F5F3FF','icon'=>'M7 20V4l10 16V4M4 10h16M4 14h16'],
  ];
  foreach($stat_cards as $sc):
    $display = $sc['fmt']==='money' ? '₦'.number_format($sc['value'],0) : number_format($sc['value']);
  ?>
  <div class="card" style="padding:20px;border-top:3px solid <?php echo $sc['color']; ?>">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:14px">
      <span style="font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted)"><?php echo $sc['label']; ?></span>
      <div style="width:34px;height:34px;background:<?php echo $sc['bg']; ?>;border-radius:10px;display:flex;align-items:center;justify-content:center;flex-shrink:0">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="<?php echo $sc['color']; ?>" stroke-width="2" stroke-linecap="round"><path d="<?php echo $sc['icon']; ?>"/></svg>
      </div>
    </div>
    <div style="font-size:1.7rem;font-weight:800;letter-spacing:-.03em;color:<?php echo $sc['color']; ?>"><?php echo $display; ?></div>
  </div>
  <?php endforeach; ?>
</div>

<!-- Secondary Stats -->
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:28px">
  <div class="card" style="padding:16px 20px;display:flex;align-items:center;gap:14px">
    <div style="width:40px;height:40px;background:var(--warning-bg);border-radius:12px;display:flex;align-items:center;justify-content:center;flex-shrink:0">
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--warning)" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
    </div>
    <div>
      <div style="font-size:.7rem;color:var(--text-muted);font-weight:600;text-transform:uppercase;letter-spacing:.08em;margin-bottom:3px">Pending Orders</div>
      <div style="font-size:1.3rem;font-weight:800;color:var(--warning)"><?php echo $stats['pending_orders']; ?></div>
    </div>
  </div>
  <div class="card" style="padding:16px 20px;display:flex;align-items:center;gap:14px">
    <div style="width:40px;height:40px;background:var(--primary-bg);border-radius:12px;display:flex;align-items:center;justify-content:center;flex-shrink:0">
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--primary)" stroke-width="2" stroke-linecap="round"><path d="M21 12V7H5a2 2 0 010-4h15a1 1 0 011 1v4"/><path d="M3 5v14a2 2 0 002 2h16v-5"/><path d="M18 12a2 2 0 000 4h4v-4z"/></svg>
    </div>
    <div>
      <div style="font-size:.7rem;color:var(--text-muted);font-weight:600;text-transform:uppercase;letter-spacing:.08em;margin-bottom:3px">Total in Wallets</div>
      <div style="font-size:1.3rem;font-weight:800;color:var(--primary)">₦<?php echo number_format($stats['wallet_total'],0); ?></div>
    </div>
  </div>
  <div class="card" style="padding:16px 20px;display:flex;align-items:center;gap:14px">
    <div style="width:40px;height:40px;background:var(--error-bg);border-radius:12px;display:flex;align-items:center;justify-content:center;flex-shrink:0">
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--error)" stroke-width="2" stroke-linecap="round"><path d="M12 5v14m-7-7l7 7 7-7"/></svg>
    </div>
    <div>
      <div style="font-size:.7rem;color:var(--text-muted);font-weight:600;text-transform:uppercase;letter-spacing:.08em;margin-bottom:3px">Pending Withdrawals</div>
      <div style="font-size:1.3rem;font-weight:800;color:var(--error)"><?php echo $stats['withdrawals_pending']; ?></div>
    </div>
  </div>
  <div class="card" style="padding:16px 20px;display:flex;align-items:center;gap:14px">
    <div style="width:40px;height:40px;background:var(--success-bg);border-radius:12px;display:flex;align-items:center;justify-content:center;flex-shrink:0">
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--success)" stroke-width="2" stroke-linecap="round"><path d="M7 20V4l10 16V4M4 10h16M4 14h16"/></svg>
    </div>
    <div>
      <div style="font-size:.7rem;color:var(--text-muted);font-weight:600;text-transform:uppercase;letter-spacing:.08em;margin-bottom:3px">Today's Orders</div>
      <div style="font-size:1.3rem;font-weight:800;color:var(--success)"><?php echo $stats['today_orders']; ?></div>
    </div>
  </div>
</div>

<!-- Content Row -->
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px">

  <!-- Restaurants with wallet balances -->
  <div class="card">
    <div class="card-header">
      <h3>Restaurants</h3>
      <a href="restaurants.php" style="font-size:.78rem;color:var(--primary);font-weight:600">View all →</a>
    </div>
    <?php if ($recent_restaurants->num_rows === 0): ?>
      <div style="padding:40px;text-align:center;color:var(--text-muted);font-size:.85rem">No restaurants yet. <a href="restaurants.php?action=create" style="color:var(--primary);font-weight:600">Add one →</a></div>
    <?php else: ?>
    <div style="overflow-x:auto">
    <table class="data-table">
      <thead><tr><th>Restaurant</th><th>Admin</th><th>Wallet</th><th>Status</th></tr></thead>
      <tbody>
      <?php while($r = $recent_restaurants->fetch_assoc()): ?>
        <tr>
          <td>
            <div style="font-weight:700;font-size:.85rem"><?php echo htmlspecialchars($r['name']); ?></div>
            <div style="font-size:.72rem;color:var(--text-muted)"><?php echo $r['order_count']; ?> orders</div>
          </td>
          <td style="font-size:.82rem"><?php echo htmlspecialchars($r['admin_name'] ?? '—'); ?></td>
          <td style="font-weight:700;color:var(--success);font-size:.82rem">₦<?php echo number_format($r['wallet_balance'],0); ?></td>
          <td><span class="badge <?php echo $r['status']?'badge-success':'badge-error'; ?>"><?php echo $r['status']?'Active':'Inactive'; ?></span></td>
        </tr>
      <?php endwhile; ?>
      </tbody>
    </table>
    </div>
    <?php endif; ?>
  </div>

  <!-- Recent Transactions -->
  <div class="card">
    <div class="card-header">
      <h3>Recent Transactions</h3>
      <a href="transactions.php" style="font-size:.78rem;color:var(--primary);font-weight:600">View all →</a>
    </div>
    <?php if ($recent_txns->num_rows === 0): ?>
      <div style="padding:40px;text-align:center;color:var(--text-muted);font-size:.85rem">No transactions yet.</div>
    <?php else: ?>
      <?php while($t = $recent_txns->fetch_assoc()):
        $is_credit = $t['type']==='credit';
        $tc = $is_credit ? 'var(--success)' : 'var(--error)';
        $tb = $is_credit ? 'var(--success-bg)' : 'var(--error-bg)';
        $ta = $is_credit ? 'M12 19V5m0 0l-7 7m7-7l7 7' : 'M12 5v14m0 0l7-7m-7 7l-7-7';
      ?>
      <div style="display:flex;align-items:center;gap:12px;padding:13px 20px;border-bottom:1px solid var(--border)">
        <div style="width:34px;height:34px;border-radius:10px;background:<?php echo $tb; ?>;display:flex;align-items:center;justify-content:center;flex-shrink:0">
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="<?php echo $tc; ?>" stroke-width="2.5" stroke-linecap="round"><path d="<?php echo $ta; ?>"/></svg>
        </div>
        <div style="flex:1;min-width:0">
          <div style="font-size:.82rem;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?php echo htmlspecialchars($t['user_name'] ?? '—'); ?></div>
          <div style="font-size:.7rem;color:var(--text-muted)"><?php echo date('M j, g:i A', strtotime($t['created_at'])); ?></div>
        </div>
        <div style="font-weight:700;font-size:.85rem;color:<?php echo $tc; ?>;flex-shrink:0"><?php echo $is_credit?'+':'-'; ?>₦<?php echo number_format($t['amount'],0); ?></div>
      </div>
      <?php endwhile; ?>
    <?php endif; ?>
  </div>

</div>

<!-- Recent Orders -->
<div class="card">
  <div class="card-header">
    <h3>Recent Orders — All Restaurants</h3>
    <a href="orders.php" style="font-size:.78rem;color:var(--primary);font-weight:600">View all →</a>
  </div>
  <?php if ($recent_orders->num_rows === 0): ?>
    <div style="padding:40px;text-align:center;color:var(--text-muted);font-size:.85rem">No orders yet.</div>
  <?php else: ?>
  <div style="overflow-x:auto">
  <table class="data-table">
    <thead><tr><th>Order</th><th>Customer</th><th>Restaurant</th><th>Amount</th><th>Payment</th><th>Status</th><th>Date</th></tr></thead>
    <tbody>
    <?php while($o = $recent_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'];
      $pc = ['paid'=>'badge-success','pending'=>'badge-warning','failed'=>'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:.82rem"><?php echo htmlspecialchars($o['customer_name'] ?? '—'); ?></td>
        <td style="font-size:.82rem"><?php echo htmlspecialchars($o['restaurant_name'] ?? '—'); ?></td>
        <td style="font-weight:700">₦<?php echo number_format($o['total_amount'],0); ?></td>
        <td><span class="badge <?php echo $pc[$o['payment_status']]??'badge-muted'; ?>"><?php echo ucfirst($o['payment_status']); ?></span></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:.78rem;color:var(--text-muted)"><?php echo date('M j, Y', strtotime($o['created_at'])); ?></td>
      </tr>
    <?php endwhile; ?>
    </tbody>
  </table>
  </div>
  <?php endif; ?>
</div>

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