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

// Handle date range filter
$start_date = $_GET['start_date'] ?? date('Y-m-d'); // default today
$end_date = $_GET['end_date'] ?? date('Y-m-d');

$whereClause = "";
if($start_date && $end_date){
    $whereClause = "WHERE pp.created_at BETWEEN '$start_date 00:00:00' AND '$end_date 23:59:59'";
}

// Optional: filter by booking
$booking_filter = $_GET['booking_id'] ?? '';
if($booking_filter){
    $whereClause .= ($whereClause ? " AND" : " WHERE") . " pp.booking_id = ".intval($booking_filter);
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Production Plans</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body{ padding:20px; background:#f8f9fa; }
        table { font-size:14px; }
        h3{ margin-top:20px; }
        .card-filter{ cursor:pointer; transition:0.3s; }
        .card-filter:hover{ transform: scale(1.02); }
        .highlight-today{ background:#fff3cd; }
    </style>
</head>
<body>

<div class="container">
  <button class="btn btn-secondary" onclick="history.back()">
            <i class="fa fa-arrow-left"></i> Back
        </button>
    <h3 class="mb-3"><i class="fa fa-boxes"></i> Production Plans</h3>

    <!-- ===== Date Range & Booking Filter Cards ===== -->
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="card card-filter p-3 bg-info text-white">
                <form method="get">
                    <label>Start Date:</label>
                    <input type="date" name="start_date" class="form-control mb-2" value="<?= htmlspecialchars($start_date) ?>" required>
                    <label>End Date:</label>
                    <input type="date" name="end_date" class="form-control mb-2" value="<?= htmlspecialchars($end_date) ?>" required>
                    <label>Booking ID (optional):</label>
                    <input type="number" name="booking_id" class="form-control mb-2" value="<?= htmlspecialchars($booking_filter) ?>">
                    <button type="submit" class="btn btn-light w-100"><i class="fa fa-filter"></i> Apply Filters</button>
                </form>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card p-3 bg-success text-white">
                <h5>Total Production Plans:</h5>
                <?php
                $countQuery = "SELECT COUNT(*) AS total FROM production_plan pp
                               JOIN conference_bookings b ON pp.booking_id = b.id
                               $whereClause";
                $totalPlans = $conn->query($countQuery)->fetch_assoc()['total'] ?? 0;
                echo "<h3>$totalPlans</h3>";
                ?>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card p-3 bg-warning text-dark text-center">
                <h5>Plans Date Range:</h5>
                <p><?= $start_date ?> → <?= $end_date ?></p>
                <a href="vew_production_plan.php" class="btn btn-dark btn-sm"><i class="fa fa-sync"></i> Reset Filters</a>
            </div>
        </div>
    </div>

    <!-- ===== Production Table ===== -->
    <?php
    $query = "SELECT pp.*, b.attendees, b.num_days, b.booking_date
              FROM production_plan pp
              JOIN conference_bookings b ON pp.booking_id = b.id
              $whereClause
              ORDER BY pp.booking_id, pp.item_type, pp.id";
    $result = $conn->query($query);

    if($result->num_rows > 0):
        echo "<div class='table-responsive'>";
        echo "<table class='table table-bordered table-striped table-sm'>";
        echo "<thead class='table-dark'><tr>
                <th>#</th>
                <th>Booking ID</th>
                <th>Booking Date</th>
                <th>Attendees</th>
                <th>Days</th>
                <th>Type</th>
                <th>Item Name</th>
                <th>Unit</th>
                <th>Qty per Person</th>
                <th>Composition</th>
                <th>Total Qty Needed</th>
              </tr></thead><tbody>";

        $counter = 1;
        $grandTotal = 0;
        while($row = $result->fetch_assoc()){
            $highlightClass = ($row['booking_date'] == date('Y-m-d')) ? 'highlight-today' : '';
            echo "<tr class='$highlightClass'>
                    <td>{$counter}</td>
                    <td>{$row['booking_id']}</td>
                    <td>{$row['booking_date']}</td>
                    <td>{$row['attendees']}</td>
                    <td>{$row['num_days']}</td>
                    <td>".ucfirst($row['item_type'])."</td>
                    <td>{$row['item_name']}</td>
                    <td>".($row['unit'] ?? '-')."</td>
                    <td>".($row['qty_per_person'] ?? '-')."</td>
                    <td>".($row['composition'] ?? 1)."</td>
                    <td>{$row['total_qty']}</td>
                  </tr>";
            $grandTotal += $row['total_qty'];
            $counter++;
        }

        echo "<tr class='table-success'>
                <td colspan='10' class='text-end fw-bold'>Overall Total Qty:</td>
                <td class='fw-bold'>{$grandTotal}</td>
              </tr>";

        echo "</tbody></table></div>";
    else:
        echo "<div class='alert alert-warning'>No production plans found for the selected period.</div>";
    endif;
    ?>

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

</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Optional: auto-print today by default
    <?php if(!$start_date && !$end_date): ?>
    window.onload = function(){ window.print(); }
    <?php endif; ?>
</script>
</body>
</html>