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

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

// ===== HANDLE UPDATE =====
$message = "";

if(isset($_POST['update_row'])){
    $item_name = $_POST['item_name'];
    $people_count = intval($_POST['people_count']);
    $unit_cost = floatval($_POST['unit_cost']);
    $qty_per_person = floatval($_POST['qty_per_person']);

    $total_qty = $people_count * $qty_per_person;
    $total_cost = $total_qty * $unit_cost;

    $stmt = $conn->prepare("
        UPDATE production_plan 
        SET people_count=?, total_qty=?, total_cost=?, unit_cost=?
        WHERE item_name=?
    ");
    $stmt->bind_param("iddss", $people_count, $total_qty, $total_cost, $unit_cost, $item_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 DATA =====
$query = $conn->prepare("
    SELECT 
        item_name,
        unit,
        qty_per_person,
        SUM(people_count) AS people_count,
        SUM(total_qty) AS total_qty,
        unit_cost,
        SUM(total_cost) AS total_costs
    FROM production_plan
    WHERE LOWER(TRIM(item_type))='perishable'
      AND DATE(created_at) BETWEEN ? AND ?
    GROUP BY item_name, unit, qty_per_person, unit_cost
");
$query->bind_param("ss", $start_date, $end_date);
$query->execute();
$result = $query->get_result();
$stock_items = $result->fetch_all(MYSQLI_ASSOC);

// ===== TOTALS =====
$total_qty=0; 
$total_cost=0; 
$total_items=0;

foreach($stock_items as $r){
    $total_qty += $r['total_qty'];
    $total_cost += $r['total_costs'];
    $total_items++;
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Perishable Report</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
body{background:#f8f9fa;padding:20px;}
.card{padding:15px;text-align:center;background:#fff;border-radius:10px;}
.edit-row{background:#fff3cd;}
tfoot{font-weight:bold;background:#e9ecef;}

/* PRINT */
@media print {
    body { background:#fff; padding:0; font-size:12px; }
    .no-print { display:none !important; }

    .print-header {
        display:flex;
        justify-content:space-between;
        align-items:center;
        border-bottom:2px solid #000;
        margin-bottom:15px;
        padding-bottom:10px;
    }
    .logo {
   /* adjust size here */
    width: auto;
}

    .print-header img { height:70px; }

    .print-title { text-align:right; }

    .print-title h3 { margin:0; font-size:20px; }

    table { font-size:12px; }

    .footer-note { text-align:center; font-size:11px; margin-top:20px; }
}
</style>

</head>

<body>

<!-- NORMAL HEADER -->
<div class="d-flex justify-content-between mb-3 no-print">
    <h4>Perishable Items Report</h4>
    <button onclick="window.print()" class="btn btn-success">Print</button>
</div>

<!-- PRINT HEADER -->
<div class="print-header">
    <div>
   <button class="btn btn-secondary" onclick="history.back()">
            <i class="fa fa-arrow-left"></i> Back
        </button>
    </div>

    <div class="print-title">
       
        <small>
            Date: <?= date('d M Y', strtotime($start_date)) ?> - <?= date('d M Y', strtotime($end_date)) ?><br>
            Generated: <?= date('d M Y H:i') ?>
        </small>
    </div>
</div>

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

<!-- FILTER -->
<form method="POST" class="row mb-3 no-print">
    <div class="col-md-3">
        <input type="date" name="start_date" value="<?= $start_date ?>" class="form-control">
    </div>
    <div class="col-md-3">
        <input type="date" name="end_date" value="<?= $end_date ?>" class="form-control">
    </div>
    <div class="col-md-2">
        <button class="btn btn-primary">Filter</button>
    </div>
</form>

<!-- SUMMARY -->
<div class="row mb-3 no-print">
    <div class="col-md-4"><div class="card">Items: <?= $total_items ?></div></div>
    <div class="col-md-4"><div class="card">Qty: <?= number_format($total_qty,2) ?></div></div>
    <div class="col-md-4"><div class="card">Cost: <?= number_format($total_cost,2) ?></div></div>
</div>

<!-- TABLE -->
<table class="table table-bordered bg-white">
<thead>
<tr>
<th>#</th>
<th>Item</th>
<th>Unit</th>
<th>People</th>
<th>Unit Cost</th>
<th>Total Qty</th>
<th>Total Cost</th>
<th class="no-print">Action</th>
</tr>
</thead>

<tbody>
<?php $i=1; foreach($stock_items as $row): ?>
<tr>
<form method="POST">

<td><?= $i++ ?></td>

<td>
    <?= $row['item_name'] ?>
    <input type="hidden" name="item_name" value="<?= $row['item_name'] ?>">
</td>

<td><?= $row['unit'] ?></td>

<td>
    <input type="number" name="people_count" 
        value="<?= $row['people_count'] ?>" 
        class="form-control people-field" readonly>
</td>

<td>
    <input type="number" step="0.01" name="unit_cost" 
        value="<?= $row['unit_cost'] ?>" 
        class="form-control cost-field" readonly>
</td>

<td><?= number_format($row['total_qty'],2) ?></td>
<td><?= number_format($row['total_costs'],2) ?></td>

<input type="hidden" name="qty_per_person" value="<?= $row['qty_per_person'] ?>">

<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 endforeach; ?>
</tbody>

<tfoot>
<tr>
<td colspan="5">GRAND TOTAL</td>
<td><?= number_format($total_qty,2) ?></td>
<td><?= number_format($total_cost,2) ?></td>
<td class="no-print"></td>
</tr>
</tfoot>

</table>

<!-- FOOTER -->
<div class="footer-note">
    <hr>
    <p>Generated by <?= $username ?> | <?= date('d M Y H:i') ?></p>
</div>

<script>
// EDIT
document.querySelectorAll('.edit-btn').forEach(btn=>{
    btn.onclick=function(){
        let row = this.closest('tr');

        row.classList.add('edit-row');

        row.querySelector('.people-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
document.querySelectorAll('.cancel-btn').forEach(btn=>{
    btn.onclick=function(){
        location.reload();
    }
});
</script>

</body>
</html>