<?php 
require_once dirname(__DIR__, 2) . '/dripend/config/config.php'; 
require_once dirname(__DIR__, 2) . '/dripend/includes/db.php'; 

$id = isset($_GET['id']) ? (int)$_GET['id'] : (isset($_POST['pr_id']) ? (int)$_POST['pr_id'] : 0);
$message = ''; $msgType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update') {
    $conn->begin_transaction();
    try {
        $store_id = (int)($_POST['store_id'] ?? 0);
        $req_date = $conn->real_escape_string($_POST['request_date'] ?? date('Y-m-d'));
        $need_date = $conn->real_escape_string($_POST['required_date'] ?? date('Y-m-d'));
        $priority = $conn->real_escape_string($_POST['priority'] ?? 'Routine');
        $justification = $conn->real_escape_string(trim($_POST['justification'] ?? ''));
        $est_total = (float)($_POST['estimated_total_value'] ?? 0);

        if ($store_id <= 0 || empty($_POST['service_id'])) throw new Exception("Store selection or payload missing.");

        // CRITICAL WORKFLOW FIX: Force status back to 'Pending Approval' so it returns to the Dashboard
        $stmtUpd = $conn->prepare("UPDATE purchase_requisitions SET store_id=?, request_date=?, required_date=?, priority=?, justification=?, estimated_total_value=?, status='Pending Approval' WHERE id=? AND status IN ('Draft', 'Pending Approval')");
        $stmtUpd->bind_param("issssdi", $store_id, $req_date, $need_date, $priority, $justification, $est_total, $id);
        $stmtUpd->execute();
        if ($stmtUpd->affected_rows === 0 && $stmtUpd->error) throw new Exception("Update failed. Record may be locked or approved.");
        
        $conn->query("DELETE FROM purchase_requisition_items WHERE requisition_id = $id");
        $stmtItem = $conn->prepare("INSERT INTO purchase_requisition_items (requisition_id, service_id, requested_quantity, estimated_unit_cost) VALUES (?, ?, ?, ?)");
        foreach ($_POST['service_id'] as $idx => $sid) {
            $s = (int)$sid; $q = (int)($_POST['quantity'][$idx] ?? 0); $c = (float)($_POST['unit_cost'][$idx] ?? 0);
            if ($s > 0 && $q > 0) { $stmtItem->bind_param("iiid", $id, $s, $q, $c); $stmtItem->execute(); }
        }
        $conn->commit();
        $message = "Requisition Updated and Resubmitted for Approval."; $msgType = "success";
    } catch (Exception $e) {
        $conn->rollback();
        $message = $e->getMessage(); $msgType = "danger";
    }
}

// Fetch Existing
$header = null; $items = []; $stores = []; $priorities = []; $products = [];
if ($id > 0) {
    $resHead = $conn->query("SELECT * FROM purchase_requisitions WHERE id = $id");
    if ($resHead && $resHead->num_rows > 0) $header = $resHead->fetch_assoc();
    $resItems = $conn->query("SELECT * FROM purchase_requisition_items WHERE requisition_id = $id");
    if ($resItems) { while($row = $resItems->fetch_assoc()) $items[] = $row; }
}
$s_res = $conn->query("SELECT id, store_name as name FROM stores WHERE is_active = 1 ORDER BY store_name ASC");
if ($s_res) { while ($s = $s_res->fetch_assoc()) $stores[] = $s; }
$p_res = $conn->query("SELECT p.id, p.generic_name as name, MAX(pv.purchase_price) as est_price FROM products p LEFT JOIN product_variants pv ON p.id = pv.product_id WHERE p.is_active = 1 GROUP BY p.id ORDER BY p.generic_name ASC");
if ($p_res) { while ($p = $p_res->fetch_assoc()) $products[] = $p; }
$enum_res = $conn->query("SHOW COLUMNS FROM purchase_requisitions LIKE 'priority'");
if ($enum_res && $row = $enum_res->fetch_assoc()) { preg_match_all("/'([^']+)'/", $row['Type'], $matches); $priorities = $matches[1] ?? []; }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"><title>Update Requisition | RiMax</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <style>body{background:#f8fafc;font-family:'Inter',sans-serif;margin:0;} .main-content{margin-left:300px;padding:20px;min-height:100vh;} @media(max-width:1024px){.main-content{margin-left:0;}}</style>
</head>
<body>
    <?php include(dirname(__DIR__, 2) . '/dripend/statpages/sidebar.php'); ?>
    <div class="main-content">
        <div class="container-fluid py-2">
            <div class="d-flex justify-content-between align-items-center mb-4 pb-3 border-bottom">
                <div><h2 class="h4 text-dark fw-bold m-0"><i class="fa-solid fa-pen-to-square text-primary me-2"></i>Update Requisition</h2></div>
                <a href="listPurchaseRequisition.php" class="btn btn-light border fw-bold">Back to List</a>
            </div>
            
            <?php if($message): ?><div class="alert alert-<?= $msgType ?> shadow-sm mb-4 border-0"><i class="fa-solid fa-circle-info me-2"></i> <?= htmlspecialchars($message) ?></div><?php endif; ?>

            <?php if($header): ?>
            <form action="" method="POST" class="bg-white p-4 rounded-3 border shadow-sm" autocomplete="off" onsubmit="return validateUpdForm()">
                <input type="hidden" name="action" value="update"><input type="hidden" name="pr_id" value="<?= $id ?>">
                <div class="row g-3 mb-4 bg-light-subtle p-3 rounded border">
                    <div class="col-md-3"><label class="form-label small fw-bold">Request Date</label><input type="date" name="request_date" class="form-control" value="<?= htmlspecialchars($header['request_date']) ?>" required></div>
                    <div class="col-md-3"><label class="form-label small fw-bold">Required By *</label><input type="date" name="required_date" class="form-control border-primary" value="<?= htmlspecialchars($header['required_date']) ?>" required></div>
                    <div class="col-md-3"><label class="form-label small fw-bold">Store *</label>
                        <select name="store_id" class="form-select" required><option value="">-- Select Store --</option><?php foreach($stores as $s): ?><option value="<?= $s['id'] ?>" <?= $s['id'] == $header['store_id'] ? 'selected' : '' ?>><?= htmlspecialchars($s['name']) ?></option><?php endforeach; ?></select>
                    </div>
                    <div class="col-md-3"><label class="form-label small fw-bold">Priority</label>
                        <select name="priority" class="form-select"><?php foreach($priorities as $p): ?><option value="<?= $p ?>" <?= $p == $header['priority'] ? 'selected' : '' ?>><?= htmlspecialchars($p) ?></option><?php endforeach; ?></select>
                    </div>
                    <div class="col-12 mt-2"><label class="form-label small fw-bold">Justification *</label><input type="text" name="justification" class="form-control" value="<?= htmlspecialchars($header['justification']) ?>" required></div>
                </div>

                <div class="table-responsive mb-4">
                    <table class="table table-bordered align-middle table-sm" id="upd_prItemsTable">
                        <thead class="table-dark small text-center"><tr><th class="text-start">Item</th><th>Qty</th><th>Cost</th><th>Total</th><th>Act</th></tr></thead>
                        <tbody id="upd_prItemsBody">
                            <?php $rc = 0; foreach($items as $i): $rc++; ?>
                                <tr id="u_row_<?= $rc ?>">
                                    <td><select name="service_id[]" class="form-select form-select-sm" onchange="setUpdPrice(this, <?= $rc ?>)" required><option value="">-- Select --</option><?php foreach($products as $p): ?><option value="<?= $p['id'] ?>" data-price="<?= $p['est_price'] ?? 0 ?>" <?= $p['id'] == $i['service_id'] ? 'selected' : '' ?>><?= htmlspecialchars($p['name']) ?></option><?php endforeach; ?></select></td>
                                    <td><input type="number" name="quantity[]" id="u_qty_<?= $rc ?>" value="<?= $i['requested_quantity'] ?>" class="form-control form-control-sm text-center fw-bold" min="1" oninput="calcUpdTotals()" required></td>
                                    <td><input type="number" step="0.01" name="unit_cost[]" id="u_cost_<?= $rc ?>" value="<?= $i['estimated_unit_cost'] ?>" class="form-control form-control-sm text-end" oninput="calcUpdTotals()" required></td>
                                    <td><input type="text" id="u_line_total_<?= $rc ?>" class="form-control form-control-sm text-end fw-bold bg-light" readonly></td>
                                    <td class="text-center"><button type="button" class="btn btn-sm btn-danger py-1 px-2" onclick="document.getElementById('u_row_<?= $rc ?>').remove(); calcUpdTotals();"><i class="fa-solid fa-times"></i></button></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <button type="button" class="btn btn-sm btn-outline-primary fw-bold" onclick="addUpdRow()"><i class="fa-solid fa-plus me-1"></i> Add Line</button>
                </div>
                <div class="text-end mb-4"><span class="d-block small fw-bold">Total Value</span><h4 class="m-0 text-danger fw-bold">GH₵ <span id="upd_summary_total">0.00</span></h4><input type="hidden" name="estimated_total_value" id="upd_hidden_total" value="0"></div>
                <div class="text-end"><button type="submit" id="btnUpdatePr" class="btn btn-warning px-5 fw-bold text-dark"><i class="fa-solid fa-save me-2"></i> Save & Resubmit</button></div>
            </form>
            <?php endif; ?>
        </div>
    </div>
    
    <script>
        const jsProducts = <?= json_encode($products) ?>; let rowCounter = <?= $rc ?? 0 ?>;
        function addUpdRow() {
            rowCounter++; let opts = '<option value="" selected disabled>-- Select Item --</option>';
            jsProducts.forEach(p => { opts += `<option value="${p.id}" data-price="${p.est_price || 0}">${p.name}</option>`; });
            document.getElementById('upd_prItemsBody').insertAdjacentHTML('beforeend', `<tr id="u_row_${rowCounter}"><td><select name="service_id[]" class="form-select form-select-sm" onchange="setUpdPrice(this, ${rowCounter})" required>${opts}</select></td><td><input type="number" name="quantity[]" id="u_qty_${rowCounter}" value="1" class="form-control form-control-sm text-center fw-bold" min="1" oninput="calcUpdTotals()" required></td><td><input type="number" step="0.01" name="unit_cost[]" id="u_cost_${rowCounter}" value="0.00" class="form-control form-control-sm text-end" oninput="calcUpdTotals()" required></td><td><input type="text" id="u_line_total_${rowCounter}" class="form-control form-control-sm text-end fw-bold bg-light" readonly></td><td class="text-center"><button type="button" class="btn btn-sm btn-danger py-1 px-2" onclick="document.getElementById('u_row_${rowCounter}').remove(); calcUpdTotals();"><i class="fa-solid fa-times"></i></button></td></tr>`);
        }
        function setUpdPrice(el, idx) {
            const val = el.value;
            if (val) {
                let cnt = 0; document.querySelectorAll('#upd_prItemsBody select[name="service_id[]"]').forEach(s => { if (s.value === val) cnt++; });
                if (cnt > 1) { alert("Product already selected."); el.value = ""; document.getElementById(`u_cost_${idx}`).value = ""; calcUpdTotals(); return; }
            }
            document.getElementById(`u_cost_${idx}`).value = parseFloat(el.options[el.selectedIndex].getAttribute('data-price') || 0).toFixed(2); calcUpdTotals();
        }
        function calcUpdTotals() {
            let t = 0;
            document.querySelectorAll('#upd_prItemsBody input[name="quantity[]"]').forEach((q, i) => {
                const c = document.querySelectorAll('#upd_prItemsBody input[name="unit_cost[]"]')[i];
                const l = (parseFloat(q.value)||0)*(parseFloat(c.value)||0); q.closest('tr').querySelector('input[id^="u_line_total_"]').value = l.toFixed(2); t+=l;
            });
            document.getElementById('upd_summary_total').textContent = t.toLocaleString(undefined, {minimumFractionDigits: 2}); document.getElementById('upd_hidden_total').value = t.toFixed(2);
        }
        function validateUpdForm() {
            const s = Array.from(document.querySelectorAll('#upd_prItemsBody select[name="service_id[]"]')).map(x=>x.value).filter(v=>v!=="");
            if(s.length !== new Set(s).size) { alert("Duplicate items detected."); return false; }
            document.getElementById('btnUpdatePr').innerHTML = 'Processing...'; return true;
        }
        document.addEventListener("DOMContentLoaded", calcUpdTotals);
    </script>
</body>
</html>