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

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

// ==================== Handle Add to Cart ====================
if(isset($_POST['add_to_cart'])){
    $product_id = intval($_POST['product_id']);
    $qty        = intval($_POST['qty'] ?? 0);

    if($qty <= 0){
        echo "<script>alert('Quantity must be at least 1');</script>";
    } else {

        $product = $conn->query("
            SELECT p.*, COALESCE(SUM(ps.quantity),0) AS stock_qty
            FROM products p
            LEFT JOIN product_stock ps 
                ON p.id = ps.product_id
                AND ps.department_id = 1
            WHERE p.id=$product_id
            GROUP BY p.id
        ")->fetch_assoc();

        if(!$product){
            echo "<script>alert('Product not found');</script>";
        } elseif($qty > $product['stock_qty']){
            echo "<script>alert('⚠️ Not enough stock! Available: {$product['stock_qty']}');</script>";
        } else {

            $found = false;

            if(!empty($_SESSION['res_cart'])){
                foreach($_SESSION['res_cart'] as &$item){
                    if($item['id'] == $product_id){
                        $item['qty'] += $qty;
                        $found = true;
                        break;
                    }
                }
            }

            if(!$found){
                $_SESSION['res_cart'][] = [
                    'id'   => $product_id,
                    'name' => $product['name'],
                    'sku'  => $product['sku'],
                    'qty'  => $qty
                ];
            }
        }
    }
}

// ==================== Remove Item ====================
if(isset($_GET['remove'])){
    unset($_SESSION['res_cart'][$_GET['remove']]);
    $_SESSION['res_cart'] = array_values($_SESSION['res_cart']);
}

// ==================== Submit Requisition ====================
if(isset($_POST['submit_requisition']) && !empty($_SESSION['res_cart'])){

    $conn->begin_transaction();

    try {

        $conn->query("
            INSERT INTO restaurant_requisitions(requested_by, status, created_at) 
            VALUES($user_id,'Pending',NOW())
        ");
        $requisition_id = $conn->insert_id;

        $email_rows = "";

        foreach($_SESSION['res_cart'] as $item){

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

            $stock = $conn->query("
                SELECT COALESCE(SUM(quantity),0) AS qty
                FROM product_stock
                WHERE product_id=$pid AND department_id=1
            ")->fetch_assoc()['qty'];

            if($qty > $stock){
                throw new Exception("Not enough stock for {$item['name']}. Available: $stock");
            }

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

            $email_rows .= "<tr>
                                <td>{$item['name']}</td>
                                <td>{$item['qty']}</td>
                            </tr>";
        }

        $conn->commit();

        // ===== EMAIL =====
        $to = "kondwanichimatiro@gmail.com, giantplusmw@gmail.com";
        $subject = "New Restaurant Requisition #".$requisition_id;

        $message = "
        <html><body>
        <h3>Restaurant Requisition Submitted</h3>
        <p><b>Requested By:</b> $username</p>
        <p><b>Requisition ID:</b> $requisition_id</p>
        <table border='1' cellpadding='6' cellspacing='0' width='100%'>
            <tr style='background:#28a745;color:#fff;'>
                <th>Product</th>
                <th>Quantity</th>
            </tr>
            $email_rows
        </table>
        </body></html>
        ";

        $headers  = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8\r\n";
        $headers .= "From: Hotel System <no-reply@yourdomain.com>\r\n";

        @mail($to, $subject, $message, $headers);

        $_SESSION['res_cart'] = [];

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

    } catch(Exception $e){
        $conn->rollback();
        echo "<script>alert('❌ ".$e->getMessage()."');</script>";
    }
}

// ==================== Fetch Products ====================
$products = $conn->query("
    SELECT p.*, COALESCE(SUM(ps.quantity),0) AS stock_qty
    FROM products p
    LEFT JOIN product_stock ps 
        ON p.id = ps.product_id
        AND ps.department_id = 1
    GROUP BY p.id
    HAVING stock_qty > 0
    ORDER BY p.name ASC
");

// ==================== Fetch Requisitions ====================
$requisitions = $conn->query("
    SELECT r.*, u.username AS requested_by_name
    FROM restaurant_requisitions r
    LEFT JOIN users u ON r.requested_by = u.id
    WHERE r.requested_by = $user_id
    ORDER BY r.created_at DESC
");
?>

<div class="container mt-4">

<h3 class="text-center mb-3">
    <i class="fa fa-utensils text-success"></i> Restaurant Requisition
</h3>

<!-- ADD PRODUCT -->
<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()): ?>
                <option value="<?= $row['id'] ?>">
                    <?= htmlspecialchars($row['name']) ?>
                    (<?= $row['sku'] ?>)
                    - Stock: <?= $row['stock_qty'] ?>
                </option>
            <?php endwhile; ?>
        </select>
    </div>

    <div class="col-md-3">
        <label>Quantity</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 -->
<?php if(!empty($_SESSION['res_cart'])): ?>
<table class="table table-bordered">
<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['res_cart'] as $i=>$item): ?>
<tr>
<td><?= $i+1 ?></td>
<td><?= htmlspecialchars($item['sku']) ?></td>
<td><?= htmlspecialchars($item['name']) ?></td>
<td><?= $item['qty'] ?></td>
<td>
<a href="?remove=<?= $i ?>" class="btn btn-danger btn-sm">
<i class="fa fa-trash"></i>
</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-circle"></i> Submit Requisition
</button>
</form>
<?php endif; ?>

<hr>

<!-- ================= PREVIOUS ================= -->
<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>Print</th>
</tr>
</thead>
<tbody>

<?php while($r = $requisitions->fetch_assoc()): ?>
<tr>
<td><?= $r['id'] ?></td>
<td><?= $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>";
elseif($r['status']=='Rejected')
    echo "<span class='badge bg-danger'>Rejected</span>";
?>
</td>
<td>
<a href="print_restaurant_requisition.php?id=<?= $r['id'] ?>"
   target="_blank"
   class="btn btn-primary btn-sm">
   <i class="fa fa-print"></i> Print
</a>
</td>
</tr>
<?php endwhile; ?>

</tbody>
</table>

</div>

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