<?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. FETCH SYSTEM DICTIONARIES
// ==============================================================================
$departments = $conn->query("SELECT id, department_name FROM departments ORDER BY department_name ASC")->fetch_all(MYSQLI_ASSOC);
$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);
$formulations = $conn->query("SELECT formulation_name, formulation_symbol FROM drug_formulations WHERE is_active = 1 ORDER BY formulation_name ASC")->fetch_all(MYSQLI_ASSOC);
$units = $conn->query("SELECT unit_name, unit_symbol FROM units_of_measure WHERE is_active = 1 ORDER BY unit_name ASC")->fetch_all(MYSQLI_ASSOC);
$prescribe_levels = $conn->query("SELECT level_code, description FROM prescribing_levels WHERE is_active = 1 ORDER BY level_code ASC")->fetch_all(MYSQLI_ASSOC);

// ==============================================================================
// 2. FORM PROCESSING (UPDATE)
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $conn->begin_transaction();
    try {
        $department_id = (int)$_POST['department_id'];
        $generic_name = trim($_POST['generic_name']);
        $drug_formulation = trim($_POST['drug_formulation']);
        $drug_strength = trim($_POST['drug_strength']);
        $strength_unit = trim($_POST['strength_unit']);
        $unit_of_pricing = trim($_POST['unit_of_pricing']);
        $cash_price = (float)$_POST['cash_price'];

        // Re-Fetch Symbols to build the updated Service Name
        $stmtF = $conn->prepare("SELECT formulation_symbol FROM drug_formulations WHERE formulation_name = ? LIMIT 1");
        $stmtF->bind_param("s", $drug_formulation);
        $stmtF->execute();
        $resF = $stmtF->get_result()->fetch_assoc();
        $f_symbol = $resF ? $resF['formulation_symbol'] : $drug_formulation;
        $stmtF->close();

        $stmtU = $conn->prepare("SELECT unit_symbol FROM units_of_measure WHERE unit_name = ? LIMIT 1");
        $stmtU->bind_param("s", $strength_unit);
        $stmtU->execute();
        $resU = $stmtU->get_result()->fetch_assoc();
        $u_symbol = $resU ? $resU['unit_symbol'] : $strength_unit;
        $stmtU->close();

        $service_name = "{$generic_name} {$f_symbol}, {$drug_strength} {$u_symbol}";

        // NHIS Data Handling
        $nhis_covered = isset($_POST['nhis_covered']) ? 1 : 0;
        $corp_covered = isset($_POST['corp_covered']) ? 1 : 0;
        
        if ($nhis_covered === 1) {
            $nhis_drug_code = !empty($_POST['nhis_drug_code']) ? trim($_POST['nhis_drug_code']) : null;
            $prescribing_level = !empty($_POST['prescribing_level']) ? trim($_POST['prescribing_level']) : null;
            $drug_tariff = (float)($_POST['drug_tariff'] ?? 0);
            $is_nhis_copay_required = isset($_POST['is_nhis_copay_required']) ? 1 : 0;
            $nhis_copay_amount = $is_nhis_copay_required ? (float)$_POST['nhis_copay_amount'] : 0.00;
        } else {
            $nhis_drug_code = null;
            $prescribing_level = null;
            $drug_tariff = 0.00;
            $is_nhis_copay_required = 0;
            $nhis_copay_amount = 0.00;
        }
        $tariff_adult = $tariff_child = $drug_tariff;

        // 1. UPDATE Master Catalog
        $stmtMaster = $conn->prepare("
            UPDATE service_catalog SET 
                department_id=?, service_name=?, nhis_covered=?, corp_covered=?,
                nhis_drug_code=?, unit_of_pricing=?, prescribing_level=?,
                drug_formulation=?, drug_strength=?, strength_unit=?,
                cash_price=?, tariff_adult=?, tariff_child=?,
                is_copay_required=?, copay_amount=? 
            WHERE id=?
        ");
        $stmtMaster->bind_param("isiissssssdddidi", 
            $department_id, $service_name, $nhis_covered, $corp_covered,
            $nhis_drug_code, $unit_of_pricing, $prescribing_level,
            $drug_formulation, $drug_strength, $strength_unit,
            $cash_price, $tariff_adult, $tariff_child,
            $is_nhis_copay_required, $nhis_copay_amount, $service_id
        );
        $stmtMaster->execute();
        $stmtMaster->close();

        // 2. REBUILD Corporate Matrix
        $conn->query("DELETE FROM service_corporate_tariffs WHERE service_id = $service_id");

        if ($corp_covered === 1 && !empty($_POST['corp_mapped'])) {
            $corp_mapped = $_POST['corp_mapped'];
            $corp_tariffs = $_POST['corp_tariff'] ?? [];
            $corp_copay_req = $_POST['corp_copay_req'] ?? [];
            $corp_copay_amts = $_POST['corp_copay_amt'] ?? [];

            $stmtCorp = $conn->prepare("INSERT INTO service_corporate_tariffs (service_id, insurance_type_id, tariff_amount, is_copay_required, copay_amount) VALUES (?, ?, ?, ?, ?)");
            foreach ($corp_mapped as $ins_id => $is_mapped) {
                if ($is_mapped == '1') {
                    $t_amt = (float)($corp_tariffs[$ins_id] ?? 0);
                    $c_req = isset($corp_copay_req[$ins_id]) ? 1 : 0;
                    $c_amt = $c_req ? (float)($corp_copay_amts[$ins_id] ?? 0) : 0.00;
                    $stmtCorp->bind_param("iidid", $service_id, $ins_id, $t_amt, $c_req, $c_amt);
                    $stmtCorp->execute();
                }
            }
            $stmtCorp->close();
        }

        $conn->commit();
        $message = "<div class='alert alert-success'><i class='fa-solid fa-check-circle'></i> <strong>Update Successful:</strong> {$service_name} has been updated.</div>";

    } catch (Exception $e) {
        $conn->rollback();
        $message = "<div class='alert alert-danger'><i class='fa-solid fa-triangle-exclamation'></i> <strong>Update Failed:</strong> " . $e->getMessage() . "</div>";
    }
}

// ==============================================================================
// 3. FETCH CURRENT DATA TO PRE-FILL FORM
// ==============================================================================
$stmt = $conn->prepare("SELECT * FROM service_catalog WHERE id = ?");
$stmt->bind_param("i", $service_id);
$stmt->execute();
$med = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$med) die("Medicine not found.");

// Fetch the symbols used to reverse-engineer the Generic Name
$stmtF = $conn->prepare("SELECT formulation_symbol FROM drug_formulations WHERE formulation_name = ?");
$stmtF->bind_param("s", $med['drug_formulation']);
$stmtF->execute();
$resF = $stmtF->get_result()->fetch_assoc();
$f_sym = $resF ? $resF['formulation_symbol'] : $med['drug_formulation'];

$stmtU = $conn->prepare("SELECT unit_symbol FROM units_of_measure WHERE unit_name = ?");
$stmtU->bind_param("s", $med['strength_unit']);
$stmtU->execute();
$resU = $stmtU->get_result()->fetch_assoc();
$u_sym = $resU ? $resU['unit_symbol'] : $med['strength_unit'];

// Extract exact generic name by stripping the suffix
$suffix = " {$f_sym}, {$med['drug_strength']} {$u_sym}";
$derived_generic_name = trim(str_replace($suffix, "", $med['service_name']));

// Fetch Existing Corporate Mappings into an easy key-value array
$existing_corp = [];
$c_res = $conn->query("SELECT * FROM service_corporate_tariffs WHERE service_id = $service_id");
while ($row = $c_res->fetch_assoc()) {
    $existing_corp[$row['insurance_type_id']] = $row;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Update Medicine | 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-bar h2 { color: #0f172a; margin: 0; font-size: 24px; font-weight: 800; 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; }

    .section-box { background: #fff; border: 1px solid var(--border); border-radius: 12px; margin-bottom: 25px; box-shadow: 0 4px 10px rgba(0,0,0,0.02); overflow: hidden; }
    .section-header { padding: 15px 20px; font-size: 14px; font-weight: 800; text-transform: uppercase; color: #fff; display: flex; align-items: center; gap: 10px; }
    .section-body { padding: 25px; }
    
    .theme-core .section-header { background: #475569; }
    .theme-nhis .section-header { background: #16a34a; }
    .theme-corp .section-header { background: #0284c7; }

    .form-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; }
    
    .form-group { display: flex; flex-direction: column; gap: 6px; position: relative; }
    .form-group label { font-size: 12px; font-weight: 700; color: #64748b; text-transform: uppercase; }
    .form-control { padding: 12px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 14px; outline: none; transition:0.2s; }
    .form-control:focus { border-color: var(--e-blue); box-shadow: 0 0 0 3px #eff6ff; }
    .form-control:disabled { background: #f1f5f9; color: #94a3b8; cursor: not-allowed; border-style: dashed; }

    .symbol-badge { position: absolute; right: 10px; top: 35px; background: #dbeafe; color: #1e40af; padding: 4px 8px; border-radius: 4px; font-size: 11px; font-weight: 800; font-family: monospace; border: 1px solid #bfdbfe; pointer-events: none; }

    .matrix-table { width: 100%; border-collapse: collapse; margin-top: 10px; }
    .matrix-table th { background: #f8fafc; padding: 12px 15px; font-size: 12px; color: #475569; text-transform: uppercase; text-align: left; border-bottom: 2px solid var(--border); }
    .matrix-table td { padding: 15px; border-bottom: 1px solid var(--border); vertical-align: middle; }
    .matrix-table tr:hover { background: #f0f9ff; }
    
    .toggle-switch { display: flex; align-items: center; gap: 8px; cursor: pointer; font-weight: 700; color: #0f172a; font-size: 14px; }
    .toggle-switch input[type="checkbox"] { width: 18px; height: 18px; cursor: pointer; accent-color: var(--e-green); }
    .toggle-switch.blue-accent input[type="checkbox"] { accent-color: var(--e-blue); }

    .btn { padding: 12px 25px; border-radius: 8px; font-weight: 800; cursor: pointer; font-size: 14px; transition: 0.2s; border: none; text-decoration:none; display:inline-flex; align-items:center; gap:8px; }
    .btn-secondary { background: #e2e8f0; color: #475569; }
    .btn-secondary:hover { background: #cbd5e1; }
    .btn-primary { background: var(--e-blue); color: #fff; box-shadow: 0 4px 6px rgba(30, 58, 138, 0.2); }
    .btn-primary:hover { background: #1e293b; transform: translateY(-1px); }

    .opacity-50 { opacity: 0.5; pointer-events: none; }
    .transition-block { transition: opacity 0.3s ease; }
</style>
</head>
<body>

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

<div class="page-wrapper">

    <div style="margin-bottom:15px;">
        <a href="viewMedicine.php?id=<?= $service_id ?>" style="color:#64748b; text-decoration:none; font-weight:700; font-size:13px;"><i class="fa-solid fa-arrow-left"></i> Back to Medicine Profile</a>
    </div>

    <div class="header-bar">
        <h2><i class="fa-solid fa-pen-to-square" style="color:var(--e-blue);"></i> Update Medicine Core Data</h2>
    </div>

    <?= $message ?>

    <form method="post" id="medicineForm">
        
        <div class="section-box theme-core">
            <div class="section-header"><i class="fa-solid fa-flask"></i> 1. Medicine Formulation & Base Price</div>
            <div class="section-body">
                <div class="form-grid" style="margin-bottom:20px;">
                    <div class="form-group" style="grid-column: span 2;">
                        <label>Drug Generic Name</label>
                        <input class="form-control" name="generic_name" type="text" value="<?= htmlspecialchars($derived_generic_name) ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Department</label>
                        <select name="department_id" class="form-control" required>
                            <option value="">-- Select --</option>
                            <?php foreach($departments as $dept): ?>
                                <option value="<?= $dept['id'] ?>" <?= $med['department_id'] == $dept['id'] ? 'selected' : '' ?>><?= htmlspecialchars($dept['department_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="form-grid" style="background:#f8fafc; padding:20px; border-radius:8px; border:1px solid #e2e8f0; margin-bottom:20px;">
                    <div class="form-group">
                        <label>Formulation (Form)</label>
                        <select name="drug_formulation" id="drug_formulation" class="form-control" required onchange="showFormulationSymbol()">
                            <option value="" data-symbol="">-- Select Formulation --</option>
                            <?php foreach($formulations as $f): ?>
                                <option value="<?= htmlspecialchars($f['formulation_name']) ?>" data-symbol="<?= htmlspecialchars($f['formulation_symbol']) ?>" <?= $med['drug_formulation'] == $f['formulation_name'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($f['formulation_name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <span id="f_badge" class="symbol-badge" style="display:inline-block;"><?= htmlspecialchars($f_sym) ?></span>
                    </div>
                    
                    <div class="form-group">
                        <label>Strength Value</label>
                        <input class="form-control" name="drug_strength" type="text" value="<?= htmlspecialchars($med['drug_strength']) ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Unit of Measure (Strength)</label>
                        <select name="strength_unit" id="strength_unit" class="form-control" required onchange="showUnitSymbol()">
                            <option value="" data-symbol="">-- Select Unit --</option>
                            <?php foreach($units as $u): ?>
                                <option value="<?= htmlspecialchars($u['unit_name']) ?>" data-symbol="<?= htmlspecialchars($u['unit_symbol']) ?>" <?= $med['strength_unit'] == $u['unit_name'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($u['unit_name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <span id="u_badge" class="symbol-badge" style="display:inline-block;"><?= htmlspecialchars($u_sym) ?></span>
                    </div>
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label>Out-of-Pocket (Cash) Price Per Unit</label>
                        <input class="form-control" name="cash_price" type="number" step="0.01" min="0" value="<?= $med['cash_price'] ?>" style="font-weight:bold; color:#16a34a; background:#f0fdf4;" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Unit of Pricing (Dispensing Base)</label>
                        <input class="form-control" name="unit_of_pricing" id="unit_of_pricing" type="text" value="<?= htmlspecialchars($med['unit_of_pricing']) ?>" required>
                    </div>
                    
                    <div style="display:flex; align-items:flex-end; gap:25px; padding-bottom:10px;">
                        <label class="toggle-switch" style="color:#16a34a;">
                            <input type="checkbox" name="nhis_covered" id="nhis_cov_main" value="1" <?= $med['nhis_covered'] ? 'checked' : '' ?> onchange="toggleNhisBlock()">
                            Covered by NHIS
                        </label>
                        <label class="toggle-switch" style="color:#0284c7;">
                            <input type="checkbox" name="corp_covered" id="corp_cov_main" value="1" <?= $med['corp_covered'] ? 'checked' : '' ?> onchange="toggleCorpBlock()">
                            Covered by Corporate
                        </label>
                    </div>
                </div>
            </div>
        </div>

        <div class="section-box theme-nhis">
            <div class="section-header"><i class="fa-solid fa-file-prescription"></i> 2. National Health Insurance (NHIS) Rules</div>
            <div class="section-body" id="nhis_logic_block" class="transition-block <?= !$med['nhis_covered'] ? 'opacity-50' : '' ?>">
                <div class="form-grid" style="background:#f8fafc; padding:20px; border-radius:8px; border:1px solid #e2e8f0;">
                    <div class="form-group">
                        <label>NHIS Drug Code</label>
                        <input class="form-control" name="nhis_drug_code" id="nhis_drug_code" type="text" value="<?= htmlspecialchars($med['nhis_drug_code'] ?? '') ?>" <?= !$med['nhis_covered'] ? 'disabled' : '' ?>>
                    </div>
                    <div class="form-group">
                        <label>Prescribing Level</label>
                        <select name="prescribing_level" id="prescribing_level" class="form-control" <?= !$med['nhis_covered'] ? 'disabled' : '' ?>>
                            <option value="">-- Select Level --</option>
                            <?php foreach($prescribe_levels as $l): ?>
                                <option value="<?= htmlspecialchars($l['level_code']) ?>" <?= $med['prescribing_level'] == $l['level_code'] ? 'selected' : '' ?>><?= 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 class="form-control" name="drug_tariff" id="drug_tariff" type="number" step="0.01" value="<?= $med['tariff_adult'] ?>" style="border-color:#16a34a;" <?= !$med['nhis_covered'] ? 'disabled' : '' ?>>
                    </div>
                </div>
                
                <div style="margin-top:20px; background:#fef3c7; padding:20px; border-radius:8px; border:1px solid #fde68a; display:flex; gap:20px; align-items:center;">
                    <label class="toggle-switch" style="color:#b45309;">
                        <input type="checkbox" name="is_nhis_copay_required" id="nhis_copay_chk" value="1" <?= $med['is_copay_required'] ? 'checked' : '' ?> onchange="toggleNhisCopay()" <?= !$med['nhis_covered'] ? 'disabled' : '' ?>>
                        Requires Patient Co-Payment (Per Unit)
                    </label>
                    <div class="form-group" style="flex-grow:1; max-width:300px; margin:0;">
                        <input class="form-control" name="nhis_copay_amount" id="nhis_copay_amt" type="number" step="0.01" value="<?= $med['copay_amount'] ?>" <?= (!$med['nhis_covered'] || !$med['is_copay_required']) ? 'disabled' : '' ?> placeholder="Amount Patient Pays (GHS)">
                    </div>
                </div>
            </div>
        </div>

        <div class="section-box theme-corp" id="corp_logic_block">
            <div class="section-header"><i class="fa-solid fa-building-shield"></i> 3. Private / Corporate Provider Routing Matrix</div>
            <div class="section-body" style="padding:0;" class="transition-block <?= !$med['corp_covered'] ? 'opacity-50' : '' ?>">
                <table class="matrix-table">
                    <thead>
                        <tr>
                            <th style="width:30%; padding-left:20px;">Insurance Provider</th>
                            <th style="width:25%;">Agreed Tariff Per Unit (GHS)</th>
                            <th style="width:20%;">Co-Payment Rule</th>
                            <th style="width:25%; padding-right:20px;">Co-Pay Per Unit (GHS)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($insurances as $ins): 
                            $id = $ins['id']; 
                            $is_mapped = isset($existing_corp[$id]);
                            $c_data = $is_mapped ? $existing_corp[$id] : null;
                        ?>
                        <tr>
                            <td style="padding-left:20px;">
                                <label class="toggle-switch blue-accent">
                                    <input type="checkbox" name="corp_mapped[<?= $id ?>]" id="map_<?= $id ?>" value="1" <?= $is_mapped ? 'checked' : '' ?> onchange="toggleCorpRow(<?= $id ?>)" <?= !$med['corp_covered'] ? 'disabled' : '' ?>>
                                    <?= htmlspecialchars($ins['insurance_name']) ?>
                                </label>
                            </td>
                            <td>
                                <input class="form-control" name="corp_tariff[<?= $id ?>]" id="tar_<?= $id ?>" type="number" step="0.01" value="<?= $is_mapped ? $c_data['tariff_amount'] : '' ?>" <?= (!$med['corp_covered'] || !$is_mapped) ? 'disabled' : '' ?>>
                            </td>
                            <td>
                                <label class="toggle-switch blue-accent" style="font-size:12px; color:#64748b;">
                                    <input type="checkbox" name="corp_copay_req[<?= $id ?>]" id="req_<?= $id ?>" value="1" <?= ($is_mapped && $c_data['is_copay_required']) ? 'checked' : '' ?> onchange="toggleCorpCopay(<?= $id ?>)" <?= (!$med['corp_covered'] || !$is_mapped) ? 'disabled' : '' ?>>
                                    Requires Co-Pay
                                </label>
                            </td>
                            <td style="padding-right:20px;">
                                <input class="form-control" name="corp_copay_amt[<?= $id ?>]" id="amt_<?= $id ?>" type="number" step="0.01" value="<?= ($is_mapped && $c_data['is_copay_required']) ? $c_data['copay_amount'] : '' ?>" <?= (!$med['corp_covered'] || !$is_mapped || !$c_data['is_copay_required']) ? 'disabled' : '' ?>>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div style="display:flex; justify-content:flex-end; gap:15px; padding-bottom:30px;">
            <a href="viewMedicine.php?id=<?= $service_id ?>" class="btn btn-secondary">Cancel Edit</a>
            <button type="button" class="btn btn-primary" onclick="document.getElementById('medicineForm').submit();"><i class="fa-solid fa-save"></i> Save System Updates</button>
        </div>

    </form>

</div>

<script>
function showFormulationSymbol() {
    const sel = document.getElementById('drug_formulation');
    const sym = sel.options[sel.selectedIndex].getAttribute('data-symbol');
    const badge = document.getElementById('f_badge');
    if(sym) { badge.style.display = 'inline-block'; badge.innerText = sym; }
    else { badge.style.display = 'none'; }
}

function showUnitSymbol() {
    const sel = document.getElementById('strength_unit');
    const sym = sel.options[sel.selectedIndex].getAttribute('data-symbol');
    const badge = document.getElementById('u_badge');
    if(sym) { 
        badge.style.display = 'inline-block'; 
        badge.innerText = sym; 
    } else { 
        badge.style.display = 'none'; 
    }
}

function toggleNhisBlock() {
    const isCovered = document.getElementById('nhis_cov_main').checked;
    const block = document.getElementById('nhis_logic_block');
    const inputs = block.querySelectorAll('input, select');
    
    if (!isCovered) {
        block.classList.add('opacity-50');
        inputs.forEach(input => {
            if (input.type !== 'checkbox') input.value = '';
            input.disabled = true;
        });
    } else {
        block.classList.remove('opacity-50');
        inputs.forEach(input => {
            if (input.id !== 'nhis_copay_amt') input.disabled = false;
        });
        toggleNhisCopay(); 
    }
}

function toggleNhisCopay() {
    const chk = document.getElementById('nhis_copay_chk').checked;
    const amt = document.getElementById('nhis_copay_amt');
    amt.disabled = !chk;
    if(!chk) amt.value = '';
}

function toggleCorpBlock() {
    const isCovered = document.getElementById('corp_cov_main').checked;
    const block = document.getElementById('corp_logic_block');
    const inputs = block.querySelectorAll('input');
    
    if (!isCovered) {
        block.classList.add('opacity-50');
        inputs.forEach(input => { input.disabled = true; });
    } else {
        block.classList.remove('opacity-50');
        inputs.forEach(input => {
            if (input.type === 'checkbox' && input.id.startsWith('map_')) input.disabled = false;
        });
        const mappedChecks = document.querySelectorAll('input[id^="map_"]');
        mappedChecks.forEach(chk => {
            const id = chk.id.replace('map_', '');
            toggleCorpRow(id);
        });
    }
}

function toggleCorpRow(id) {
    const isMapped = document.getElementById('map_' + id).checked;
    const isCovered = document.getElementById('corp_cov_main').checked;
    
    const tariffInput = document.getElementById('tar_' + id);
    const copayReqChk = document.getElementById('req_' + id);
    const copayAmtInput = document.getElementById('amt_' + id);

    if(!isCovered) return;

    tariffInput.disabled = !isMapped;
    copayReqChk.disabled = !isMapped;
    
    if (!isMapped) {
        tariffInput.value = '';
        copayReqChk.checked = false;
        copayAmtInput.value = '';
        copayAmtInput.disabled = true;
    } else {
        toggleCorpCopay(id);
    }
}

function toggleCorpCopay(id) {
    const isReq = document.getElementById('req_' + id).checked;
    const amtInput = document.getElementById('amt_' + id);
    amtInput.disabled = !isReq;
    if (!isReq) amtInput.value = '';
}
</script>
</body>
</html>