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

$date_from = $_GET['date_from'] ?? date('Y-m-01');
$date_to   = $_GET['date_to']   ?? date('Y-m-d');

// Period totals
$rev = $conn->prepare("SELECT
    COALESCE(SUM(total_amount),0) as total,
    COALESCE(SUM(CASE WHEN payment_method='wallet'   THEN total_amount ELSE 0 END),0) as wallet_rev,
    COALESCE(SUM(CASE WHEN payment_method='paystack' THEN total_amount ELSE 0 END),0) as paystack_rev,
    COUNT(*) as paid_orders,
    AVG(total_amount) as avg_order
    FROM orders WHERE restaurant_id=? AND payment_status='paid' AND DATE(created_at) BETWEEN ? AND ?");
$rev->bind_param("iss", $__rid, $date_from, $date_to); $rev->execute();
$rev = $rev->get_result()->fetch_assoc();

$today_rev = $conn->prepare("SELECT COALESCE(SUM(total_amount),0) FROM orders WHERE restaurant_id=? AND payment_status='paid' AND DATE(created_at)=CURDATE()");
$today_rev->bind_param("i",$__rid); $today_rev->execute();
$today_rev = $today_rev->get_result()->fetch_row()[0];

$unpaid = $conn->prepare("SELECT COUNT(*),COALESCE(SUM(total_amount),0) FROM orders WHERE restaurant_id=? AND payment_status='pending' AND order_status NOT IN('cancelled') AND DATE(created_at) BETWEEN ? AND ?");
$unpaid->bind_param("iss",$__rid,$date_from,$date_to); $unpaid->execute();
$unpaid = $unpaid->get_result()->fetch_row();

// Best-selling items this period
$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 5");
$top_items->bind_param("iss",$__rid,$date_from,$date_to); $top_items->execute();
$top_items = $top_items->get_result();

// Orders list
$orders = $conn->prepare("SELECT o.*,u.name as customer_name FROM orders o LEFT JOIN users u ON o.user_id=u.id WHERE o.restaurant_id=? AND o.payment_status='paid' AND DATE(o.created_at) BETWEEN ? AND ? ORDER BY o.created_at DESC");
$orders->bind_param("iss",$__rid,$date_from,$date_to); $orders->execute();
$orders = $orders->get_result();

$sc=['pending'=>'badge-warning','accepted'=>'badge-primary','preparing'=>'badge-purple','ready'=>'badge-success','served'=>'badge-info','completed'=>'badge-success','cancelled'=>'badge-error'];
?>

<div style="display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap;gap:12px">
  <div>
    <h1 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em;margin-bottom:3px">Payments</h1>
    <p style="color:var(--text-muted);font-size:.875rem">Revenue and payment breakdown — <?php echo htmlspecialchars($__rest_name); ?></p>
  </div>
  <form method="GET" style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
    <input type="date" name="date_from" value="<?php echo $date_from; ?>" style="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">
    <span style="color:var(--text-muted);font-size:.8rem">to</span>
    <input type="date" name="date_to" value="<?php echo $date_to; ?>" style="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">
    <button type="submit" class="btn btn-primary btn-sm">Filter</button>
    <a href="payments.php" class="btn btn-secondary btn-sm">Reset</a>
  </form>
</div>

<!-- Stats Grid -->
<div class="grid-4" style="margin-bottom:24px">
  <div class="card" style="padding:18px 20px;border-top:3px solid var(--success)">
    <div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:8px">Period Revenue</div>
    <div style="font-size:1.45rem;font-weight:800;color:var(--success)">₦<?php echo number_format($rev['total'],0); ?></div>
    <div style="font-size:.7rem;color:var(--text-muted);margin-top:4px"><?php echo date('M j',strtotime($date_from)).' – '.date('M j, Y',strtotime($date_to)); ?></div>
  </div>
  <div class="card" style="padding:18px 20px;border-top:3px solid var(--primary)">
    <div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:8px">Today's Revenue</div>
    <div style="font-size:1.45rem;font-weight:800;color:var(--primary)">₦<?php echo number_format($today_rev,0); ?></div>
  </div>
  <div class="card" style="padding:18px 20px;border-top:3px solid var(--warning)">
    <div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:8px">Wallet Revenue</div>
    <div style="font-size:1.45rem;font-weight:800;color:var(--warning)">₦<?php echo number_format($rev['wallet_rev'],0); ?></div>
  </div>
  <div class="card" style="padding:18px 20px;border-top:3px solid #8B5CF6">
    <div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:8px">Avg. Order Value</div>
    <div style="font-size:1.45rem;font-weight:800;color:#8B5CF6">₦<?php echo number_format($rev['avg_order'] ?? 0,0); ?></div>
  </div>
</div>

<div class="grid-2" style="margin-bottom:24px;align-items:start">

  <!-- Payment Method Split -->
  <div class="card">
    <div class="card-header"><h3>Payment Methods</h3></div>
    <div class="card-body">
      <?php if ($rev['total'] > 0):
        $wp = round(($rev['wallet_rev']/$rev['total'])*100);
        $pp = 100 - $wp;
      ?>
      <div style="margin-bottom:16px">
        <div style="display:flex;justify-content:space-between;margin-bottom:6px;font-size:.82rem">
          <span style="font-weight:600;color:var(--primary)">Wallet</span>
          <span style="font-weight:700">₦<?php echo number_format($rev['wallet_rev'],0); ?> (<?php echo $wp; ?>%)</span>
        </div>
        <div style="height:10px;background:var(--bg);border-radius:20px;overflow:hidden">
          <div style="height:100%;width:<?php echo $wp; ?>%;background:var(--primary);border-radius:20px;transition:width .5s"></div>
        </div>
      </div>
      <div>
        <div style="display:flex;justify-content:space-between;margin-bottom:6px;font-size:.82rem">
          <span style="font-weight:600;color:var(--info)">Paystack</span>
          <span style="font-weight:700">₦<?php echo number_format($rev['paystack_rev'],0); ?> (<?php echo $pp; ?>%)</span>
        </div>
        <div style="height:10px;background:var(--bg);border-radius:20px;overflow:hidden">
          <div style="height:100%;width:<?php echo $pp; ?>%;background:var(--info);border-radius:20px;transition:width .5s"></div>
        </div>
      </div>
      <div style="margin-top:16px;padding-top:14px;border-top:1px solid var(--border);display:flex;justify-content:space-between;font-size:.85rem">
        <span style="color:var(--text-muted)">Total paid orders</span>
        <span style="font-weight:700"><?php echo $rev['paid_orders']; ?></span>
      </div>
      <?php else: ?>
      <p style="text-align:center;color:var(--text-muted);padding:24px 0;font-size:.84rem">No paid orders in this period</p>
      <?php endif; ?>
    </div>
  </div>

  <!-- Top Items -->
  <div class="card">
    <div class="card-header"><h3>Top Selling Items</h3></div>
    <div class="card-body" style="padding:0">
      <?php if ($top_items->num_rows === 0): ?>
        <p style="text-align:center;color:var(--text-muted);padding:32px;font-size:.84rem">No data yet</p>
      <?php else: $rank=1; while ($ti = $top_items->fetch_assoc()): ?>
      <div style="display:flex;align-items:center;gap:12px;padding:13px 20px;border-bottom:1px solid var(--border)">
        <div style="width:26px;height:26px;border-radius:50%;background:<?php echo $rank===1?'var(--warning)':($rank===2?'var(--text-muted)':'var(--bg)'); ?>;display:flex;align-items:center;justify-content:center;font-size:.7rem;font-weight:800;color:<?php echo $rank<=2?'#fff':'var(--text-muted)'; ?>;flex-shrink:0"><?php echo $rank++; ?></div>
        <div style="flex:1;min-width:0">
          <div style="font-size:.84rem;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?php echo htmlspecialchars($ti['item_name']); ?></div>
          <div style="font-size:.7rem;color:var(--text-muted)"><?php echo $ti['qty']; ?> sold</div>
        </div>
        <div style="font-weight:700;color:var(--success);font-size:.84rem">₦<?php echo number_format($ti['revenue'],0); ?></div>
      </div>
      <?php endwhile; endif; ?>
    </div>
  </div>

</div>

<!-- Paid Orders Table -->
<div class="card">
  <div class="card-header">
    <h3>Paid Orders</h3>
    <span style="font-size:.78rem;color:var(--text-muted)"><?php echo $orders->num_rows; ?> records</span>
  </div>
  <?php if ($orders->num_rows === 0): ?>
    <div style="padding:48px;text-align:center;color:var(--text-muted)">
      <p style="font-weight:700;margin-bottom:4px">No paid orders in this period</p>
    </div>
  <?php else: ?>
    <div class="table-scroll">
<table class="data-table">
    <thead><tr><th>Order</th><th>Customer</th><th>Table</th><th>Method</th><th>Amount</th><th>Status</th><th>Date & Time</th></tr></thead>
    <tbody>
    <?php while ($o = $orders->fetch_assoc()): ?>
    <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><span class="badge <?php echo ($o['payment_method']==='wallet')?'badge-primary':'badge-info'; ?>"><?php echo ucfirst($o['payment_method']); ?></span></td>
      <td style="font-weight:800;color:var(--success)">₦<?php echo number_format($o['total_amount'],2); ?></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);white-space:nowrap"><?php echo date('M j, Y g:i A', strtotime($o['created_at'])); ?></td>
    </tr>
    <?php endwhile; ?>
    </tbody>
  </table>
</div>
  <?php endif; ?>
</div>

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