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

$username = $_SESSION['username'] ?? 'Guest';
$user_id  = $_SESSION['user_id'] ?? 0;
$hk_store_id = 4; // Housekeeping store
$main_store_id = 1; // Main Store

// ==================== Add item to session cart ====================
if(isset($_POST['add_to_cart'])){
    $product_id = intval($_POST['product_id']);
    $qty        = intval($_POST['qty']);

    // Fetch stock from HK store, fallback to Main Store
    $stock = $conn->query("
        SELECT COALESCE(hk.quantity, m.quantity, 0) AS available_qty
        FROM products p
        LEFT JOIN product_stock hk ON p.id = hk.product_id AND hk.store_id=$hk_store_id
        LEFT JOIN product_stock m  ON p.id = m.product_id  AND m.store_id=$main_store_id
        WHERE p.id=$product_id
    ")->fetch_assoc();

    $available = intval($stock['available_qty']);

    if($qty > $available){
        echo "<script>alert('Insufficient stock. Available: $available');</script>";
    } else {
        $product = $conn->query("SELECT * FROM products WHERE id=$product_id")->fetch_assoc();

        // Avoid duplicates in session cart
        $found = false;
        if(!empty($_SESSION['hk_cart'])){
            foreach($_SESSION['hk_cart'] as &$item){
                if($item['id'] == $product_id){
                    $item['qty'] += $qty;
                    $found = true;
                    break;
                }
            }
        }
        if(!$found){
            $_SESSION['hk_cart'][] = [
                'id'   => $product_id,
                'name' => $product['name'],
                'sku'  => $product['sku'],
                'qty'  => $qty
            ];
        }
    }
}

// ==================== Remove item from cart ====================
if(isset($_GET['remove'])){
    unset($_SESSION['hk_cart'][$_GET['remove']]);
    $_SESSION['hk_cart'] = array_values($_SESSION['hk_cart']);
}

// ==================== Submit Requisition ====================
if(isset($_POST['submit_requisition']) && !empty($_SESSION['hk_cart'])){
    // Insert requisition header
    $conn->query("INSERT INTO hk_requisitions(requested_by, store_id, created_at) VALUES($user_id, $hk_store_id, NOW())");
    $requisition_id = $conn->insert_id;

    // Insert items
    foreach($_SESSION['hk_cart'] as $item){
        $pid = $item['id'];
        $qty = $item['qty'];

        // Reduce stock from HK store if available, otherwise Main Store
        $stock = $conn->query("SELECT quantity FROM product_stock WHERE product_id=$pid AND store_id=$hk_store_id")->fetch_assoc();
        $hk_qty = intval($stock['quantity'] ?? 0);

        if($hk_qty >= $qty){
            // Deduct from HK store
            $conn->query("UPDATE product_stock SET quantity = quantity - $qty WHERE product_id=$pid AND store_id=$hk_store_id");
        } else {
            // Deduct all from HK store and remainder from Main Store
            if($hk_qty > 0){
                $conn->query("UPDATE product_stock SET quantity = 0 WHERE product_id=$pid AND store_id=$hk_store_id");
            }
            $remaining = $qty - $hk_qty;
            $conn->query("UPDATE product_stock SET quantity = quantity - $remaining WHERE product_id=$pid AND store_id=$main_store_id");
        }

        $conn->query("INSERT INTO hk_requisition_items(requisition_id, product_id, quantity) VALUES($requisition_id, $pid, $qty)");
    }

    // Clear session cart
    $_SESSION['hk_cart'] = [];

    echo "<script>alert('Housekeeping requisition submitted successfully!'); window.location='hk_requisition_request.php';</script>";
    exit;
}

// ==================== Fetch products for selection ====================
// Show available stock in HK store, fallback to Main Store
$products = $conn->query("
    SELECT p.*, COALESCE(hk.quantity, m.quantity, 0) AS stock_qty
    FROM products p
    LEFT JOIN product_stock hk ON p.id = hk.product_id AND hk.store_id=$hk_store_id
    LEFT JOIN product_stock m  ON p.id = m.product_id  AND m.store_id=$main_store_id
    ORDER BY p.name ASC
");
?>

<div class="container mt-4">
     <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
    </div>
    <button class="btn btn-secondary" onclick="history.back()"><i class="fa fa-arrow-left"></i> Back</button>
    <h3 class="text-center">🧹 Housekeeping Requisition</h3>
    <hr>

    <div class="welcome-msg mb-3">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($username) ?></strong>!
    </div>

    <!-- Add Product Form -->
    <form method="POST" class="row g-3 mb-3">
        <div class="col-md-6">
            <label>Select Product</label>
            <select name="product_id" class="form-control" required>
                <option value="">-- Select Product --</option>
                <?php while($row = $products->fetch_assoc()):
                    $available = $row['stock_qty'] ?? 0; ?>
                    <option value="<?= $row['id'] ?>">
                        <?= $row['name'] ?> (<?= $row['sku'] ?>) - Available: <?= $available ?>
                    </option>
                <?php endwhile; ?>
            </select>
        </div>
        <div class="col-md-3">
            <label>Qty</label>
            <input type="number" name="qty" min="1" value="1" class="form-control" required>
        </div>
        <div class="col-md-3 mt-4">
            <button type="submit" name="add_to_cart" class="btn btn-success w-100">
                <i class="fa fa-plus"></i> Add to Cart
            </button>
        </div>
    </form>

    <!-- Cart Table -->
    <?php if(!empty($_SESSION['hk_cart'])): ?>
        <h5>Items in Requisition</h5>
        <table class="table table-bordered table-striped">
            <thead class="bg-dark text-white">
                <tr>
                    <th>#</th>
                    <th>SKU</th>
                    <th>Product</th>
                    <th>Qty</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($_SESSION['hk_cart'] as $i=>$item): ?>
                    <tr>
                        <td><?= $i+1 ?></td>
                        <td><?= $item['sku'] ?></td>
                        <td><?= $item['name'] ?></td>
                        <td><?= $item['qty'] ?></td>
                        <td>
                            <a href="hk_requisition_request.php?remove=<?= $i ?>" class="btn btn-danger btn-sm">
                                Remove
                            </a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <form method="POST">
            <button type="submit" name="submit_requisition" class="btn btn-primary w-100">
                <i class="fa fa-check"></i> Submit Requisition
            </button>
        </form>
    <?php endif; ?>
</div>

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