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

$user_id   = $_SESSION['user_id'] ?? 0;
$username  = $_SESSION['username'] ?? 'Guest';
$department_id = 5; // Main Store

/* ================= HANDLE SUBMIT ================= */
if(isset($_POST['submit_requisition'])){

    if(empty($_POST['items'])){
        echo "<script>alert('Select at least one item');</script>";
    } else {

        $conn->begin_transaction();

        try {

            /* ================= CREATE REQUISITION ================= */
            $stmt = $conn->prepare("
                INSERT INTO front_desk_requisitions (requested_by, status)
                VALUES (?, 'Pending')
            ");

            if(!$stmt){
                throw new Exception("DB Error (requisition insert): " . $conn->error);
            }

            $stmt->bind_param("i", $user_id);
            $stmt->execute();

            $requisition_id = $conn->insert_id;

            /* ================= INSERT ITEMS ================= */
            foreach($_POST['items'] as $product_id){

                $product_id = intval($product_id);
                $qty = intval($_POST['qty'][$product_id] ?? 0);

                if($qty <= 0) continue;

                $stmt2 = $conn->prepare("
                    INSERT INTO front_desk_requisition_items
                    (requisition_id, product_id, quantity)
                    VALUES (?,?,?)
                ");

                if(!$stmt2){
                    throw new Exception("DB Error (items insert): " . $conn->error);
                }

                $stmt2->bind_param("iii", $requisition_id, $product_id, $qty);
                $stmt2->execute();
            }

            $conn->commit();

            echo "<script>
                alert('✅ Front Desk requisition submitted successfully!');
                window.location='font_desk_requisitions.php';
            </script>";
            exit;

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

/* ================= PRODUCTS ================= */
$products = $conn->query("
    SELECT p.*, COALESCE(ps.quantity,0) AS main_qty
    FROM products p
    LEFT JOIN product_stock ps
        ON p.id = ps.product_id AND ps.department_id = 5
    ORDER BY p.name ASC
");

/* ================= USER REQUISITIONS ================= */
$requisitions = $conn->query("
    SELECT fr.*, u.username,
           (SELECT COUNT(*) 
            FROM front_desk_requisition_items 
            WHERE requisition_id = fr.id) AS item_count
    FROM front_desk_requisitions fr
    LEFT JOIN users u ON fr.requested_by = u.id
    WHERE fr.requested_by = $user_id
    ORDER BY fr.id DESC
");
?>

<div class="container mt-4">

<h3 class="text-center">🏢 Front Desk Requisition Form</h3>
<hr>

<!-- ================= FORM ================= -->
<form method="POST">

<table class="table table-bordered table-striped">

<thead class="bg-dark text-white">
<tr>
    <th>Select</th>
    <th>Product</th>
    <th>Main Store Qty</th>
    <th>Request Qty</th>
</tr>
</thead>

<tbody>

<?php while($p = $products->fetch_assoc()): ?>

<?php $disabled = ($p['main_qty'] <= 0) ? 'disabled' : ''; ?>

<tr>
    <td>
        <input type="checkbox"
               name="items[]"
               value="<?= $p['id'] ?>"
               <?= $disabled ?>>
    </td>

    <td><?= htmlspecialchars($p['name']) ?></td>

    <td><?= intval($p['main_qty']) ?></td>

    <td>
        <input type="number"
               name="qty[<?= $p['id'] ?>]"
               class="form-control"
               min="0"
               max="<?= intval($p['main_qty']) ?>"
               <?= $disabled ?>>
    </td>
</tr>

<?php endwhile; ?>

</tbody>
</table>

<div class="text-end mb-4">
    <button type="submit" name="submit_requisition" class="btn btn-success">
        ✅ Submit Requisition
    </button>
</div>

</form>

<hr>

<!-- ================= HISTORY ================= -->
<h4>📋 Your Previous Requisitions</h4>

<table class="table table-bordered table-striped">

<thead class="bg-secondary text-white">
<tr>
    <th>ID</th>
    <th>Date</th>
    <th>Status</th>
    <th>Items</th>
</tr>
</thead>

<tbody>

<?php if($requisitions && $requisitions->num_rows > 0): ?>

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

    <tr>
        <td>#<?= $r['id'] ?></td>

        <td><?= date('d-m-Y H:i', strtotime($r['created_at'])) ?></td>

        <td>
            <?php
            if($r['status']=='Pending')
                echo "<span class='badge bg-warning'>Pending</span>";
            elseif($r['status']=='Approved')
                echo "<span class='badge bg-success'>Approved</span>";
            else
                echo "<span class='badge bg-danger'>Rejected</span>";
            ?>
        </td>

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

    <tr id="items_<?= $r['id'] ?>" style="display:none;background:#f9f9f9;">
        <td colspan="4">

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

        <table class="table table-sm table-bordered">
            <tr class="bg-light">
                <th>Product</th>
                <th>Quantity</th>
            </tr>

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

        </table>

        </td>
    </tr>

    <?php endwhile; ?>

<?php else: ?>

<tr>
    <td colspan="4" class="text-center">No requisitions found</td>
</tr>

<?php endif; ?>

</tbody>
</table>

</div>

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

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