<?php require_once dirname(__DIR__, 2) . '/dripend/config/config.php'; 
require_once dirname(__DIR__, 2) . '/includes/db.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Delete 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-5">
            <div class="row justify-content-center">
                <div class="col-md-6">
                    
                    <div id="prDeleteMessage" class="d-none alert shadow-sm mb-4 rounded-3 border-0"></div>
                    
                    <div class="card border-danger shadow text-center">
                        <div class="card-header bg-danger text-white fw-bold text-uppercase py-3">
                            <i class="fa-solid fa-triangle-exclamation me-2"></i> Critical Action Warning
                        </div>
                        <div class="card-body py-5">
                            <i class="fa-solid fa-trash-can text-danger mb-3" style="font-size: 3rem;"></i>
                            <h4 class="card-title fw-bold">Permanent Deletion</h4>
                            <p class="card-text text-muted mb-4">You are about to permanently delete Requisition: <br> <strong id="del_pr_no" class="text-dark fs-4 font-monospace">Loading...</strong></p>
                            
                            <form id="purchaseRequisitionDeleteForm" autocomplete="off">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" id="del_pr_id" value="">
                                
                                <div class="d-flex justify-content-center gap-3 mt-4">
                                    <a href="listPurchaseRequisition.php" class="btn btn-secondary px-4 fw-bold shadow-sm">Cancel</a>
                                    <button type="submit" id="btnConfirmDelete" class="btn btn-danger px-4 fw-bold shadow-sm" disabled>Yes, Delete Record</button>
                                </div>
                            </form>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

    <!-- SELF-CONTAINED JAVASCRIPT LOGIC -->
    <script>
        
        document.addEventListener("DOMContentLoaded", async () => {
            const urlParams = new URLSearchParams(window.location.search);
            const id = urlParams.get('id');
            const msgBox = document.getElementById('prDeleteMessage');
            const btn = document.getElementById('btnConfirmDelete');

            if (!id) {
                msgBox.className = 'alert alert-danger d-block shadow-sm';
                msgBox.innerHTML = '<i class="fa-solid fa-triangle-exclamation me-2"></i> Error: No Requisition ID provided.';
                return;
            }

            try {
                // Pre-fetch to verify existence and get the Requisition Number
                const res = await fetch(`${PR_API_PATH}?action=get_single&id=${id}`);
                const payload = await res.json();

                if (payload.status === 'success') {
                    document.getElementById('del_pr_id').value = id;
                    document.getElementById('del_pr_no').textContent = payload.data.header.requisition_no;
                    btn.disabled = false; // Enable delete button only if record valid
                } else {
                    throw new Error(payload.message);
                }
            } catch (err) {
                msgBox.className = 'alert alert-danger d-block shadow-sm';
                msgBox.innerHTML = `<i class="fa-solid fa-triangle-exclamation me-2"></i> ${err.message}`;
                document.getElementById('del_pr_no').textContent = "ERROR";
            }

            // Form Submit Interceptor
            const frm = document.getElementById('purchaseRequisitionDeleteForm');
            if (frm) {
                frm.addEventListener('submit', async function(e) {
                    e.preventDefault();
                    
                    btn.disabled = true; 
                    btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-2"></i> Deleting...';
                    
                    try {
                        const res = await fetch(PR_POST_PATH, { method: 'POST', body: new FormData(frm) });
                        const json = await res.json();
                        
                        if (json.status === 'success') {
                            msgBox.className = 'alert alert-success d-block shadow-sm'; 
                            msgBox.innerHTML = `<i class="fa-solid fa-check-circle me-2"></i> ${json.message}`;
                            // Automatically route user back to the list after success
                            setTimeout(() => { window.location.href = "listPurchaseRequisition.php"; }, 1500);
                        } else {
                            throw new Error(json.message);
                        }
                    } catch (err) {
                        msgBox.className = 'alert alert-danger d-block shadow-sm'; 
                        msgBox.innerHTML = `<i class="fa-solid fa-triangle-exclamation me-2"></i> ${err.message}`;
                        btn.disabled = false; 
                        btn.innerHTML = 'Yes, Delete Record';
                    }
                });
            }
        });
    </script>
</body>
</html>