<?php
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once '../../../dripend/includes/db.php';

if (!isset($_GET['id']) || empty($_GET['id'])) {
    header("Location: listMedicine.php");
    exit;
}

$service_id = (int)$_GET['id'];
$message = '';

// ==============================================================================
// 1. HANDLE POST ACTIONS (MAP CORPORATE OR ENABLE NHIS)
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    
    // ACTION A: MAP NEW CORPORATE PROVIDER
    if ($_POST['action'] === 'map_insurance') {
        $ins_id = (int)$_POST['insurance_type_id'];
        $tariff = (float)$_POST['tariff_amount'];
        $req_copay = isset($_POST['is_copay_required']) ? 1 : 0;
        $copay_amt = $req_copay ? (float)$_POST['copay_amount'] : 0.00;

        $conn->begin_transaction();
        try {
            $stmt = $conn->prepare("INSERT INTO service_corporate_tariffs (service_id, insurance_type_id, tariff_amount, is_copay_required, copay_amount) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("iidid", $service_id, $ins_id, $tariff, $req_copay, $copay_amt);
            $stmt->execute();
            $stmt->close();

            $conn->query("UPDATE service_catalog SET corp_covered = 1 WHERE id = $service_id");

            $conn->commit();
            $message = "<div class='alert alert-success'><i class='fa-solid fa-link'></i> Corporate provider successfully mapped to this medicine!</div>";
        } catch (Exception $e) {
            $conn->rollback();
            $message = "<div class='alert alert-danger'><i class='fa-solid fa-triangle-exclamation'></i> Error mapping insurance: " . $e->getMessage() . "</div>";
        }
    }
    
    // ACTION B: ENABLE NHIS COVERAGE RETROACTIVELY
    elseif ($_POST['action'] === 'map_nhis') {
        $nhis_code = !empty($_POST['nhis_drug_code']) ? trim($_POST['nhis_drug_code']) : null;
        $p_level = !empty($_POST['prescribing_level']) ? trim($_POST['prescribing_level']) : null;
        $tariff = (float)$_POST['drug_tariff'];
        $req_copay = isset($_POST['is_nhis_copay_required']) ? 1 : 0;
        $copay_amt = $req_copay ? (float)$_POST['nhis_copay_amount'] : 0.00;

        try {
            // Drugs don't split by age, apply tariff to both for backend consistency
            $stmt = $conn->prepare("UPDATE service_catalog SET nhis_covered = 1, nhis_drug_code = ?, prescribing_level = ?, tariff_adult = ?, tariff_child = ?, is_copay_required = ?, copay_amount = ? WHERE id = ?");
            $stmt->bind_param("ssddidi", $nhis_code, $p_level, $tariff, $tariff, $req_copay, $copay_amt, $service_id);
            $stmt->execute();
            $stmt->close();

            $message = "<div class='alert alert-success'><i class='fa-solid fa-file-prescription'></i> NHIS Coverage successfully enabled for this medicine!</div>";
        } catch (Exception $e) {
            $message = "<div class='alert alert-danger'><i class='fa-solid fa-triangle-exclamation'></i> Error enabling NHIS: " . $e->getMessage() . "</div>";
        }
    }
}

// ==============================================================================
// 2. FETCH COMPLETE 360-DEGREE MEDICINE DATA
// ==============================================================================

// A. Master Catalog Details
$stmt = $conn->prepare("
    SELECT sc.*, d.department_name 
    FROM service_catalog sc 
    LEFT JOIN departments d ON sc.department_id = d.id 
    WHERE sc.id = ? AND sc.service_type = 'Drug'
");
$stmt->bind_param("i", $service_id);
$stmt->execute();
$medicine = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$medicine) {
    die("Medicine not found or is not a valid drug format.");
}

// B. Active Corporate Mappings
$mapped_stmt = $conn->prepare("
    SELECT sct.*, it.insurance_name 
    FROM service_corporate_tariffs sct 
    JOIN insurance_type it ON sct.insurance_type_id = it.id 
    WHERE sct.service_id = ?
    ORDER BY it.insurance_name ASC
");
$mapped_stmt->bind_param("i", $service_id);
$mapped_stmt->execute();
$mapped_insurances = $mapped_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$mapped_stmt->close();

// C. Available Unmapped Insurances (For Corporate Modal)
$unmapped_stmt = $conn->prepare("
    SELECT id, insurance_name FROM insurance_type 
    WHERE id NOT IN (SELECT insurance_type_id FROM service_corporate_tariffs WHERE service_id = ?) 
    AND LOWER(insurance_name) NOT IN ('nhis', 'cash') AND is_active = 1
    ORDER BY insurance_name ASC
");
$unmapped_stmt->bind_param("i", $service_id);
$unmapped_stmt->execute();
$unmapped_insurances = $unmapped_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$unmapped_stmt->close();

// D. Prescribing Levels (For NHIS Modal)
$levels_stmt = $conn->query("SELECT level_code, description FROM prescribing_levels WHERE is_active = 1 ORDER BY level_code ASC");
$prescribe_levels = $levels_stmt->fetch_all(MYSQLI_ASSOC);

// E. Price Audit Ledger
$history_stmt = $conn->prepare("
    SELECT * FROM medicine_price_history 
    WHERE service_id = ? 
    ORDER BY effective_date DESC, created_at DESC
");
$history_stmt->bind_param("i", $service_id);
$history_stmt->execute();
$price_history = $history_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$history_stmt->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Medicine Profile | Enterprise</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
    :root { --sidebar-width: 240px; --e-blue: #1e3a8a; --e-green: #16a34a; --bg: #f8fafc; --border: #e2e8f0; --text: #334155; }
    body { font-family: "Segoe UI", system-ui, sans-serif; background: var(--bg); margin: 0; padding: 0; color: var(--text); overflow-x: hidden; }
    
    .page-wrapper { position: absolute; top: 0; left: var(--sidebar-width); width: calc(100% - var(--sidebar-width)); min-height: 100vh; padding: 30px; box-sizing: border-box; }
    
    .header-bar { display: flex; justify-content: space-between; align-items: flex-end; margin-bottom: 25px; padding-bottom: 15px; border-bottom: 2px solid var(--border); }
    .header-info { display: flex; flex-direction: column; gap: 5px; }
    .header-info h2 { color: #0f172a; margin: 0; font-size: 26px; font-weight: 800; display:flex; align-items:center; gap:12px; }
    .header-info p { margin: 0; color: #64748b; font-weight: 600; font-size: 14px; }
    
    .primary-actions { display: flex; gap: 10px; }
    .btn { padding: 10px 18px; text-decoration: none; border-radius: 8px; font-weight: 700; transition: 0.2s; display: inline-flex; align-items: center; gap: 8px; border: none; font-size:13px; cursor: pointer; }
    .btn-edit { background: #f0fdf4; color: #166534; border: 1px solid #bbf7d0; }
    .btn-edit:hover { background: #dcfce7; }
    .btn-audit { background: #fdf4ff; color: #7e22ce; border: 1px solid #e9d5ff; }
    .btn-audit:hover { background: #fae8ff; }
    .btn-map { background: var(--e-blue); color: #fff; box-shadow: 0 4px 6px rgba(30,58,138,0.2); }
    .btn-map:hover { background: #1e293b; transform: translateY(-1px); }
    .btn-sm-green { background: #16a34a; color: #fff; padding: 6px 12px; border-radius: 6px; font-size: 12px; font-weight: 800; cursor: pointer; border: none; transition: 0.2s; }
    .btn-sm-green:hover { background: #15803d; }

    .alert { padding: 15px 20px; border-radius: 8px; margin-bottom: 20px; font-weight: 600; display:flex; align-items:center; gap:10px; border-left: 5px solid; }
    .alert-success { background: #dcfce7; color: #166534; border-color: #22c55e; }
    .alert-danger { background: #fee2e2; color: #991b1b; border-color: #ef4444; }

    .grid-container { display: grid; grid-template-columns: 1fr 1fr; gap: 25px; }
    
    .profile-card { background: #fff; border-radius: 12px; border: 1px solid var(--border); box-shadow: 0 4px 15px rgba(0,0,0,0.02); overflow: hidden; margin-bottom:25px; }
    .card-header { padding: 15px 20px; font-size: 14px; font-weight: 800; text-transform: uppercase; color: #fff; display: flex; align-items: center; justify-content: space-between; gap: 10px; }
    .header-clinical { background: #475569; }
    .header-finance { background: #16a34a; }
    .header-matrix { background: #0284c7; }
    
    .card-body { padding: 20px; }
    .data-row { display: flex; justify-content: space-between; align-items: center; padding: 12px 0; border-bottom: 1px dashed var(--border); }
    .data-row:last-child { border-bottom: none; }
    .data-label { color: #64748b; font-size: 13px; font-weight: 700; text-transform: uppercase; }
    .data-value { color: #0f172a; font-size: 15px; font-weight: 800; text-align: right; }
    
    .badge { padding: 4px 8px; border-radius: 6px; font-size: 11px; font-weight: 800; display: inline-flex; align-items: center; gap: 5px; }
    .bg-green { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
    .bg-red { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }
    .bg-blue { background: #dbeafe; color: #1e40af; border: 1px solid #bfdbfe; }
    .bg-gray { background: #f1f5f9; color: #475569; border: 1px solid #cbd5e1; }

    table { width: 100%; border-collapse: collapse; }
    th { background: #f8fafc; color: #475569; padding: 12px; font-size: 12px; text-transform: uppercase; border-bottom: 2px solid var(--border); text-align: left; }
    td { padding: 12px; border-bottom: 1px solid var(--border); font-size: 14px; vertical-align: middle; }

    /* MODAL UI */
    .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(15,23,42,0.6); backdrop-filter: blur(4px); display: none; align-items: center; justify-content: center; z-index: 9999; opacity: 0; transition: 0.2s; }
    .modal-overlay.active { display: flex; opacity: 1; }
    .modal-card { background: #fff; border-radius: 12px; box-shadow: 0 20px 40px rgba(0,0,0,0.2); transform: scale(0.95); transition: 0.2s; overflow: hidden; display:flex; flex-direction:column; max-height:90vh; }
    .modal-card.md { width: 500px; }
    .modal-card.lg { width: 900px; max-width: 95%; }
    .modal-overlay.active .modal-card { transform: scale(1); }
    
    .modal-header { padding: 20px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; background: #f8fafc; }
    .modal-header h2 { margin: 0; color: #0f172a; font-size: 18px; font-weight: 800; }
    .close-modal { background: none; border: none; font-size: 20px; color: #64748b; cursor: pointer; }
    
    .modal-body { padding: 20px; overflow-y:auto; }
    .form-group { margin-bottom: 15px; display: flex; flex-direction: column; gap: 5px; }
    .form-group label { font-size: 12px; font-weight: 700; color: #475569; text-transform: uppercase; }
    .form-control { padding: 10px 12px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 14px; outline: none; }
    .form-control:focus { border-color: var(--e-blue); }
    
    .toggle-switch { display: flex; align-items: center; gap: 8px; cursor: pointer; font-weight: 700; color: #0f172a; font-size: 14px; }
    .toggle-switch input { width: 18px; height: 18px; accent-color: var(--e-blue); cursor: pointer; }

    .modal-footer { padding: 15px 20px; background: #f8fafc; border-top: 1px solid var(--border); display: flex; justify-content: flex-end; gap: 10px; }
</style>
</head>
<body>

<?php include('../../../dripend/statpages/sidebar.php'); ?>

<div class="page-wrapper">

    <div style="margin-bottom:10px;">
        <a href="listMedicine.php" style="color:#64748b; text-decoration:none; font-weight:700; font-size:13px;"><i class="fa-solid fa-arrow-left"></i> Back to Master Formulary</a>
    </div>

    <div class="header-bar">
        <div class="header-info">
            <h2>
                <i class="fa-solid <?= strtolower($medicine['drug_formulation']) == 'injection' ? 'fa-syringe' : 'fa-pills' ?>" style="color:#64748b;"></i> 
                <?= htmlspecialchars($medicine['service_name']) ?>
            </h2>
            <p>System ID: #<?= str_pad($medicine['id'], 5, '0', STR_PAD_LEFT) ?> | Managed by: <?= htmlspecialchars($medicine['department_name']) ?></p>
        </div>
        <div class="primary-actions">
            <a href="updateMedicine.php?id=<?= $medicine['id'] ?>" class="btn btn-edit"><i class="fa-solid fa-pen-to-square"></i> Edit Core Data</a>
            <button onclick="openModal('auditModal')" class="btn btn-audit"><i class="fa-solid fa-clock-rotate-left"></i> Price Audit Ledger</button>
            <button onclick="openModal('mapModal')" class="btn btn-map"><i class="fa-solid fa-shield-plus"></i> Map New Provider</button>
        </div>
    </div>

    <?= $message ?>

    <div class="grid-container">
        <div>
            <div class="profile-card">
                <div class="card-header header-clinical">
                    <span style="display:flex; align-items:center; gap:8px;"><i class="fa-solid fa-microscope"></i> Clinical Data & Formulation</span>
                </div>
                <div class="card-body">
                    <div class="data-row">
                        <div class="data-label">Status</div>
                        <div class="data-value">
                            <?= $medicine['is_active'] ? '<span class="badge bg-green">Active</span>' : '<span class="badge bg-red">Inactive</span>' ?>
                        </div>
                    </div>
                    <div class="data-row">
                        <div class="data-label">Target Group</div>
                        <div class="data-value"><?= htmlspecialchars($medicine['target_age_group']) ?></div>
                    </div>
                    <div class="data-row">
                        <div class="data-label">Physical Form</div>
                        <div class="data-value"><span class="badge bg-gray"><?= htmlspecialchars($medicine['drug_formulation']) ?></span></div>
                    </div>
                    <div class="data-row">
                        <div class="data-label">Strength Value</div>
                        <div class="data-value"><?= htmlspecialchars($medicine['drug_strength']) ?> <?= htmlspecialchars($medicine['strength_unit']) ?></div>
                    </div>
                    <div class="data-row">
                        <div class="data-label">Dispensing Base (Unit)</div>
                        <div class="data-value"><?= htmlspecialchars($medicine['unit_of_pricing']) ?></div>
                    </div>
                </div>
            </div>
            
            <div class="profile-card">
                <div class="card-header header-finance" style="background:#475569;">
                    <span style="display:flex; align-items:center; gap:8px;"><i class="fa-solid fa-file-prescription"></i> NHIS Rules & Coding</span>
                    <?php if(!$medicine['nhis_covered']): ?>
                        <button onclick="openModal('nhisModal')" class="btn-sm-green"><i class="fa-solid fa-plus"></i> Enable NHIS</button>
                    <?php endif; ?>
                </div>
                <div class="card-body">
                    <div class="data-row">
                        <div class="data-label">NHIS Coverage</div>
                        <div class="data-value">
                            <?= $medicine['nhis_covered'] ? '<span class="badge bg-green"><i class="fa-solid fa-check"></i> Covered</span>' : '<span class="badge bg-gray">Not Covered</span>' ?>
                        </div>
                    </div>
                    <?php if($medicine['nhis_covered']): ?>
                    <div class="data-row">
                        <div class="data-label">NHIS Drug Code</div>
                        <div class="data-value"><span class="badge bg-blue" style="font-family:monospace;"><?= htmlspecialchars($medicine['nhis_drug_code'] ?: 'N/A') ?></span></div>
                    </div>
                    <div class="data-row">
                        <div class="data-label">Prescribing Level</div>
                        <div class="data-value"><?= htmlspecialchars($medicine['prescribing_level'] ?: 'Any') ?></div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div>
            <div class="profile-card">
                <div class="card-header header-finance">
                    <span style="display:flex; align-items:center; gap:8px;"><i class="fa-solid fa-wallet"></i> Standard Base Pricing</span>
                </div>
                <div class="card-body">
                    <div class="data-row" style="background:#f0fdf4; padding:15px; border-radius:8px; border:1px solid #bbf7d0;">
                        <div class="data-label" style="color:#166534;">Out-Of-Pocket (Cash)</div>
                        <div class="data-value" style="color:#166534; font-size:20px;">GHS <?= number_format($medicine['cash_price'], 2) ?></div>
                    </div>
                    
                    <?php if($medicine['nhis_covered']): ?>
                    <div class="data-row" style="margin-top:15px;">
                        <div class="data-label">NHIS Billed Tariff</div>
                        <div class="data-value" style="color:#0284c7;">GHS <?= number_format($medicine['tariff_adult'], 2) ?></div>
                    </div>
                    <div class="data-row">
                        <div class="data-label">NHIS Required Co-Pay</div>
                        <div class="data-value">
                            <?php if($medicine['is_copay_required']): ?>
                                <span class="badge bg-red">GHS <?= number_format($medicine['copay_amount'], 2) ?></span>
                            <?php else: ?>
                                <span style="color:#94a3b8;">None</span>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="profile-card">
                <div class="card-header header-matrix">
                    <span style="display:flex; align-items:center; gap:8px;"><i class="fa-solid fa-building-shield"></i> Active Corporate Matrix</span>
                </div>
                <div class="card-body" style="padding:0;">
                    <?php if(empty($mapped_insurances)): ?>
                        <div style="padding:30px; text-align:center; color:#94a3b8; font-weight:600;">
                            <i class="fa-solid fa-link-slash" style="font-size:24px; margin-bottom:10px; display:block;"></i>
                            No private insurance mapped.<br>Click "Map New Provider" above.
                        </div>
                    <?php else: ?>
                        <table>
                            <thead>
                                <tr>
                                    <th style="padding-left:20px;">Provider</th>
                                    <th>Tariff</th>
                                    <th style="padding-right:20px;">Co-Pay</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($mapped_insurances as $mi): ?>
                                <tr>
                                    <td style="font-weight:700; color:#0f172a; padding-left:20px;"><?= htmlspecialchars($mi['insurance_name']) ?></td>
                                    <td style="font-weight:800; color:#0284c7;">GHS <?= number_format($mi['tariff_amount'], 2) ?></td>
                                    <td style="padding-right:20px;">
                                        <?php if($mi['is_copay_required']): ?>
                                            <span class="badge bg-red">GHS <?= number_format($mi['copay_amount'], 2) ?></span>
                                        <?php else: ?>
                                            <span class="badge bg-green"><i class="fa-solid fa-check"></i></span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal-overlay" id="nhisModal">
    <div class="modal-card md">
        <div class="modal-header">
            <h2><i class="fa-solid fa-file-prescription"></i> Enable NHIS Coverage</h2>
            <button class="close-modal" onclick="closeModal('nhisModal')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="">
            <div class="modal-body">
                <input type="hidden" name="action" value="map_nhis">
                
                <div class="alert alert-success" style="padding:10px; font-size:13px; margin-bottom:20px;">
                    <i class="fa-solid fa-info-circle"></i> Fill out the details below to officially add this medicine to your active NHIS Formulary.
                </div>

                <div class="form-group">
                    <label>NHIS Drug Code</label>
                    <input type="text" name="nhis_drug_code" class="form-control" placeholder="e.g. ACETAZTA1">
                </div>
                
                <div class="form-group">
                    <label>Prescribing Level</label>
                    <select name="prescribing_level" class="form-control">
                        <option value="">-- Select Level --</option>
                        <?php foreach($prescribe_levels as $l): ?>
                            <option value="<?= htmlspecialchars($l['level_code']) ?>"><?= htmlspecialchars($l['level_code']) ?> - <?= htmlspecialchars($l['description']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label style="color:#16a34a;">Universal NHIS Tariff (GHS)</label>
                    <input type="number" name="drug_tariff" class="form-control" step="0.01" style="border-color:#16a34a;" required>
                </div>

                <div style="background:#fef3c7; padding:15px; border-radius:8px; border:1px solid #fde68a; margin-top:15px;">
                    <label class="toggle-switch" style="color:#b45309; margin-bottom:10px;">
                        <input type="checkbox" name="is_nhis_copay_required" id="nhis_copay_req" onchange="toggleNhisCopay()">
                        Requires Patient Co-Pay
                    </label>
                    <div class="form-group" style="margin:0;">
                        <input type="number" name="nhis_copay_amount" id="nhis_copay_amt" class="form-control" step="0.01" placeholder="Amount Patient Pays (GHS)" disabled>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn" style="background:#e2e8f0; color:#475569;" onclick="closeModal('nhisModal')">Cancel</button>
                <button type="submit" class="btn btn-map" style="background:#16a34a;"><i class="fa-solid fa-save"></i> Save NHIS Mapping</button>
            </div>
        </form>
    </div>
</div>

<div class="modal-overlay" id="mapModal">
    <div class="modal-card md">
        <div class="modal-header">
            <h2><i class="fa-solid fa-shield-plus"></i> Map Corporate Provider</h2>
            <button class="close-modal" onclick="closeModal('mapModal')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="">
            <div class="modal-body">
                <input type="hidden" name="action" value="map_insurance">
                
                <?php if(empty($unmapped_insurances)): ?>
                    <div class="alert alert-success">
                        <i class="fa-solid fa-check-circle"></i> This medicine is already mapped to all active corporate providers!
                    </div>
                <?php else: ?>
                    <div class="form-group">
                        <label>Select Unmapped Provider</label>
                        <select name="insurance_type_id" class="form-control" required>
                            <option value="">-- Select Provider --</option>
                            <?php foreach($unmapped_insurances as $ui): ?>
                                <option value="<?= $ui['id'] ?>"><?= htmlspecialchars($ui['insurance_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Agreed Tariff per Unit (GHS)</label>
                        <input type="number" name="tariff_amount" class="form-control" step="0.01" style="border-color:#0284c7;" required>
                    </div>
                    <div style="background:#fef3c7; padding:15px; border-radius:8px; border:1px solid #fde68a; margin-top:15px;">
                        <label class="toggle-switch" style="color:#b45309; margin-bottom:10px;">
                            <input type="checkbox" name="is_copay_required" id="map_copay_req" onchange="toggleMapCopay()">
                            Requires Patient Co-Pay
                        </label>
                        <div class="form-group" style="margin:0;">
                            <input type="number" name="copay_amount" id="map_copay_amt" class="form-control" step="0.01" placeholder="Amount Patient Pays (GHS)" disabled>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn" style="background:#e2e8f0; color:#475569;" onclick="closeModal('mapModal')">Cancel</button>
                <?php if(!empty($unmapped_insurances)): ?>
                    <button type="submit" class="btn btn-map"><i class="fa-solid fa-save"></i> Map Provider</button>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>

<div class="modal-overlay" id="auditModal">
    <div class="modal-card lg">
        <div class="modal-header">
            <h2><i class="fa-solid fa-clock-rotate-left"></i> Historical Price Audit Ledger</h2>
            <button class="close-modal" onclick="closeModal('auditModal')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <div class="modal-body" style="padding:0;">
            <?php if(empty($price_history)): ?>
                <div style="padding:30px; text-align:center; color:#94a3b8; font-weight:600;">
                    <i class="fa-solid fa-folder-open" style="font-size:24px; margin-bottom:10px; display:block;"></i>
                    No price changes have been tracked for this medicine yet.
                </div>
            <?php else: ?>
                <table>
                    <thead>
                        <tr>
                            <th style="padding-left:20px;">Created On</th>
                            <th>Effective Date</th>
                            <th>Cash Change</th>
                            <th>NHIS Change</th>
                            <th style="padding-right:20px; text-align:right;">Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($price_history as $ph): ?>
                        <tr style="<?= $ph['status'] == 'Pending' ? 'background:#fffbeb;' : '' ?>">
                            <td style="padding-left:20px; font-size:12px; color:#64748b; font-weight:600;">
                                <?= date('d M Y, H:i', strtotime($ph['created_at'])) ?>
                            </td>
                            <td style="font-weight:800; color:#0f172a;">
                                <?= date('d M Y', strtotime($ph['effective_date'])) ?>
                            </td>
                            <td>
                                <span style="text-decoration:line-through; color:#94a3b8; font-size:12px;"><?= $ph['old_cash_price'] ?></span> 
                                <i class="fa-solid fa-arrow-right" style="font-size:10px; color:#cbd5e1; margin:0 5px;"></i> 
                                <span style="font-weight:700; color:#16a34a;"><?= $ph['new_cash_price'] ?></span>
                            </td>
                            <td>
                                <span style="text-decoration:line-through; color:#94a3b8; font-size:12px;"><?= $ph['old_nhis_tariff'] ?></span> 
                                <i class="fa-solid fa-arrow-right" style="font-size:10px; color:#cbd5e1; margin:0 5px;"></i> 
                                <span style="font-weight:700; color:#0284c7;"><?= $ph['new_nhis_tariff'] ?></span>
                            </td>
                            <td style="padding-right:20px; text-align:right;">
                                <?php 
                                    if($ph['status'] == 'Applied') echo '<span class="badge bg-green">Applied</span>';
                                    else if($ph['status'] == 'Pending') echo '<span class="badge bg-red" style="background:#fef3c7; color:#b45309; border-color:#fde68a;">Pending</span>';
                                    else echo '<span class="badge bg-gray">Cancelled</span>';
                                ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        <div class="modal-footer">
            <button class="btn" style="background:#e2e8f0; color:#475569;" onclick="closeModal('auditModal')">Close Ledger</button>
        </div>
    </div>
</div>

<script>
function openModal(id) {
    document.getElementById(id).classList.add('active');
}
function closeModal(id) {
    document.getElementById(id).classList.remove('active');
}
function toggleMapCopay() {
    const chk = document.getElementById('map_copay_req').checked;
    const amt = document.getElementById('map_copay_amt');
    amt.disabled = !chk;
    if(!chk) amt.value = '';
}
function toggleNhisCopay() {
    const chk = document.getElementById('nhis_copay_req').checked;
    const amt = document.getElementById('nhis_copay_amt');
    amt.disabled = !chk;
    if(!chk) amt.value = '';
}
</script>

</body>
</html>