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

$username = $_SESSION['username'] ?? 'Guest';
$today = date('Y-m-d');

// ================= FILTERS =================
$from_date = $_GET['from'] ?? $today;
$to_date   = $_GET['to'] ?? $today;
$waiter    = $_GET['waiter'] ?? '';
$table     = $_GET['table'] ?? '';
$status    = $_GET['status'] ?? '';
$search    = $_GET['search'] ?? '';

// ================= BUILD WHERE =================
$where = [];
$where[] = "DATE(ro.created_at) >= '".$conn->real_escape_string($from_date)."'";
$where[] = "DATE(ro.created_at) <= '".$conn->real_escape_string($to_date)."'";

if($waiter){
    $where[] = "ro.waiter_id = '".$conn->real_escape_string($waiter)."'";
}
if($table){
    $where[] = "ro.table_number LIKE '%".$conn->real_escape_string($table)."%'";
}
if($status){
    $where[] = "ro.status = '".$conn->real_escape_string($status)."'";
}
if($search){
    $s = $conn->real_escape_string($search);
    $where[] = "(ro.table_number LIKE '%$s%' OR ro.created_by LIKE '%$s%')";
}

$where_sql = "WHERE ".implode(" AND ", $where);

// ================= FETCH ORDERS =================
$query = "
SELECT ro.*, w.username AS waiter_name, 
       IFNULL(SUM(roi.price * roi.qty),0) AS total_items_amount
FROM restaurant_orders ro
LEFT JOIN restaurant_order_items roi ON roi.order_id = ro.id
LEFT JOIN users w ON w.id = ro.waiter_id
$where_sql
GROUP BY ro.id
ORDER BY ro.created_at DESC
";

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

// ================= SUMMARY =================
$summary = $conn->query("
SELECT 
    COUNT(*) AS total_orders,
    IFNULL(SUM(grand_total),0) AS total_grand,
    SUM(CASE WHEN status='PENDING' THEN 1 ELSE 0 END) AS pending_count,
    SUM(CASE WHEN status='IN_KITCHEN' THEN 1 ELSE 0 END) AS in_kitchen_count,
    SUM(CASE WHEN status='READY' THEN 1 ELSE 0 END) AS ready_count,
    SUM(CASE WHEN status='PAID' THEN 1 ELSE 0 END) AS paid_count,
    SUM(CASE WHEN status='SERVED' THEN 1 ELSE 0 END) AS served_count
FROM restaurant_orders ro
$where_sql
")->fetch_assoc();
?>

<div class="container-fluid mt-4">
    <button class="btn btn-secondary no-print" onclick="history.back()"><i class="fa fa-arrow-left"></i> Back</button>

    <div class="welcome-msg no-print mb-3">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($username) ?></strong>
    </div>

    <h3 class="mb-2"><i class="fa fa-utensils text-primary"></i> Restaurant Orders Report</h3>
    <hr>

    <!-- ================= FILTERS ================= -->
    <form method="GET" class="row g-2 mb-3 no-print">
        <div class="col-md-2"><input type="date" name="from" class="form-control" value="<?= htmlspecialchars($from_date) ?>"></div>
        <div class="col-md-2"><input type="date" name="to" class="form-control" value="<?= htmlspecialchars($to_date) ?>"></div>
        <div class="col-md-2"><input type="text" name="waiter" class="form-control" placeholder="Waiter ID" value="<?= htmlspecialchars($waiter) ?>"></div>
        <div class="col-md-2"><input type="text" name="table" class="form-control" placeholder="Table Number" value="<?= htmlspecialchars($table) ?>"></div>
        <div class="col-md-2">
            <select name="status" class="form-control">
                <option value="">All Statuses</option>
                <option <?= $status=='PENDING'?'selected':'' ?>>PENDING</option>
                <option <?= $status=='IN_KITCHEN'?'selected':'' ?>>IN_KITCHEN</option>
                <option <?= $status=='READY'?'selected':'' ?>>READY</option>
                <option <?= $status=='PAID'?'selected':'' ?>>PAID</option>
                <option <?= $status=='SERVED'?'selected':'' ?>>SERVED</option>
            </select>
        </div>
        <div class="col-md-2 d-flex gap-1">
            <input type="text" name="search" class="form-control" placeholder="Search" value="<?= htmlspecialchars($search) ?>">
            <button class="btn btn-primary"><i class="fa fa-filter"></i> Filter</button>
        </div>
    </form>

    <!-- ================= ACTION BUTTONS ================= -->
    <div class="mb-3 no-print d-flex gap-2">
        <a href="export_restaurant_orders_excel.php?from=<?= urlencode($from_date) ?>&to=<?= urlencode($to_date) ?>&waiter=<?= urlencode($waiter) ?>&table=<?= urlencode($table) ?>&status=<?= urlencode($status) ?>&search=<?= urlencode($search) ?>" class="btn btn-success">
            <i class="fa fa-file-excel"></i> Export Excel
        </a>
        <button onclick="window.print()" class="btn btn-info"><i class="fa fa-print"></i> Print / PDF</button>
    </div>

    <!-- ================= SUMMARY CARDS ================= -->
    <div class="row mb-3 text-center">
        <div class="col-md-2"><div class="card shadow-sm report-card"><div class="card-body"><h6>Total Orders</h6><h4><?= $summary['total_orders'] ?></h4></div></div></div>
        <div class="col-md-2"><div class="card shadow-sm report-card"><div class="card-body"><h6>Total Amount (MK)</h6><h4><?= number_format($summary['total_grand'],2) ?></h4></div></div></div>
        <div class="col-md-2"><div class="card shadow-sm report-card"><div class="card-body"><h6>PENDING</h6><h4><?= $summary['pending_count'] ?></h4></div></div></div>
        <div class="col-md-2"><div class="card shadow-sm report-card"><div class="card-body"><h6>IN KITCHEN</h6><h4><?= $summary['in_kitchen_count'] ?></h4></div></div></div>
        <div class="col-md-2"><div class="card shadow-sm report-card"><div class="card-body"><h6>READY</h6><h4><?= $summary['ready_count'] ?></h4></div></div></div>
        <div class="col-md-2"><div class="card shadow-sm report-card"><div class="card-body"><h6>PAID</h6><h4><?= $summary['paid_count'] ?></h4></div></div></div>
        <div class="col-md-2"><div class="card shadow-sm report-card"><div class="card-body"><h6>SERVED</h6><h4><?= $summary['served_count'] ?></h4></div></div></div>
    </div>

    <!-- ================= TABLE ================= -->
    <div class="table-responsive">
        <table class="table table-bordered table-striped table-sm">
            <thead class="table-dark">
                <tr>
                    <th>Order ID</th>
                    <th>Waiter</th>
                    <th>Table Number</th>
                    <th>Subtotal</th>
                    <th>Discount</th>
                    <th>Grand Total</th>
                    <th>Payment Method</th>
                    <th>Status</th>
                    <th>Created At</th>
                    <th>Created By</th>
                </tr>
            </thead>
            <tbody>
                <?php if($result && $result->num_rows): ?>
                    <?php while($row = $result->fetch_assoc()): ?>
                        <tr>
                            <td><?= $row['id'] ?></td>
                            <td><?= htmlspecialchars($row['waiter_name'] ?? $row['waiter_id']) ?></td>
                            <td><?= $row['table_number'] ?></td>
                            <td><?= number_format($row['subtotal'],2) ?></td>
                            <td><?= number_format($row['discount'],2) ?></td>
                            <td><?= number_format($row['grand_total'],2) ?></td>
                            <td><?= $row['payment_method'] ?></td>
                            <td><?= $row['status'] ?></td>
                            <td><?= $row['created_at'] ?></td>
                            <td><?= $row['created_by'] ?></td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr><td colspan="10" class="text-center text-danger">No orders found</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

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