<?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'];
    $unit_cost = floatval($_POST['unit_cost']);
    $total_qty = floatval($_POST['total_qty']);

    $total_cost = $total_qty * $unit_cost;

    $stmt = $conn->prepare("
        UPDATE production_plan 
        SET unit_cost=?, total_qty=?, total_cost=?
        WHERE item_name=?
    ");
    $stmt->bind_param("ddds", $unit_cost, $total_qty, $total_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 
       pp.people_count,
        pp.item_name,
        pp.unit,
        SUM(pp.total_qty) AS total_qty,
        COALESCE(p.buying_price, pp.unit_cost) AS unit_cost
    FROM production_plan pp
    LEFT JOIN products p ON pp.item_name = p.name
    WHERE DATE(pp.created_at) BETWEEN ? AND ? AND LOWER(TRIM(pp.item_type)) = ''
    GROUP BY pp.item_name, pp.unit, unit_cost
    ORDER BY pp.item_name ASC
");

$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 $row) {
    $total_qty += $row['total_qty'];
    $total_cost += ($row['total_qty'] * $row['unit_cost']);
    $total_items++;
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Meal Parameters 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:20px; text-align:center; background:#fff; border-radius:10px; }
.edit-row { background:#fff3cd; }
tfoot { font-weight:bold; background:#e9ecef; }
</style>
</head>

<body>

<div class="d-flex justify-content-between mb-3 no-print">
     <button class="btn btn-secondary" onclick="history.back()">
            <i class="fa fa-arrow-left"></i> Back
        </button>
    <h4>Meal Parameters Report</h4>
    <button onclick="window.print()" class="btn btn-success">Print</button>
</div>

<?php if($message): ?>
<div class="alert alert-success"><?= $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>Material</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($stock_items as $row): ?>
<tr>
<form method="POST">

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

<td>
    <?= htmlspecialchars($row['item_name']) ?>
    <input type="hidden" name="item_name" value="<?= $row['item_name'] ?>">
</td>
<td>
    <?= htmlspecialchars($row['people_count']) ?>
    <input type="hidden" name="people_count" value="<?= $row['people_count'] ?>">
</td>
<td>
    <input type="number" step="0.01" name="total_qty"
        value="<?= $row['total_qty'] ?>"
        class="form-control qty-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'] * $row['unit_cost'],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 endforeach; ?>
</tbody>

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

</table>

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

</body>
</html>