<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

// ==================== FILTERS ====================
$status_filter = $_GET['status'] ?? '';
$from = $_GET['from'] ?? date('Y-m-d');
$to = $_GET['to'] ?? date('Y-m-d');

$where = "WHERE 1=1 ";

if($status_filter){
    $status = $conn->real_escape_string($status_filter);
    $where .= " AND ro.status='$status'";
}

// Default = today's orders if no manual range
if($from && $to){
    $f = $conn->real_escape_string($from);
    $t = $conn->real_escape_string($to);
    $where .= " AND DATE(ro.created_at) BETWEEN '$f' AND '$t'";
}else{
    $where .= " AND DATE(ro.created_at)=CURDATE()";
}

// ==================== FETCH ORDERS ====================
$query = "SELECT ro.*, u.username as waiter_name, c.name as customer_name 
          FROM restaurant_orders ro
          LEFT JOIN users u ON ro.waiter_id = u.id
          LEFT JOIN guests c ON ro.customer_id = c.id
          $where
          ORDER BY ro.id DESC";

$orders = $conn->query($query);

// ==================== DASHBOARD DATA ====================
$total_orders = $conn->query("SELECT COUNT(*) t FROM restaurant_orders")->fetch_assoc()['t'];

$today_orders = $conn->query("
    SELECT COUNT(*) t FROM restaurant_orders 
    WHERE DATE(created_at)=CURDATE()
")->fetch_assoc()['t'];

$today_sales = $conn->query("
    SELECT SUM(grand_total) t FROM restaurant_orders 
    WHERE DATE(created_at)=CURDATE() AND status='PAID'
")->fetch_assoc()['t'] ?? 0;

$paid_orders = $conn->query("
    SELECT COUNT(*) t FROM restaurant_orders 
    WHERE status='PAID'
")->fetch_assoc()['t'];
?>

<div class="container mt-4">

<div class="welcome-msg">
<i class="fa fa-user-circle"></i> Welcome, 
<strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
</div>

<button class="btn btn-secondary btn-custom" onclick="history.back()">
<i class="fa fa-arrow-left"></i> Back
</button>

<a href="restaurant_pos.php" class="btn btn-sm btn-primary">
Make Restaurant Order
</a>

<h3 class="text-center">Restaurant Orders List</h3>
<hr>

<!-- ================= DASHBOARD CARDS ================= -->
<div class="row mb-4">

<div class="col-md-3">
<div class="card shadow-sm border-primary">
<div class="card-body text-center">
<h6>Total Orders</h6>
<h3><?= $total_orders ?></h3>
</div>
</div>
</div>

<div class="col-md-3">
<div class="card shadow-sm border-success">
<div class="card-body text-center">
<h6>Today's Orders</h6>
<h3><?= $today_orders ?></h3>
</div>
</div>
</div>

<div class="col-md-3">
<div class="card shadow-sm border-warning">
<div class="card-body text-center">
<h6>Today's Sales</h6>
<h3><?= number_format($today_sales,2) ?></h3>
</div>
</div>
</div>

<div class="col-md-3">
<div class="card shadow-sm border-dark">
<div class="card-body text-center">
<h6>Paid Orders</h6>
<h3><?= $paid_orders ?></h3>
</div>
</div>
</div>

</div>

<!-- ================= FILTERS ================= -->
<div class="mb-3">
<form method="GET" class="row g-2">

<div class="col-md-3">
<select name="status" class="form-control">
<option value="">-- All Statuses --</option>
<option value="IN_KITCHEN" <?= $status_filter=='IN_KITCHEN'?'selected':'' ?>>In Kitchen</option>
<option value="READY" <?= $status_filter=='READY'?'selected':'' ?>>Ready</option>
<option value="SERVED" <?= $status_filter=='SERVED'?'selected':'' ?>>Served</option>
<option value="PAID" <?= $status_filter=='PAID'?'selected':'' ?>>Paid</option>
</select>
</div>

<div class="col-md-2">
<input type="date" name="from" class="form-control" value="<?= $from ?>">
</div>

<div class="col-md-2">
<input type="date" name="to" class="form-control" value="<?= $to ?>">
</div>

<div class="col-md-2">
<button class="btn btn-primary w-100">
<i class="fa fa-search"></i> Filter
</button>
</div>

<div class="col-md-2">
<a href="restaurant_orders.php" class="btn btn-secondary w-100">
Reset
</a>
</div>

</form>
</div>

<!-- ================= REMINDER ================= -->
<div class="checkout-reminder">
<i class="fa fa-exclamation-triangle"></i>
<strong>Reminder:</strong>
Make sure you click <b>Ready</b> then <b>Served</b> and then 
<b>Collect Payment</b> to make sure it balances
</div>

<style>
.checkout-reminder{
background: linear-gradient(135deg,#fff3cd,#ffe69c);
border-left:6px solid #ffc107;
border:2px solid #dc3545;
padding:14px 18px;
border-radius:10px;
margin-bottom:15px;
display:flex;
gap:10px;
align-items:center;
}

.card{
border-radius:10px;
}
</style>

<!-- ================= ORDERS TABLE ================= -->
<table class="table table-bordered table-striped">

<thead class="bg-dark text-white">
<tr>
<th>#</th>
<th>Order ID</th>
<th>Waiter</th>
<th>Customer</th>
<th>Subtotal</th>
<th>Discount</th>
<th>Grand Total</th>
<th>Date</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>

<tbody>
<?php
$i=1;
while($order=$orders->fetch_assoc()):
?>

<tr>

<td><?= $i++ ?></td>
<td><?= $order['id'] ?></td>
<td><?= $order['waiter_name'] ?></td>
<td><?= $order['customer_name'] ?? 'Walk-in' ?></td>
<td><?= number_format($order['subtotal'],2) ?></td>
<td><?= number_format($order['discount'],2) ?></td>
<td><?= number_format($order['grand_total'],2) ?></td>
<td><?= $order['created_at'] ?></td>

<td>
<?php
if($order['status']=='IN_KITCHEN') echo "<span class='badge bg-warning'>In Kitchen</span>";
if($order['status']=='READY') echo "<span class='badge bg-success'>Ready</span>";
if($order['status']=='SERVED') echo "<span class='badge bg-primary'>Served</span>";
if($order['status']=='PAID') echo "<span class='badge bg-dark'>Paid</span>";
?>
</td>

<td>

<a href="restaurant_order_view.php?order_id=<?= $order['id'] ?>" 
class="btn btn-info btn-sm mb-1">View/Print</a>

<?php if($order['status']=='IN_KITCHEN'): ?>
<a href="restaurant_order_update_status.php?order_id=<?= $order['id'] ?>&status=READY"
class="btn btn-success btn-sm mb-1"
onclick="return confirm('Mark this order as Ready?');">
✅ Ready
</a>
<?php endif; ?>

<?php if($order['status']=='READY'): ?>
<a href="restaurant_order_update_status.php?order_id=<?= $order['id'] ?>&status=SERVED"
class="btn btn-primary btn-sm mb-1"
onclick="return confirm('Mark this order as Served?');">
🍽️ Served
</a>
<?php endif; ?>

<?php if($order['status']=='PAID'): ?>
<span style="color:red;font-weight:bold;">
<i class="fas fa-check-circle"></i> PAID
</span>
<?php endif; ?>

<?php if($order['status']=='SERVED'): ?>
<a href="print_restaurant_receipt.php?order_id=<?= $order['id'] ?>" 
target="_blank"
class="btn btn-dark btn-sm mb-1">
🧾 Print
</a>

<a href="restaurant_order_payment.php?order_id=<?= $order['id'] ?>"
class="btn btn-success btn-sm mb-1">
💳 Collect Payment
</a>
<?php endif; ?>

</td>

</tr>

<?php endwhile; ?>
</tbody>
</table>

</div>

<?php include 'includes/footer.php'; ?>