<?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;
$search    = $_GET['search'] ?? '';

// ================= BUILD WHERE =================
$where = [];
$where[] = "pp.created_at >= '".$conn->real_escape_string($from_date)." 00:00:00'";
$where[] = "pp.created_at <= '".$conn->real_escape_string($to_date)." 23:59:59'";

if($search){
    $s = $conn->real_escape_string($search);
    $where[] = "p.name LIKE '%$s%'";
}

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

// ================= FETCH PERISHABLES =================
$query = "
SELECT 
    pp.id AS production_id,
    pp.number_of_people,
    pp.created_at,
    p.name,
    p.unit,
    IFNULL(ppi.qty_per_person, pp_default.qty_per_person) AS qty_per_person,
    ppi.total_needed,
    ppi.stock_available
FROM perishable_production_items ppi
JOIN perishable_production pp ON pp.id = ppi.production_id
JOIN perishables p ON p.id = ppi.perishable_id
LEFT JOIN perishable_parameters pp_default ON pp_default.perishable_id = p.id
$where_sql
ORDER BY pp.created_at DESC
";

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

// ================= SUMMARY =================
$summary_query = "
SELECT 
    COUNT(DISTINCT pp.id) AS total_productions,
    SUM(pp.number_of_people) AS total_people
FROM perishable_production pp
JOIN perishable_production_items ppi ON pp.id = ppi.production_id
JOIN perishables p ON p.id = ppi.perishable_id
$where_sql
";

$summary = $conn->query($summary_query)->fetch_assoc();

$total_productions = $summary['total_productions'] ?? 0;
$total_people      = $summary['total_people'] ?? 0;
?>

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

    <h4><i class="fa fa-leaf text-success"></i> Perishables Production Report</h4>
    <hr>

    <!-- FILTERS -->
    <form method="GET" class="row g-2 mb-3">
        <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-4">
            <input type="text" name="search" class="form-control" placeholder="Perishable Item" value="<?= htmlspecialchars($search) ?>">
        </div>
        <div class="col-md-4 d-flex gap-1">
            <button class="btn btn-primary w-100"><i class="fa fa-filter"></i> Filter</button>
            <a href="perishables_report.php" class="btn btn-secondary w-100">Reset</a>
        </div>
    </form>

    <!-- SUMMARY CARDS -->
    <div class="row mb-3" id="printSection">
        <div class="col-md-3">
            <div class="card text-center p-2">
                <h6>Total Productions</h6>
                <h4><?= $total_productions ?></h4>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card text-center p-2">
                <h6>Total People Served</h6>
                <h4><?= $total_people ?></h4>
            </div>
        </div>
    </div>

    <!-- PRINT BUTTON -->
    <div class="mb-3">
        <button class="btn btn-success" onclick="printReport()">
            <i class="fa fa-print"></i> Print Report
        </button>
    </div>

    <!-- TABLE -->
    <div class="table-responsive" id="printSection">
        <table class="table table-bordered table-striped table-sm">
            <thead class="table-dark">
                <tr>
                    <th>Production ID</th>
                    <th>Item</th>
                    <th>Unit</th>
                    <th>Qty per Person</th>
                    <th>Qty Needed</th>
                    <th>Qty Available</th>
                    <th>Number of People</th>
                    <th>Produced At</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php if($result && $result->num_rows): ?>
                    <?php while($row = $result->fetch_assoc()): ?>
                        <?php $status = ($row['stock_available'] >= $row['total_needed']) ? 'Sufficient' : 'Low'; ?>
                        <tr class="<?= $status==='Low' ? 'table-danger' : '' ?>">
                            <td><?= $row['production_id'] ?></td>
                            <td><?= $row['name'] ?></td>
                            <td><?= $row['unit'] ?></td>
                            <td><?= $row['qty_per_person'] ?></td>
                            <td><?= $row['total_needed'] ?></td>
                            <td><?= $row['stock_available'] ?></td>
                            <td><?= $row['number_of_people'] ?></td>
                            <td><?= $row['created_at'] ?></td>
                            <td><?= $status ?></td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="9" class="text-center text-danger">No production found</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
function printReport() {
    // Get the content of the section to print
    let content = document.getElementById('printSection').innerHTML;

    // Open a new window for printing
    let printWindow = window.open('', '', 'height=700,width=1000');
    printWindow.document.write('<html><head><title>Perishables Production Report</title>');
    printWindow.document.write('<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">');
    printWindow.document.write('<style>h4{margin-bottom:20px;} table{font-size:0.9rem;} .table-danger{background-color:#f8d7da !important;}</style>');
    printWindow.document.write('</head><body>');
    printWindow.document.write(content);
    printWindow.document.write('</body></html>');
    printWindow.document.close();
    printWindow.print();
}
</script>

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