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

// ===== HANDLE FILTERS =====
$start_date = $_GET['start_date'] ?? '';
$end_date   = $_GET['end_date'] ?? '';
$item_type  = $_GET['item_type'] ?? '';

// ===== BUILD WHERE CLAUSE =====
$whereClause = [];

if ($start_date && $end_date) {
    $whereClause[] = "production_date BETWEEN '$start_date' AND '$end_date'";
}

if ($item_type) {
    $whereClause[] = "item_type = '" . $conn->real_escape_string($item_type) . "'";
}

$whereSQL = $whereClause ? "WHERE " . implode(' AND ', $whereClause) : "";

// ===== TOTAL CALCULATIONS =====
$totalQuery = "
    SELECT 
        COUNT(*) AS total_productions, 
        SUM(total_qty) AS total_qty 
    FROM walkin_production 
    $whereSQL
";

$totalData = $conn->query($totalQuery)->fetch_assoc();
$totalProductions = $totalData['total_productions'] ?? 0;
$grandTotalQty    = $totalData['total_qty'] ?? 0;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Walk-in Productions</title>

    <!-- Bootstrap & Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">

    <style>
        body {
            background: #f8f9fa;
        }
        .card {
            border-radius: 10px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        }
        .table th, .table td {
            vertical-align: middle !important;
        }
    </style>
</head>

<body>

<div class="container mt-4">

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

    <h2 class="mb-3">Walk-in Productions</h2>

    <!-- ===== FILTERS ===== -->
    <div class="card p-3 mb-3 bg-info text-white">
        <form method="get" class="row g-2 align-items-end">
            
            <div class="col-md-3">
                <label>Start Date:</label>
                <input type="date" name="start_date" class="form-control"
                       value="<?= htmlspecialchars($start_date) ?>" required>
            </div>

            <div class="col-md-3">
                <label>End Date:</label>
                <input type="date" name="end_date" class="form-control"
                       value="<?= htmlspecialchars($end_date) ?>" required>
            </div>

            <div class="col-md-3">
                <label>Item Type:</label>
                <select name="item_type" class="form-control">
                    <option value="">All</option>
                    <option value="meal" <?= $item_type=='meal'?'selected':'' ?>>Meal</option>
                    <option value="refreshment" <?= $item_type=='refreshment'?'selected':'' ?>>Refreshment</option>
                    <option value="perishable" <?= $item_type=='perishable'?'selected':'' ?>>Perishable</option>
                </select>
            </div>

            <div class="col-md-3">
                <button type="submit" class="btn btn-light w-100">
                    <i class="fa fa-filter"></i> Apply Filters
                </button>
                <a href="view_walkin_productions.php" class="btn btn-dark w-100 mt-2">
                    <i class="fa fa-sync"></i> Reset
                </a>
            </div>

        </form>
    </div>

    <!-- ===== TOTALS ===== -->
    <div class="row mb-3">
        <div class="col-md-6">
            <div class="card p-3 bg-success text-white">
                <h5>Total Productions</h5>
                <h3><?= $totalProductions ?></h3>
            </div>
        </div>

        <div class="col-md-6">
            <div class="card p-3 bg-warning text-dark">
                <h5>Overall Quantity</h5>
                <h3><?= number_format($grandTotalQty) ?></h3>
            </div>
        </div>
    </div>

    <!-- ===== TABLE ===== -->
    <?php
    $productions = $conn->query("
        SELECT * 
        FROM walkin_production 
        $whereSQL 
        ORDER BY production_date DESC, id DESC
    ");

    if ($productions->num_rows > 0):
    ?>
    <div class="table-responsive">
        <table class="table table-bordered table-striped table-sm bg-white">
           <thead class="table-dark">
    <tr>
        <th>#</th>
        <th>Production Date</th>
        <th>People Count</th>
        <th>Item Produced</th>
        <th>Item(s) Used</th>
        <th>Qty per Person</th>
        <th>Total Qty</th>
        <th>Unit Price (MWK)</th>
        <th>Total Cost (MWK)</th>
        <th>Actions</th>
    </tr>
</thead>

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

    // ===== CALCULATIONS =====
    $unit_cost = $p['unit_cost'] ?? 0;
    $total_cost = $unit_cost * $p['people_count'];

    // ===== CHECK IF AUDITED =====
    $audited = $conn->query("SELECT COUNT(*) AS c FROM walkin_audit_log WHERE production_id={$p['id']}")->fetch_assoc()['c'] ?? 0;
?>
    <tr>
        <td><?= $i ?></td>
        <td><?= $p['production_date'] ?></td>
        <td><?= $p['people_count'] ?></td>
        <td><?= htmlspecialchars($p['item_name']) ?></td>
        <td><?= !empty($p['perishable_name']) ? htmlspecialchars($p['perishable_name']) : '-' ?></td>
        <td><?= $p['qty_per_person'] ?? '-' ?></td>
        <td><?= number_format($p['total_qty']) ?></td>
        <td><?= number_format($unit_cost, 2) ?></td>
        <td><?= number_format($total_cost, 2) ?></td>

        <!-- Actions -->
        <td>
            <?php if($audited > 0): ?>
                <span class="text-success"><i class="fa fa-check"></i> Audited</span>
            <?php else: ?>
                <a href="audit_production.php?id=<?= $p['id'] ?>" class="btn btn-warning btn-sm">
                    <i class="fa fa-balance-scale"></i> Audit
                </a>
            <?php endif; ?>
        </td>
    </tr>
<?php 
$i++; 
endwhile; 
?>
</tbody>
        </table>
    </div>

    <?php else: ?>
        <div class="alert alert-warning">
            No walk-in productions found for the selected filters.
        </div>
    <?php endif; ?>

    <!-- ===== PRINT BUTTON ===== -->
    <div class="mt-3">
        <button onclick="window.print()" class="btn btn-primary">
            <i class="fa fa-print"></i> Print List
        </button>
    </div>

</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>