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

$username = $_SESSION['username'] ?? 'Guest';
$user_role = $_SESSION['role'] ?? 'guest';

if(!in_array($user_role, ['admin','manager'])){
    echo "<div class='alert alert-danger'>Access denied.</div>";
    exit;
}

/* ================= APPROVE / REJECT ================= */
if(isset($_POST['action'], $_POST['req_id'])){

    $req_id = intval($_POST['req_id']);
    $action = $_POST['action'] === 'approve' ? 'Approved' : 'Rejected';

    $conn->begin_transaction();

    try {

        // update requisition
        $conn->query("UPDATE bar_requisitions SET status='$action' WHERE id=$req_id");

        /* ================= APPROVE STOCK TRANSFER ================= */
        if($action === 'Approved'){

            $items = $conn->query("
                SELECT * FROM bar_requisition_items 
                WHERE requisition_id=$req_id
            ");

            while($item = $items->fetch_assoc()){

                $pid = intval($item['product_id']);
                $qty = intval($item['quantity']);

                // MAIN STORE (5)
                $main = $conn->query("
                    SELECT * FROM product_stock 
                    WHERE product_id=$pid AND department_id=5
                ")->fetch_assoc();

                if(!$main || $main['quantity'] < $qty){
                    throw new Exception("Insufficient stock for product ID $pid");
                }

                // deduct main
                $conn->query("
                    UPDATE product_stock 
                    SET quantity = quantity - $qty 
                    WHERE id=".$main['id']
                );

                // BAR (1)
                $bar = $conn->query("
                    SELECT * FROM product_stock 
                    WHERE product_id=$pid AND department_id=5
                ")->fetch_assoc();

                if($bar){
                    $conn->query("
                        UPDATE product_stock 
                        SET quantity = quantity + $qty 
                        WHERE id=".$bar['id']
                    );
                } else {
                    $conn->query("
                        INSERT INTO product_stock(product_id, department_id, quantity)
                        VALUES($pid, 1, $qty)
                    ");
                }
            }
        }

        $conn->commit();

        echo "<script>
            alert('✅ Requisition $action successfully');
            window.location='approve_bar_requisitions.php';
        </script>";
        exit;

    } catch(Exception $e){
        $conn->rollback();
        echo "<div class='alert alert-danger'>".$e->getMessage()."</div>";
    }
}

/* ================= PENDING ================= */
$requisitions = $conn->query("
    SELECT br.*, u.username,
    (SELECT COUNT(*) FROM bar_requisition_items WHERE requisition_id=br.id) AS item_count
    FROM bar_requisitions br
    LEFT JOIN users u ON br.requested_by=u.id
    WHERE br.status='Pending'
    ORDER BY br.id DESC
");

/* ================= FILTER REPORT ================= */
$from = $_GET['from'] ?? '';
$to = $_GET['to'] ?? '';
$status = $_GET['status'] ?? 'Approved';

$where = "WHERE 1=1";

if($status){
    $where .= " AND br.status='$status'";
}

if($from && $to){
    $where .= " AND DATE(br.created_at) BETWEEN '$from' AND '$to'";
}

$approved = $conn->query("
    SELECT br.*, u.username
    FROM bar_requisitions br
    LEFT JOIN users u ON br.requested_by=u.id
    $where
    ORDER BY br.id DESC
");
?>

<div class="container mt-4">

<!-- BACK -->
<button class="btn btn-secondary mb-3" onclick="history.back()">
    <i class="fa fa-arrow-left"></i> Back
</button>

<h3 class="text-center">🍺 Bar Requisitions Management</h3>
<hr>

<!-- ================= PENDING TABLE ================= -->
<h5>Pending Requisitions</h5>

<?php if($requisitions->num_rows == 0): ?>
    <div class="alert alert-info">No pending requisitions.</div>
<?php else: ?>

<table class="table table-bordered table-striped">
<thead class="bg-dark text-white">
<tr>
    <th>ID</th>
    <th>Requested By</th>
    <th>Date</th>
    <th>Items</th>
    <th>Actions</th>
</tr>
</thead>

<tbody>
<?php while($r=$requisitions->fetch_assoc()): ?>
<tr>
    <td><?= $r['id'] ?></td>
    <td><?= $r['username'] ?></td>
    <td><?= date('d-m-Y H:i', strtotime($r['created_at'])) ?></td>

    <td>
        <button class="btn btn-info btn-sm" onclick="toggleItems(<?= $r['id'] ?>)">
            View (<?= $r['item_count'] ?>)
        </button>
    </td>

    <td>
        <form method="POST" style="display:inline;">
            <input type="hidden" name="req_id" value="<?= $r['id'] ?>">
            <button name="action" value="approve" class="btn btn-success btn-sm">Approve</button>
        </form>

        <form method="POST" style="display:inline;">
            <input type="hidden" name="req_id" value="<?= $r['id'] ?>">
            <button name="action" value="reject" class="btn btn-danger btn-sm">Reject</button>
        </form>
    </td>
</tr>

<tr id="items_<?= $r['id'] ?>" style="display:none;">
<td colspan="5">
<?php
$items = $conn->query("
    SELECT bri.*, p.name, p.sku
    FROM bar_requisition_items bri
    LEFT JOIN products p ON bri.product_id=p.id
    WHERE bri.requisition_id={$r['id']}
");
?>
<table class="table table-sm table-bordered">
<tr>
<th>SKU</th><th>Product</th><th>Qty</th>
</tr>

<?php while($it=$items->fetch_assoc()): ?>
<tr>
<td><?= $it['sku'] ?></td>
<td><?= $it['name'] ?></td>
<td><?= $it['quantity'] ?></td>
</tr>
<?php endwhile; ?>

</table>
</td>
</tr>

<?php endwhile; ?>
</tbody>
</table>

<?php endif; ?>

<hr>

<!-- ================= FILTER ================= -->
<form method="GET" class="row g-2 mb-3">
<div class="col-md-3"><input type="date" name="from" class="form-control"></div>
<div class="col-md-3"><input type="date" name="to" class="form-control"></div>
<div class="col-md-3">
<select name="status" class="form-control">
<option value="Approved">Approved</option>
<option value="Rejected">Rejected</option>
<option value="">All</option>
</select>
</div>
<div class="col-md-3">
<button class="btn btn-primary w-100"><i class="fa fa-search"></i> Filter</button>
</div>
</form>

<div class="text-end mb-2">
<button onclick="window.print()" class="btn btn-dark">
<i class="fa fa-print"></i> Print
</button>
</div>

<!-- ================= PRINT AREA ================= -->
<div id="printArea">

<div class="text-center">
<img src="assets/logo.png" style="width:80px;"><br>
<h4>BAR REQUISITION REPORT</h4>
<p>Generated by: <?= $username ?> | <?= date('d-m-Y H:i') ?></p>
</div>

<table class="table table-bordered" id="printTable">
<thead class="bg-success text-white">
<tr>
<th>ID</th>
<th>Requested By</th>
<th>Date</th>
<th>Status</th>
<th>Items</th>
<th>Total Qty</th>
</tr>
</thead>

<tbody>

<?php while($r=$approved->fetch_assoc()): ?>

<?php
$items = $conn->query("
SELECT bri.quantity,p.name,p.sku
FROM bar_requisition_items bri
LEFT JOIN products p ON bri.product_id=p.id
WHERE bri.requisition_id={$r['id']}
");

$total=0;
$txt="";

while($it=$items->fetch_assoc()){
$total+=$it['quantity'];
$txt.=$it['name']." (".$it['quantity'].")<br>";
}
?>

<tr>
<td>#<?= $r['id'] ?></td>
<td><?= $r['username'] ?></td>
<td><?= $r['created_at'] ?></td>
<td><?= $r['status'] ?></td>
<td><?= $txt ?></td>
<td><?= $total ?></td>
</tr>

<?php endwhile; ?>

</tbody>
</table>

<!-- SIGNATURES -->
<br><br>
<div class="row text-center">

<div class="col-md-6">
<hr>
Requested By<br>
Name: ____________<br>
Signature: ____________
</div>

<div class="col-md-6">
<hr>
Approved By<br>
Name: ____________<br>
Signature: ____________
</div>

</div>

</div>

</div>

<script>
function toggleItems(id){
let row=document.getElementById('items_'+id);
row.style.display=(row.style.display==='none')?'table-row':'none';
}
</script>

<style>
@media print{
body *{visibility:hidden;}
#printArea,#printArea *{visibility:visible;}
#printArea{position:absolute;top:0;left:0;width:100%;}
button,form{display:none!important;}
}
</style>

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