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

$user_id = $_SESSION['user_id'] ?? 0;

// Handle bulk form submission
if(isset($_POST['products']) && is_array($_POST['products'])){
    $errors = [];
    $inserted = 0;

    foreach($_POST['products'] as $pid){
        $qty = intval($_POST['quantities'][$pid] ?? 0);
        $reason = $conn->real_escape_string($_POST['reason'][$pid] ?? '');

        if($qty > 0){
            $stmt = $conn->prepare("
                INSERT INTO purchase_requests 
                (product_id, requested_by, quantity, reason, created_at, status) 
                VALUES (?, ?, ?, ?, NOW(), 'Pending')
            ");
            $stmt->bind_param("iiis", $pid, $user_id, $qty, $reason);
            if($stmt->execute()){
                $inserted++;
            } else {
                $errors[] = "Product ID $pid: ".$stmt->error;
            }
        }
    }

    if($inserted > 0){
        echo "<script>alert('Purchase request(s) submitted successfully!'); window.location='purchase_request_hk.php?print=1';</script>";
        exit;
    } elseif(!empty($errors)){
        echo "<div class='alert alert-danger'>Errors:<br>".implode('<br>', $errors)."</div>";
    }
}

// Fetch all products (low or out of stock) for housekeeping
$department_id = 6; // housekeeping
$products = $conn->query("
    SELECT p.id, p.name, p.sku, p.buying_price, ps.quantity, IFNULL(ps.reorder_level,5) AS reorder_level
    FROM products p
    INNER JOIN product_stock ps ON ps.product_id=p.id
    WHERE ps.department_id=$department_id
    ORDER BY p.name ASC
");

// Printable template
if(isset($_GET['print']) && $_GET['print']==1){
    $requests = $conn->query("
        SELECT pr.*, p.name, p.sku, p.buying_price, u.username
        FROM purchase_requests pr
        JOIN products p ON pr.product_id=p.id
        JOIN users u ON pr.requested_by=u.id
        WHERE pr.requested_by=$user_id AND pr.status='Pending'
        ORDER BY pr.created_at DESC
    ");

    $total_amount = 0;

    echo "<div class='container mt-4'>
            <h4 class='mb-3'>🧹 Purchase Request Template</h4>
            <table class='table table-bordered table-striped'>
                <thead class='bg-dark text-white'>
                    <tr>
                        <th>SKU</th>
                        <th>Product</th>
                        <th>Buying Price</th>
                        <th>Quantity</th>
                        <th>Amount</th>
                        <th>Reason</th>
                        <th>Requested By</th>
                    </tr>
                </thead>
                <tbody>";

    while($r = $requests->fetch_assoc()){
        $amount = $r['buying_price'] * $r['quantity'];
        $total_amount += $amount;

        echo "<tr>
            <td>".htmlspecialchars($r['sku'])."</td>
            <td>".htmlspecialchars($r['name'])."</td>
            <td>".number_format($r['buying_price'], 2)."</td>
            <td>".intval($r['quantity'])."</td>
            <td>".number_format($amount, 2)."</td>
            <td>".htmlspecialchars($r['reason'])."</td>
            <td>".htmlspecialchars($r['username'])."</td>
        </tr>";
    }

    echo "<tr class='table-success'>
            <td colspan='4' class='text-end'><strong>Total Amount:</strong></td>
            <td colspan='3'><strong>".number_format($total_amount,2)."</strong></td>
          </tr>";

    echo "</tbody></table>
          <button class='btn btn-secondary' onclick='window.print()'>Print Template</button>
          </div>";
    include 'includes/footer.php';
    exit;
}

?>

<div class="container mt-4">
    <button class="btn btn-secondary btn-custom mb-3" onclick="history.back()">
        <i class="fa fa-arrow-left"></i> Back
    </button>

    <h4 class="mb-3">🧹 Bulk Purchase Request</h4>

    <form method="POST">
        <table class="table table-bordered table-striped table-hover">
            <thead class="bg-dark text-white">
                <tr>
                    <th>#</th>
                    <th>SKU</th>
                    <th>Product</th>
                    <th>Buying Price</th>
                    <th>Available Qty</th>
                    <th>Reorder Level</th>
                    <th>Request Qty</th>
                    <th>Reason</th>
                    <th>Select</th>
                </tr>
            </thead>
            <tbody>
            <?php $i=1; while($p = $products->fetch_assoc()): ?>
                <tr>
                    <td><?= $i ?></td>
                    <td><?= htmlspecialchars($p['sku']) ?></td>
                    <td><?= htmlspecialchars($p['name']) ?></td>
                    <td><?= number_format($p['buying_price'], 2) ?></td>
                    <td><?= intval($p['quantity']) ?></td>
                    <td><?= intval($p['reorder_level']) ?></td>
                    <td>
                        <input type="number" min="1" name="quantities[<?= $p['id'] ?>]" class="form-control form-control-sm" style="width:80px;">
                    </td>
                    <td>
                        <input type="text" name="reason[<?= $p['id'] ?>]" class="form-control form-control-sm">
                    </td>
                    <td>
                        <input type="checkbox" name="products[]" value="<?= $p['id'] ?>">
                    </td>
                </tr>
            <?php $i++; endwhile; ?>
            </tbody>
        </table>
        <button type="submit" class="btn btn-warning">Submit Purchase Requests</button>
    </form>
</div>

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