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

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

$message = '';

// ==============================================================================
// 1. THE AUTO-APPLIER ENGINE (RUNS SILENTLY ON LOAD)
// ==============================================================================
$apply_stmt = $conn->prepare("SELECT * FROM medicine_price_history WHERE status = 'Pending' AND effective_date <= CURRENT_DATE");
$apply_stmt->execute();
$pending_updates = $apply_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$apply_stmt->close();

if (!empty($pending_updates)) {
    $conn->begin_transaction();
    try {
        $update_catalog = $conn->prepare("UPDATE service_catalog SET cash_price = ?, tariff_adult = ?, tariff_child = ?, is_copay_required = ?, copay_amount = ? WHERE id = ?");
        $mark_applied = $conn->prepare("UPDATE medicine_price_history SET status = 'Applied' WHERE id = ?");
        $update_corp = $conn->prepare("INSERT INTO service_corporate_tariffs (service_id, insurance_type_id, tariff_amount, is_copay_required, copay_amount) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE tariff_amount = VALUES(tariff_amount), is_copay_required = VALUES(is_copay_required), copay_amount = VALUES(copay_amount)");

        foreach ($pending_updates as $pu) {
            $h_id = $pu['id'];
            $s_id = $pu['service_id'];

            // 1. Update Master Catalog (Cash + NHIS + NHIS Copay)
            $update_catalog->bind_param("dddddi", $pu['new_cash_price'], $pu['new_nhis_tariff'], $pu['new_nhis_tariff'], $pu['new_nhis_copay_req'], $pu['new_nhis_copay_amt'], $s_id);
            $update_catalog->execute();
            
            // 2. Fetch and Update Corporate Matrices associated with this history event
            $corp_res = $conn->query("SELECT * FROM medicine_price_history_corp WHERE history_id = $h_id");
            while ($corp = $corp_res->fetch_assoc()) {
                $update_corp->bind_param("iidid", $s_id, $corp['insurance_type_id'], $corp['new_tariff'], $corp['new_copay_req'], $corp['new_copay_amt']);
                $update_corp->execute();
            }

            // 3. Mark as Applied
            $mark_applied->bind_param("i", $h_id);
            $mark_applied->execute();
        }
        $conn->commit();
        $message = "<div class='alert alert-success'><i class='fa-solid fa-clock'></i> <strong>Automated System:</strong> Successfully applied " . count($pending_updates) . " scheduled multi-matrix price updates that reached their effective date today.</div>";
    } catch (Exception $e) {
        $conn->rollback();
        $message = "<div class='alert alert-danger'>Auto-Apply Error: " . $e->getMessage() . "</div>";
    }
}

// ==============================================================================
// 2. PROCESS NEW PRICE SCHEDULE SUBMISSIONS
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['schedule_price'])) {
    $conn->begin_transaction();
    try {
        $service_id = (int)$_POST['service_id'];
        $effective_date = $_POST['effective_date'];

        // Base & NHIS
        $old_cash = (float)$_POST['old_cash'];
        $new_cash = (float)$_POST['new_cash'];
        $old_nhis = (float)$_POST['old_nhis'];
        $new_nhis = (float)$_POST['new_nhis'];
        $old_nhis_req = (int)$_POST['old_nhis_req'];
        $new_nhis_req = isset($_POST['new_nhis_req']) ? 1 : 0;
        $old_nhis_amt = (float)$_POST['old_nhis_amt'];
        $new_nhis_amt = $new_nhis_req ? (float)$_POST['new_nhis_amt'] : 0.00;

        $stmt = $conn->prepare("INSERT INTO medicine_price_history (service_id, old_cash_price, new_cash_price, old_nhis_tariff, new_nhis_tariff, old_nhis_copay_req, new_nhis_copay_req, old_nhis_copay_amt, new_nhis_copay_amt, effective_date, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'Pending')");
        $stmt->bind_param("iddddiidds", $service_id, $old_cash, $new_cash, $old_nhis, $new_nhis, $old_nhis_req, $new_nhis_req, $old_nhis_amt, $new_nhis_amt, $effective_date);
        $stmt->execute();
        $history_id = $conn->insert_id;
        $stmt->close();

        // Corporate Sub-Matrices
        $corp_ins_ids = $_POST['corp_ins_id'] ?? [];
        $old_corp_tariffs = $_POST['old_corp_tariff'] ?? [];
        $new_corp_tariffs = $_POST['new_corp_tariff'] ?? [];
        $old_corp_reqs = $_POST['old_corp_req'] ?? [];
        $new_corp_reqs = $_POST['new_corp_req'] ?? []; // Checkbox array
        $old_corp_amts = $_POST['old_corp_amt'] ?? [];
        $new_corp_amts = $_POST['new_corp_amt'] ?? [];

        if (!empty($corp_ins_ids)) {
            $stmtCorp = $conn->prepare("INSERT INTO medicine_price_history_corp (history_id, insurance_type_id, old_tariff, new_tariff, old_copay_req, new_copay_req, old_copay_amt, new_copay_amt) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            foreach ($corp_ins_ids as $idx => $ins_id) {
                $o_tar = (float)$old_corp_tariffs[$idx];
                $n_tar = (float)$new_corp_tariffs[$idx];
                $o_req = (int)$old_corp_reqs[$idx];
                $n_req = isset($new_corp_reqs[$ins_id]) ? 1 : 0; // Checkbox check by ID
                $o_amt = (float)$old_corp_amts[$idx];
                $n_amt = $n_req ? (float)$new_corp_amts[$idx] : 0.00;

                $stmtCorp->bind_param("iidididd", $history_id, $ins_id, $o_tar, $n_tar, $o_req, $n_req, $o_amt, $n_amt);
                $stmtCorp->execute();
            }
            $stmtCorp->close();
        }

        $conn->commit();
        $message = "<div class='alert alert-success'><i class='fa-solid fa-calendar-check'></i> Universal Price Update (Cash, NHIS, and Corporate) scheduled successfully for " . date('d M Y', strtotime($effective_date)) . ".</div>";
    } catch (Exception $e) {
        $conn->rollback();
        $message = "<div class='alert alert-danger'>Error scheduling price update: " . $e->getMessage() . "</div>";
    }
}

// ==============================================================================
// 3. FETCH GLOBAL DATA FOR JS
// ==============================================================================
// 1. Fetch all active corporate insurances
$insurances = $conn->query("SELECT id, insurance_name FROM insurance_type WHERE LOWER(insurance_name) NOT IN ('nhis', 'cash') AND is_active = 1 ORDER BY insurance_name ASC")->fetch_all(MYSQLI_ASSOC);
$ins_json = json_encode($insurances);

// 2. Fetch all current mapped corporate tariffs globally to assemble in PHP
$all_corp_tariffs = $conn->query("SELECT service_id, insurance_type_id, tariff_amount, is_copay_required, copay_amount FROM service_corporate_tariffs")->fetch_all(MYSQLI_ASSOC);
$matrix_map = [];
foreach ($all_corp_tariffs as $t) {
    $matrix_map[$t['service_id']][$t['insurance_type_id']] = $t;
}

// 3. Fetch Master Medicines
$medicines = $conn->query("
    SELECT sc.id, sc.service_name, sc.cash_price, sc.tariff_adult AS nhis_tariff, sc.is_copay_required AS nhis_copay_req, sc.copay_amount AS nhis_copay_amt, 
    (SELECT effective_date FROM medicine_price_history mph WHERE mph.service_id = sc.id AND mph.status = 'Pending' ORDER BY mph.effective_date ASC LIMIT 1) as pending_date
    FROM service_catalog sc 
    WHERE sc.service_type = 'Drug' AND sc.is_active = 1 
    ORDER BY sc.service_name ASC
")->fetch_all(MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Medicine Price Update</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: center; margin-bottom: 20px; }
    .header-bar h2 { color: #0f172a; margin: 0; font-size: 24px; font-weight: 800; text-transform: uppercase; display:flex; align-items:center; gap:10px; }
    
    .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; }

    /* DATA TABLE */
    .table-card { background: #fff; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); overflow: hidden; border: 1px solid var(--border); }
    table { width: 100%; border-collapse: collapse; }
    th { background: #f8fafc; color: #475569; padding: 15px; font-size: 12px; text-transform: uppercase; border-bottom: 2px solid var(--border); text-align: left; }
    td { padding: 15px; border-bottom: 1px solid var(--border); font-size: 14px; vertical-align: middle; }
    tr:hover { background: #f0fdf4; }
    
    .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-orange { background: #fef3c7; color: #b45309; border: 1px solid #fde68a; }

    .btn-action { background: #0f172a; color: #fff; border: none; padding: 8px 15px; border-radius: 6px; font-weight: bold; cursor: pointer; transition: 0.2s; font-size: 12px; }
    .btn-action:hover { background: #1e293b; }

    /* 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 { width: 800px; max-width:95%; max-height:90vh; display:flex; flex-direction:column; 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; }
    .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; background:#f1f5f9; }
    
    .pricing-box { background:#fff; border-radius:10px; border:1px solid var(--border); margin-bottom:20px; overflow:hidden; }
    .box-header { padding:12px 15px; font-weight:800; font-size:13px; text-transform:uppercase; color:#fff; display:flex; align-items:center; gap:8px; }
    .box-body { padding:15px; }

    .matrix-table { width:100%; border-collapse:collapse; }
    .matrix-table th { background:#f8fafc; padding:10px; font-size:11px; border-bottom:1px solid #cbd5e1; }
    .matrix-table td { padding:10px; border-bottom:1px solid #e2e8f0; }

    .form-control { padding: 8px 10px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 13px; outline: none; width:100%; box-sizing:border-box; }
    .form-control[readonly] { background: #f1f5f9; color: #64748b; border-style: dashed; }
    .toggle-switch input { width:16px; height:16px; cursor:pointer; }

    .modal-footer { padding: 15px 20px; background: #fff; border-top: 1px solid var(--border); display: flex; justify-content: flex-end; gap: 10px; }
    .btn-save { background: #0f172a; color: #fff; padding: 10px 20px; border: none; border-radius: 6px; font-weight: bold; cursor: pointer; transition: 0.2s; }
    .btn-save:hover { background: #1e293b; }
    .btn-cancel { background: #e2e8f0; color: #475569; padding: 10px 20px; border: none; border-radius: 6px; font-weight: bold; cursor: pointer; }
</style>
</head>
<body>

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

<div class="page-wrapper">

    <div style="margin-bottom:15px;">
        <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 Medicine List</a>
    </div>

    <div class="header-bar">
        <h2><i class="fa-solid fa-tags"></i> Medicine Price Update</h2>
    </div>

    <?= $message ?>

    <div class="table-card">
        <table>
            <thead>
                <tr>
                    <th>Medicine </th>
                    <th>Current Cash Price</th>
                    <th>Current NHIS Tariff</th>
                    <th>Update Status</th>
                    <th style="text-align:right;">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($medicines as $m): 
                    // Safely extract this drug's corporate matrix array for JS injection
                    $my_matrix = isset($matrix_map[$m['id']]) ? $matrix_map[$m['id']] : [];
                ?>
                <tr>
                    <td style="font-weight:700; color:#0f172a; font-size:15px;">
                        <?= htmlspecialchars($m['service_name']) ?>
                    </td>
                    <td style="font-weight:800; color:#16a34a;">GHS <?= number_format($m['cash_price'], 2) ?></td>
                    <td style="font-weight:800; color:#0284c7;">GHS <?= number_format($m['nhis_tariff'], 2) ?></td>
                    <td>
                        <?php if($m['pending_date']): ?>
                            <span class="badge bg-orange"><i class="fa-regular fa-clock"></i> Scheduled for <?= date('d M Y', strtotime($m['pending_date'])) ?></span>
                        <?php else: ?>
                            <span class="badge bg-green"><i class="fa-solid fa-check"></i> Active & Current</span>
                        <?php endif; ?>
                    </td>
                    <td style="text-align:right;">
                        <button class="btn-action" onclick='openModal(
                            <?= $m['id'] ?>, 
                            "<?= htmlspecialchars(addslashes($m['service_name'])) ?>", 
                            <?= $m['cash_price'] ?>, 
                            <?= $m['nhis_tariff'] ?>, 
                            <?= $m['nhis_copay_req'] ?>, 
                            <?= $m['nhis_copay_amt'] ?>, 
                            <?= json_encode($my_matrix) ?>
                        )'>
                            <i class="fa-solid fa-sliders"></i> Update Price
                        </button>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

</div>

<div class="modal-overlay" id="priceModal">
    <div class="modal-card">
        <div class="modal-header">
            <h2><i class="fa-solid fa-tags"></i> Schedule Price Update Matrix</h2>
            <button class="close-modal" onclick="closeModal()"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="">
            <div class="modal-body">
                <input type="hidden" name="schedule_price" value="1">
                <input type="hidden" name="service_id" id="mod_id" value="">
                
                <div style="margin-bottom:15px; font-weight:800; color:#1e3a8a; font-size:18px;" id="mod_name"></div>

                <div class="pricing-box">
                    <div class="box-header" style="background:#475569;"><i class="fa-solid fa-money-bill"></i> Base Cash & NHIS Rules</div>
                    <div class="box-body">
                        <table class="matrix-table">
                            <thead>
                                <tr>
                                    <th>Policy</th>
                                    <th>Current Tariff</th>
                                    <th>New Tariff (GHS)</th>
                                    <th style="text-align:center;">Req Co-Pay</th>
                                    <th>Current Co-Pay</th>
                                    <th>New Co-Pay (GHS)</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td style="font-weight:700; color:#16a34a;">Out-of-Pocket (Cash)</td>
                                    <td><input type="number" name="old_cash" id="mod_old_cash" class="form-control" readonly></td>
                                    <td><input type="number" name="new_cash" id="mod_new_cash" class="form-control" step="0.01" style="border-color:#16a34a;" required></td>
                                    <td colspan="3" style="text-align:center; color:#94a3b8; font-size:11px;">N/A for Cash</td>
                                </tr>
                                <tr>
                                    <td style="font-weight:700; color:#0284c7;">NHIS </td>
                                    <td><input type="number" name="old_nhis" id="mod_old_nhis" class="form-control" readonly></td>
                                    <td><input type="number" name="new_nhis" id="mod_new_nhis" class="form-control" step="0.01" style="border-color:#0284c7;" required></td>
                                    <td style="text-align:center;">
                                        <input type="hidden" name="old_nhis_req" id="mod_old_nhis_req">
                                        <label class="toggle-switch"><input type="checkbox" name="new_nhis_req" id="mod_new_nhis_req" onchange="toggleCopay('mod_new_nhis_req', 'mod_new_nhis_amt')"></label>
                                    </td>
                                    <td><input type="number" name="old_nhis_amt" id="mod_old_nhis_amt" class="form-control" readonly></td>
                                    <td><input type="number" name="new_nhis_amt" id="mod_new_nhis_amt" class="form-control" step="0.01"></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="pricing-box">
                    <div class="box-header" style="background:#0284c7;"><i class="fa-solid fa-building-shield"></i> Mapped Corporate Providers</div>
                    <div class="box-body" style="padding:0;">
                        <table class="matrix-table" id="corp_table">
                            <thead>
                                <tr>
                                    <th>Provider</th>
                                    <th>Current Tariff</th>
                                    <th>New Tariff (GHS)</th>
                                    <th style="text-align:center;">Req Co-Pay</th>
                                    <th>Current Co-Pay</th>
                                    <th>New Co-Pay (GHS)</th>
                                </tr>
                            </thead>
                            <tbody id="corp_tbody">
                                </tbody>
                        </table>
                    </div>
                </div>

                <div style="background:#fffbeb; padding:15px; border-radius:8px; border:1px solid #fde68a;">
                    <label style="color:#b45309; font-weight:800; display:block; margin-bottom:8px;"><i class="fa-regular fa-calendar"></i> Universal Effective Date (When do these new prices launch?)</label>
                    <input type="date" name="effective_date" class="form-control" min="<?= date('Y-m-d') ?>" style="max-width:250px; font-weight:bold;" required>
                </div>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn-cancel" onclick="closeModal()">Cancel</button>
                <button type="submit" class="btn-save"><i class="fa-solid fa-clock"></i> Schedule Universal Matrix Update</button>
            </div>
        </form>
    </div>
</div>

<script>
// Load global insurances from PHP
const globalInsurances = <?= $ins_json ?>;

function openModal(id, name, cash, nhisTariff, nhisReq, nhisAmt, corpMatrix) {
    document.getElementById('mod_id').value = id;
    document.getElementById('mod_name').innerHTML = name;
    
    // Fill Base Fields
    document.getElementById('mod_old_cash').value = cash;
    document.getElementById('mod_new_cash').value = cash; // Pre-fill with current for easy edit
    
    document.getElementById('mod_old_nhis').value = nhisTariff;
    document.getElementById('mod_new_nhis').value = nhisTariff;
    
    document.getElementById('mod_old_nhis_req').value = nhisReq;
    document.getElementById('mod_new_nhis_req').checked = (nhisReq == 1);
    
    document.getElementById('mod_old_nhis_amt').value = nhisAmt;
    const newNhisAmt = document.getElementById('mod_new_nhis_amt');
    newNhisAmt.value = nhisAmt;
    newNhisAmt.disabled = (nhisReq != 1);

    // Build Corporate Matrix Dynamically
    const tbody = document.getElementById('corp_tbody');
    tbody.innerHTML = ''; // Clear old rows
    
    let mappedCount = 0;

    globalInsurances.forEach(ins => {
        // Only show providers that this specific drug is ACTUALLY mapped to
        if(corpMatrix[ins.id]) {
            mappedCount++;
            const mData = corpMatrix[ins.id];
            
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td style="font-weight:700; font-size:12px; color:#475569;">
                    <input type="hidden" name="corp_ins_id[]" value="${ins.id}">
                    ${ins.insurance_name}
                </td>
                <td><input type="number" name="old_corp_tariff[]" class="form-control" value="${mData.tariff_amount}" readonly></td>
                <td><input type="number" name="new_corp_tariff[]" class="form-control" value="${mData.tariff_amount}" step="0.01" style="border-color:#0284c7;" required></td>
                
                <td style="text-align:center;">
                    <input type="hidden" name="old_corp_req[]" value="${mData.is_copay_required}">
                    <label class="toggle-switch">
                        <input type="checkbox" name="new_corp_req[${ins.id}]" id="req_corp_${ins.id}" value="1" ${mData.is_copay_required == 1 ? 'checked' : ''} onchange="toggleCopay('req_corp_${ins.id}', 'amt_corp_${ins.id}')">
                    </label>
                </td>
                
                <td><input type="number" name="old_corp_amt[]" class="form-control" value="${mData.copay_amount}" readonly></td>
                <td><input type="number" name="new_corp_amt[]" id="amt_corp_${ins.id}" class="form-control" value="${mData.copay_amount}" step="0.01" ${mData.is_copay_required != 1 ? 'disabled' : ''}></td>
            `;
            tbody.appendChild(tr);
        }
    });

    if(mappedCount === 0) {
        tbody.innerHTML = `<tr><td colspan="6" style="text-align:center; padding:20px; color:#94a3b8;"><i class="fa-solid fa-link-slash"></i> This medicine is currently not mapped to any private/corporate providers.</td></tr>`;
    }

    document.getElementById('priceModal').classList.add('active');
}

function toggleCopay(chkId, amtId) {
    const chk = document.getElementById(chkId).checked;
    const amt = document.getElementById(amtId);
    amt.disabled = !chk;
    if(!chk) amt.value = '0.00';
}

function closeModal() {
    document.getElementById('priceModal').classList.remove('active');
}
</script>

</body>
</html>