<?php
include 'includes/auth.php';
include 'db.php';
include 'phpqrcode/qrlib.php';

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

$ticked_items = $_POST['tick'] ?? [];
$replenish = $_POST['replenish'] ?? [];

if(empty($ticked_items)){
    die("<p>No items selected for printing.</p>");
}

// ================== INSERT REQUISITION ==================
$stmt = $conn->prepare("INSERT INTO low_stock_requisitions (requested_by) VALUES (?)");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$requisition_id = $stmt->insert_id; // get last inserted id

// ================== INSERT ITEMS ==================
$item_stmt = $conn->prepare("INSERT INTO low_stock_requisition_items (requisition_id, product_id, quantity) VALUES (?, ?, ?)");
foreach($ticked_items as $product_id => $val){
    $qty = intval($replenish[$product_id] ?? 1);
    $item_stmt->bind_param("iii", $requisition_id, $product_id, $qty);
    $item_stmt->execute();
}

// ================== FETCH SELECTED ITEMS ==================
$ids = implode(',', array_map('intval', array_keys($ticked_items)));
$items = $conn->query("
    SELECT p.*, COALESCE(ps.quantity,0) AS stock_qty
    FROM products p
    LEFT JOIN product_stock ps 
        ON p.id = ps.product_id AND ps.store_id = 1
    WHERE p.id IN ($ids)
");

// ================== QR CODE ==================

?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Low Stock Requisition #<?= $requisition_id ?></title>
<style>
body{font-family: Arial, sans-serif; margin:30px; color:#000;}
.header{display:flex; justify-content:space-between; align-items:center; border-bottom:3px solid #000; padding-bottom:10px; margin-bottom:20px;}
.logo img{height:80px;}
.title{text-align:right; font-size:14px;}
.title h2{margin:0;}
.info{margin-top:10px; line-height:1.6;}
.qr{text-align:right; margin-top:10px;}
table{width:100%; border-collapse:collapse; margin-top:20px;}
th, td{border:1px solid #000; padding:8px; text-align:center;}
th{background:#f2f2f2;}
.footer{margin-top:70px; display:flex; justify-content:space-between;}
.signature{width:220px; border-top:1px solid #000; text-align:center; padding-top:6px; font-size:13px;}
.page-footer{position:fixed; bottom:10px; left:0; right:0; text-align:center; font-size:12px; color:#666;}
.print-btn{float:right; margin-bottom:10px;}
@media print{.print-btn{ display:none; } body{ margin:15px; }}
</style>
</head>
<body onload="window.print()">

<button onclick="window.print()" class="print-btn">🖨 Print</button>

<!-- HEADER -->
<div class="header">
    <div class="logo">
        <img src="assets/logo.png" onerror="this.style.display='none'">
    </div>
    <div class="title">
        <h2>RAMS EXECUTIVE LODGE</h2>
        Phone: 0993 899 382<br>
        Cell: 0889 899 382<br>
        https://ramslodgemw.com
    </div>
</div>

<!-- INFO -->
<div class="info">
    <strong>Requisition ID:</strong> #<?= $requisition_id ?><br>
    <strong>Prepared By:</strong> <?= htmlspecialchars($username) ?><br>
    <strong>Date:</strong> <?= date('d M Y H:i') ?><br>
</div>


<center><b>INVENTORY REPLENISHMENT REQUEST</b></center>

<!-- ITEMS TABLE -->
<?php
$grand_total = 0;
?>
<table>
<thead>
<tr>
    <th width="5%">#</th>
    <th width="15%">SKU</th>
    <th>Product</th>
    <th width="10%">Current Qty</th>
    <th width="12%">Buying Price</th>
    <th width="12%">Qty to Replenish</th>
    <th width="15%">Total Value</th>
</tr>
</thead>
<tbody>
<?php $i=1; while($p = $items->fetch_assoc()): ?>

<?php
$qty = intval($replenish[$p['id']] ?? 1);
$buying_price = floatval($p['buying_price']);
$total_value = $buying_price * $qty;
$grand_total += $total_value;
?>

<tr>
    <td><?= $i++ ?></td>
    <td><?= htmlspecialchars($p['sku']) ?></td>
    <td><?= htmlspecialchars($p['name']) ?></td>
    <td><?= intval($p['stock_qty']) ?></td>

    <td style="text-align:right;">
        MWK <?= number_format($buying_price,2) ?>
    </td>

    <td><?= $qty ?></td>

    <td style="text-align:right;">
        MWK <?= number_format($total_value,2) ?>
    </td>
</tr>

<?php endwhile; ?>
<?php if($i==1): ?>
<tr>
    <td colspan="7" style="text-align:center;">No items selected</td>
</tr>
<?php endif; ?>
<tr>
    <td colspan="6" style="text-align:right; font-weight:bold;">
        GRAND TOTAL
    </td>
    <td style="text-align:right; font-weight:bold;">
        MWK <?= number_format($grand_total,2) ?>
    </td>
</tr>
</tbody>
</table>
<div style="margin-top:20px; text-align:right; font-size:18px;">
    <strong>
        Estimated Requisition Cost:
        MWK <?= number_format($grand_total,2) ?>
    </strong>
</div>
<!-- SIGNATURES -->
<div class="footer">
    <div class="signature">Prepared By</div>
    <div class="signature">Approved By</div>
    <div class="signature">Store Issued By</div>
</div>

<div class="page-footer">
    Generated on <?= date('d M Y H:i') ?>
</div>

</body>
</html>