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

$username = $_SESSION['username'] ?? 'Guest';

// ===== HANDLE UPDATE =====
$message = "";
if(isset($_POST['update_row'])){
    $perishable_name = $_POST['perishable_name'];
    $total_qty = floatval($_POST['total_qty']);
    $unit_cost = floatval($_POST['unit_cost']);
    $total_cost = $total_qty * $unit_cost;

    $stmt = $conn->prepare("
        UPDATE walkin_production 
        SET total_qty=?, unit_cost=?, total_costs=? 
        WHERE perishable_name=?
    ");
    $stmt->bind_param("ddds", $total_qty, $unit_cost, $total_cost, $perishable_name);
    $stmt->execute();

    $message = "✅ Updated successfully!";
}

// ===== DATE RANGE =====
$start_date = $_POST['start_date'] ?? date('Y-m-d');
$end_date   = $_POST['end_date'] ?? date('Y-m-d');

// ===== FETCH PERISHABLES =====
$perishables_total_costs = 0;
$perishables_total_qty   = 0;
$perishables_total_items = 0;

$query = $conn->prepare("
    SELECT perishable_name, unit, qty_per_person, SUM(total_qty) AS total_qty,people_count,
           unit_cost, SUM(total_costs) AS total_costs
    FROM walkin_production
    WHERE item_type='' AND production_date BETWEEN ? AND ?
    GROUP BY perishable_name, unit, qty_per_person, unit_cost
");
$query->bind_param("ss", $start_date, $end_date);
$query->execute();
$result = $query->get_result();
$perishables = $result->fetch_all(MYSQLI_ASSOC);

foreach ($perishables as $row) {
    $perishables_total_costs += $row['total_costs'];
    $perishables_total_qty   += $row['total_qty'];
    $perishables_total_items++;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Stock Items Report</title>
<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 { padding: 20px; background: #f8f9fa; }
.card { padding: 20px; text-align:center; background:#fff; border-radius:10px; }
.edit-row { background:#fff3cd; }

@media print {
    .no-print { display:none; }
    body { background:#fff; }
    table { page-break-inside:auto; }
    tr { page-break-inside:avoid; page-break-after:auto; }
}
table th, table td { vertical-align: middle !important; }
</style>
</head>
<body>

<!-- HEADER WITH LOGO -->
<div class="print-header no-print">
    
    <h4>Stock Items Report</h4>
    <button class="btn btn-success" onclick="window.print()"><i class="fa fa-print"></i> Print</button>
</div>

<?php if($message): ?>
<div class="alert alert-success no-print"><?= $message ?></div>
<?php endif; ?>

<!-- FILTER -->
<form method="POST" class="row g-3 mb-4 no-print">
    <div class="col-md-3">
        <label class="form-label">Start Date</label>
        <input type="date" name="start_date" class="form-control" value="<?= $start_date ?>">
    </div>
    <div class="col-md-3">
        <label class="form-label">End Date</label>
        <input type="date" name="end_date" class="form-control" value="<?= $end_date ?>">
    </div>
    <div class="col-md-2 d-flex align-items-end">
        <button class="btn btn-primary w-100" type="submit"><i class="fa fa-filter"></i> Filter</button>
    </div>
</form>

<!-- SUMMARY CARDS -->
<div class="row mb-4">
    <div class="col-md-4"><div class="card">Items: <?= $perishables_total_items ?></div></div>
    <div class="col-md-4"><div class="card">Qty: <?= number_format($perishables_total_qty,2) ?></div></div>
    <div class="col-md-4"><div class="card">Cost: <?= number_format($perishables_total_costs,2) ?></div></div>
</div>

<!-- PERISHABLES TABLE -->
<?php if(!empty($perishables)): ?>
<table class="table table-bordered bg-white">
<thead class="table-light">
<tr>
<th>#</th>
<th>Item Name</th>
<th>People Count</th>
<th>Total Qty</th>
<th>Unit Cost</th>
<th>Total Cost</th>
<th class="no-print">Action</th>
</tr>
</thead>
<tbody>
<?php $i=1; foreach($perishables as $row): ?>
<tr>
<form method="POST">
<td><?= $i ?></td>
<td>
    <?= htmlspecialchars($row['perishable_name']) ?>
    <input type="hidden" name="perishable_name" value="<?= $row['perishable_name'] ?>">
</td>
<td><?= $row['people_count'] ?></td>
<td><input type="number" step="0.01" name="total_qty" class="form-control qty-field" value="<?= $row['total_qty'] ?>" readonly></td>
<td><input type="number" step="0.01" name="unit_cost" class="form-control cost-field" value="<?= $row['unit_cost'] ?>" readonly></td>
<td><?= number_format($row['total_costs'],2) ?></td>
<td class="no-print">
    <button type="button" class="btn btn-sm btn-warning edit-btn">Edit</button>
    <button type="submit" name="update_row" class="btn btn-sm btn-success save-btn d-none">Save</button>
    <button type="button" class="btn btn-sm btn-secondary cancel-btn d-none">Cancel</button>
</td>
</form>
</tr>
<?php $i++; endforeach; ?>
</tbody>
<tfoot>
<tr>
<td colspan="3">GRAND TOTAL</td>
<td></td>
<td>-</td>
<td><b><?= number_format($perishables_total_costs,2) ?></b></td>
<td class="no-print"></td>
</tr>
</tfoot>
</table>
<?php else: ?>
<p class="text-center text-muted">No perishable productions found for the selected date range.</p>
<?php endif; ?>

<script>
// EDIT FUNCTION
document.querySelectorAll('.edit-btn').forEach(btn=>{
    btn.onclick=function(){
        let row = this.closest('tr');
        row.classList.add('edit-row');
        row.querySelector('.qty-field').removeAttribute('readonly');
        row.querySelector('.cost-field').removeAttribute('readonly');
        row.querySelector('.edit-btn').classList.add('d-none');
        row.querySelector('.save-btn').classList.remove('d-none');
        row.querySelector('.cancel-btn').classList.remove('d-none');
    }
});

// CANCEL FUNCTION
document.querySelectorAll('.cancel-btn').forEach(btn=>{
    btn.onclick=function(){ location.reload(); }
});
</script>

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