<?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'] : 0;
$error = null; $header = null; $items = []; $logs = [];

if ($id > 0) {
    // Fetch Header
    $stmt = $conn->prepare("SELECT pr.*, s.store_name, CONCAT(st.first_name, ' ', st.last_name) as staff_name FROM purchase_requisitions pr LEFT JOIN stores s ON pr.store_id = s.id LEFT JOIN staff st ON pr.requested_by = st.staff_id WHERE pr.id = ?");
    $stmt->bind_param("i", $id); $stmt->execute();
    $res = $stmt->get_result();
    if ($res && $res->num_rows > 0) {
        $header = $res->fetch_assoc();
        
        // Fetch Items
        $resItems = $conn->query("SELECT pri.*, p.generic_name as name FROM purchase_requisition_items pri LEFT JOIN products p ON pri.service_id = p.id WHERE pri.requisition_id = $id");
        if($resItems) { while($row = $resItems->fetch_assoc()) $items[] = $row; }

        // Fetch Audit Approval Logs
        $logRes = $conn->query("SELECT a.*, CONCAT(st.first_name, ' ', st.last_name) as approver_name FROM purchase_requisition_approvals a LEFT JOIN staff st ON a.approved_by = st.staff_id WHERE a.requisition_id = $id ORDER BY a.approval_date ASC");
        if($logRes) { while($l = $logRes->fetch_assoc()) $logs[] = $l; }

    } else $error = "Requisition not found in database.";
} else $error = "Invalid Requisition ID.";

$badge = 'bg-secondary';
if ($header && $header['status'] === 'Approved') $badge = 'bg-success';
if ($header && in_array($header['status'], ['Rejected', 'Cancelled'])) $badge = 'bg-danger';
if ($header && $header['status'] === 'Pending Approval') $badge = 'bg-warning text-dark';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"><title>View 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">
            
            <?php if($error): ?>
                <div class="alert alert-danger shadow-sm mb-3"><i class="fa-solid fa-triangle-exclamation me-2"></i> <?= htmlspecialchars($error) ?></div>
            <?php endif; ?>

            <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-file-invoice text-primary me-2"></i>Requisition: <span class="text-primary font-monospace"><?= $header ? htmlspecialchars($header['requisition_no']) : 'N/A' ?></span></h2>
                </div>
                <div class="d-flex gap-2">
                    <button class="btn btn-outline-secondary fw-bold shadow-sm" onclick="window.print()"><i class="fa-solid fa-print me-1"></i> Print</button>
                    <a href="listPurchaseRequisition.php" class="btn btn-light border fw-bold shadow-sm">Back to List</a>
                </div>
            </div>

            <?php if($header): ?>
            <div class="row g-3 mb-4">
                <div class="col-md-8">
                    <div class="bg-white p-4 rounded-3 border shadow-sm h-100">
                        <h6 class="fw-bold text-secondary mb-3 border-bottom pb-2">Header Information</h6>
                        <div class="row g-3">
                            <div class="col-md-6"><span class="small text-muted d-block">Requesting Store</span><strong><?= htmlspecialchars($header['store_name'] ?? 'N/A') ?></strong></div>
                            <div class="col-md-6"><span class="small text-muted d-block">Requested By</span><strong><?= htmlspecialchars($header['staff_name'] ?? 'System') ?></strong></div>
                            <div class="col-md-4"><span class="small text-muted d-block">Request Date</span><strong><?= htmlspecialchars($header['request_date']) ?></strong></div>
                            <div class="col-md-4"><span class="small text-muted d-block">Required By Date</span><strong class="text-danger"><?= htmlspecialchars($header['required_date']) ?></strong></div>
                            <div class="col-md-4"><span class="small text-muted d-block">Priority Level</span><strong><?= htmlspecialchars($header['priority']) ?></strong></div>
                            <div class="col-12"><span class="small text-muted d-block">Justification</span><span class="text-dark bg-light p-2 rounded d-block border"><?= htmlspecialchars($header['justification']) ?></span></div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="bg-white p-4 rounded-3 border shadow-sm h-100 d-flex flex-column justify-content-center text-center">
                        <span class="small text-muted text-uppercase fw-bold mb-2">Current Status</span>
                        <div class="mb-4"><span class="badge <?= $badge ?> fs-5 px-3 py-2 shadow-sm"><?= htmlspecialchars($header['status']) ?></span></div>
                        <span class="small text-muted text-uppercase fw-bold mb-1">Total Estimated Value</span>
                        <h2 class="text-danger fw-bold m-0">GH₵ <?= number_format($header['estimated_total_value'], 2) ?></h2>
                    </div>
                </div>
            </div>

            <div class="bg-white p-4 rounded-3 border shadow-sm mb-4">
                <h6 class="fw-bold text-secondary mb-3"><i class="fa-solid fa-cart-flatbed me-2"></i>Requested Line Items</h6>
                <div class="table-responsive">
                    <table class="table table-bordered align-middle table-sm m-0">
                        <thead class="table-dark small text-center"><tr><th class="text-start">Product Catalog Item</th><th>Requested Qty</th><th class="text-end">Est. Unit (GH₵)</th><th class="text-end">Est. Total (GH₵)</th></tr></thead>
                        <tbody>
                            <?php foreach($items as $item): $lineTotal = $item['requested_quantity'] * $item['estimated_unit_cost']; ?>
                                <tr>
                                    <td class="fw-bold text-primary"><?= htmlspecialchars($item['name']) ?></td>
                                    <td class="text-center fw-bold"><?= htmlspecialchars($item['requested_quantity']) ?></td>
                                    <td class="text-end"><?= number_format($item['estimated_unit_cost'], 2) ?></td>
                                    <td class="text-end fw-bold bg-light"><?= number_format($lineTotal, 2) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="bg-white p-4 rounded-3 border shadow-sm">
                <h6 class="fw-bold text-secondary mb-3"><i class="fa-solid fa-timeline me-2"></i>Approval Audit History</h6>
                <div class="table-responsive">
                    <table class="table table-sm m-0">
                        <thead class="table-light small text-uppercase text-muted"><tr><th>Date & Time</th><th>Action By</th><th>Decision</th><th>Remarks / Comments</th></tr></thead>
                        <tbody>
                            <?php if(empty($logs)): ?>
                                <tr><td colspan="4" class="text-center py-3 text-muted">No approval logs found.</td></tr>
                            <?php else: ?>
                                <?php foreach($logs as $log): 
                                    $lBadge = 'bg-secondary';
                                    if($log['decision'] === 'Approved') $lBadge = 'bg-success';
                                    if($log['decision'] === 'Returned') $lBadge = 'bg-warning text-dark';
                                    if($log['decision'] === 'Rejected') $lBadge = 'bg-danger';
                                ?>
                                    <tr>
                                        <td class="text-muted small fw-bold"><?= date('M d, Y h:i A', strtotime($log['approval_date'])) ?></td>
                                        <td class="fw-bold"><?= htmlspecialchars($log['approver_name'] ?? 'System') ?></td>
                                        <td><span class="badge <?= $lBadge ?>"><?= $log['decision'] ?></span></td>
                                        <td class="text-secondary"><?= htmlspecialchars($log['comments'] ?? 'No comments provided.') ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>