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

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

$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);

// NEW: Fetch Item Categories
$categories = $conn->query("SELECT id, category_name FROM item_categories WHERE is_active = 1 ORDER BY id ASC")->fetch_all(MYSQLI_ASSOC);

// ==============================================================================
// 2. FORM PROCESSING & RELATIONAL INSERTION
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $conn->begin_transaction();
    try {
        // --- A. Core Identity ---
        $category_id = (int)$_POST['category_id'];
        $department_id = (int)$_POST['department_id'];
        $service_type = 'Drug'; // We keep the base module type as 'Drug' for billing routing
        $is_consultation = 0; 
        $target_age_group = 'All Ages'; 
        
        $generic_name = trim($_POST['generic_name']);
        $unit_of_pricing = trim($_POST['unit_of_pricing']);
        
        // NEW: Inventory Control Settings
        $reorder_level = (int)$_POST['reorder_level'];
        $alert_quantity = (int)$_POST['alert_quantity'];

        // Dynamic Logic: Is it a Drug (Requires Formulation) or a Consumable?
        if ($category_id == 1) { // 1 = Drugs & Medications
            $drug_formulation = trim($_POST['drug_formulation']);
            $drug_strength = trim($_POST['drug_strength']);
            $strength_unit = trim($_POST['strength_unit']);
            
            // Fetch Short Symbols
            $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}";
        } else {
            // It's a Consumable (e.g. "Latex Gloves")
            $drug_formulation = null;
            $drug_strength = null;
            $strength_unit = null;
            $service_name = $generic_name;
        }

        // --- B. Base Cash Price ---
        $cash_price = (float)$_POST['cash_price'];

        // --- C. NHIS Formulary Data ---
        $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 = $drug_tariff;
        $tariff_child = $drug_tariff;
        $gdrg_adult_code = null; 
        $gdrg_child_code = null; 

        // 1. Insert into Master Service Catalog
        $stmtMaster = $conn->prepare("
            INSERT INTO service_catalog (
                category_id, department_id, service_name, service_type, is_consultation, target_age_group,
                nhis_covered, corp_covered,
                nhis_drug_code, unit_of_pricing, prescribing_level,
                drug_formulation, drug_strength, strength_unit,
                cash_price, 
                gdrg_adult_code, tariff_adult, gdrg_child_code, tariff_child,
                is_copay_required, copay_amount, reorder_level, alert_quantity, is_active
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
        ");
        
        // Exact 23-character bind string
        $stmtMaster->bind_param("iissisiisssssssdsdidii", 
            $category_id, $department_id, $service_name, $service_type, $is_consultation, $target_age_group,
            $nhis_covered, $corp_covered,
            $nhis_drug_code, $unit_of_pricing, $prescribing_level,
            $drug_formulation, $drug_strength, $strength_unit,
            $cash_price, 
            $gdrg_adult_code, $tariff_adult, $gdrg_child_code, $tariff_child,
            $is_nhis_copay_required, $nhis_copay_amount, $reorder_level, $alert_quantity
        );
        
        if (!$stmtMaster->execute()) {
            throw new Exception("Formulary Insert Failed: " . $stmtMaster->error);
        }
        $service_id = $conn->insert_id;
        $stmtMaster->close();

        // --- D. Corporate Matrix Data ---
        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>Item Added Successfully:</strong> {$service_name} has been secured into the formulary.</div>";

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

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Medicine / Consumable</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
    :root { --e-blue: #1e3a8a; --e-green: #16a34a; --bg: #f8fafc; --border: #e2e8f0; --text: #334155; }
    html, body { height: 100%; margin: 0; font-family: "Segoe UI", Tahoma, sans-serif; background: rgba(15, 23, 42, 0.4); }
    
    .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; backdrop-filter: blur(4px); z-index: 9999; }
    .modal-card { width: 1050px; max-width: 95%; background: #ffffff; border-radius: 12px; box-shadow: 0 20px 40px rgba(0,0,0,0.3); position: relative; max-height: 92vh; display: flex; flex-direction: column; }
    
    .modal-header { padding: 20px 25px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; background: #f0fdf4; border-radius: 12px 12px 0 0; }
    .modal-header h2 { margin: 0; color: var(--e-green); font-size: 20px; font-weight: 800; display:flex; align-items:center; gap:10px; }
    .close-btn { background: #fee2e2; border: none; font-size: 16px; color: #dc2626; cursor: pointer; padding: 6px 12px; border-radius: 6px; font-weight: bold; transition:0.2s; text-decoration:none;}
    .close-btn:hover { background: #fca5a5; }

    .modal-body { padding: 25px; overflow-y: auto; flex-grow: 1; }
    
    .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 { border: 1px solid var(--border); border-radius: 10px; margin-bottom: 25px; background: #fff; overflow: hidden; }
    .section-header { padding: 12px 20px; font-size: 14px; font-weight: 800; text-transform: uppercase; color: #fff; display: flex; align-items: center; gap: 10px; }
    .section-body { padding: 20px; background: #fff; }
    
    .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: 10px 12px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 14px; outline: none; transition:0.2s; }
    .form-control:focus { border-color: var(--e-green); box-shadow: 0 0 0 3px #dcfce7; }
    .form-control:disabled { background: #f1f5f9; color: #94a3b8; cursor: not-allowed; border-style: dashed; }

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

    .matrix-table { width: 100%; border-collapse: collapse; margin-top: 10px; }
    .matrix-table th { background: #f8fafc; padding: 10px; font-size: 12px; color: #64748b; text-transform: uppercase; text-align: left; border-bottom: 2px solid var(--border); }
    .matrix-table td { padding: 12px 10px; 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); }

    .modal-footer { padding: 20px 25px; border-top: 1px solid var(--border); background: #f8fafc; display: flex; justify-content: flex-end; gap: 15px; border-radius: 0 0 12px 12px; }
    .btn { padding: 12px 25px; border-radius: 8px; font-weight: 800; cursor: pointer; font-size: 14px; transition: 0.2s; border: none; }
    .btn-secondary { background: #e2e8f0; color: #475569; }
    .btn-secondary:hover { background: #cbd5e1; }
    .btn-primary { background: var(--e-green); color: #fff; box-shadow: 0 4px 6px rgba(22, 163, 74, 0.2); }
    .btn-primary:hover { background: #15803d; transform: translateY(-1px); }

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

<div class="modal-overlay">
    <div class="modal-card">
        <div class="modal-header">
            <h2><i class="fa-solid fa-boxes-packing"></i> Add Pharmacy Item to Formulary</h2>
            <a href="listMedicine.php" class="close-btn"><i class="fa-solid fa-xmark"></i> Close</a>
        </div>

        <div class="modal-body">
            <?= $message ?>

            <form method="post" id="medicineForm">
                
                <div class="section-box theme-core">
                    <div class="section-header"><i class="fa-solid fa-flask"></i> 1. Item Identity & Inventory Limits</div>
                    <div class="section-body">
                        
                        <div class="form-grid" style="margin-bottom:15px; background:#eff6ff; padding:15px; border-radius:8px; border:1px solid #bfdbfe;">
                            <div class="form-group" style="grid-column: span 2;">
                                <label style="color:#1e40af;">Item Classification (Category)</label>
                                <select name="category_id" id="category_id" class="form-control" style="border-color:#1e40af; font-weight:700;" required onchange="toggleCategoryFields()">
                                    <option value="">-- Select Item Category --</option>
                                    <?php foreach($categories as $cat): ?>
                                        <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['category_name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </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'] ?>" <?= (strtolower($dept['department_name']) == 'pharmacy') ? 'selected' : '' ?>><?= htmlspecialchars($dept['department_name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <div class="form-grid" style="margin-bottom:15px;">
                            <div class="form-group" style="grid-column: span 3;">
                                <label id="name_label">Generic Name / Item Name</label>
                                <input class="form-control" name="generic_name" id="generic_name" type="text" placeholder="e.g. Paracetamol OR Latex Examination Gloves" required>
                            </div>
                        </div>

                        <div id="drug_fields_block" class="form-grid transition-block" style="background:#f8fafc; padding:15px; 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" 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']) ?>">
                                            <?= htmlspecialchars($f['formulation_name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <span id="f_badge" class="symbol-badge"></span>
                            </div>
                            
                            <div class="form-group">
                                <label>Strength Value</label>
                                <input class="form-control" name="drug_strength" id="drug_strength" type="text" placeholder="e.g. 500 or 125/5">
                            </div>
                            
                            <div class="form-group">
                                <label>Unit of Measure (Strength)</label>
                                <select name="strength_unit" id="strength_unit" class="form-control" 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']) ?>">
                                            <?= htmlspecialchars($u['unit_name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <span id="u_badge" class="symbol-badge"></span>
                            </div>
                        </div>

                        <div class="form-grid" style="margin-bottom:20px;">
                            <div class="form-group">
                                <label>Out-of-Pocket (Cash) Price</label>
                                <input class="form-control" name="cash_price" type="number" step="0.01" min="0" 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" placeholder="e.g. mg, mL, Box, Piece" 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" 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" checked onchange="toggleCorpBlock()">
                                    Covered by Corporate
                                </label>
                            </div>
                        </div>

                        <div class="form-grid" style="background:#fffbeb; padding:15px; border-radius:8px; border:1px solid #fde68a;">
                            <div class="form-group">
                                <label style="color:#b45309;"><i class="fa-solid fa-box"></i> Minimum Reorder Level</label>
                                <input class="form-control" name="reorder_level" type="number" min="0" value="10" required>
                            </div>
                            <div class="form-group">
                                <label style="color:#dc2626;"><i class="fa-solid fa-triangle-exclamation"></i> Critical Alert Quantity</label>
                                <input class="form-control" name="alert_quantity" type="number" min="0" value="5" required>
                            </div>
                            <div class="form-group" style="justify-content:center; color:#94a3b8; font-size:11px;">
                                <i>These thresholds apply globally across all your stores and dispensaries to warn procurement.</i>
                            </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">
                        <div class="form-grid" style="background:#f8fafc; padding:15px; 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" placeholder="e.g. ACETAZTA1">
                            </div>
                            <div class="form-group">
                                <label>Prescribing Level</label>
                                <select name="prescribing_level" id="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 class="form-control" name="drug_tariff" id="drug_tariff" type="number" step="0.01" placeholder="0.00" style="border-color:#16a34a;">
                            </div>
                        </div>
                        
                        <div style="margin-top:15px; background:#fef3c7; padding:15px; 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" onchange="toggleNhisCopay()">
                                Requires Patient Co-Payment (Per Unit)
                            </label>
                            <div class="form-group" style="flex-grow:1; max-width:250px;">
                                <input class="form-control" name="nhis_copay_amount" id="nhis_copay_amt" type="number" step="0.01" placeholder="Amount Patient Pays (GHS)" disabled>
                            </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">
                        <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']; ?>
                                <tr>
                                    <td style="padding-left:20px;">
                                        <label class="toggle-switch blue-accent">
                                            <input type="checkbox" name="corp_mapped[<?= $id ?>]" id="map_<?= $id ?>" value="1" onchange="toggleCorpRow(<?= $id ?>)">
                                            <?= htmlspecialchars($ins['insurance_name']) ?>
                                        </label>
                                    </td>
                                    <td>
                                        <input class="form-control" name="corp_tariff[<?= $id ?>]" id="tar_<?= $id ?>" type="number" step="0.01" placeholder="Billed to Ins." 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" onchange="toggleCorpCopay(<?= $id ?>)" 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" placeholder="Patient Pays" disabled>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

            </form>
        </div>
        
        <div class="modal-footer">
            <a href="listMedicine.php" class="btn btn-secondary" style="text-decoration:none;">Cancel & Return</a>
            <button type="button" class="btn btn-primary" onclick="document.getElementById('medicineForm').submit();"><i class="fa-solid fa-save"></i> Save Item to Formulary</button>
        </div>
    </div>
</div>

<script>
// --- UI DYNAMIC CATEGORY LOGIC ---
function toggleCategoryFields() {
    const catId = document.getElementById('category_id').value;
    const drugBlock = document.getElementById('drug_fields_block');
    const nameLabel = document.getElementById('name_label');
    
    // Drug Formulation inputs
    const formSel = document.getElementById('drug_formulation');
    const strInp = document.getElementById('drug_strength');
    const unitSel = document.getElementById('strength_unit');

    if (catId == 1) { // 1 = Drugs
        drugBlock.style.display = 'grid';
        nameLabel.innerText = "Drug Generic Name";
        formSel.required = true;
        strInp.required = true;
        unitSel.required = true;
    } else { // 2 = Consumables, etc.
        drugBlock.style.display = 'none';
        nameLabel.innerText = "Consumable / Item Name";
        formSel.required = false; formSel.value = '';
        strInp.required = false; strInp.value = '';
        unitSel.required = false; unitSel.value = '';
        document.getElementById('f_badge').style.display = 'none';
        document.getElementById('u_badge').style.display = 'none';
    }
}

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; 
        document.getElementById('unit_of_pricing').value = sym;
    } else { 
        badge.style.display = 'none'; 
        document.getElementById('unit_of_pricing').value = '';
    }
}

// --- NHIS LOGIC ---
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 = '';
}

// --- CORPORATE MATRIX LOGIC ---
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 => {
            if (input.type === 'checkbox') input.checked = false;
            else input.value = '';
            input.disabled = true;
        });
    } else {
        block.classList.remove('opacity-50');
        inputs.forEach(input => {
            if (input.type === 'checkbox') input.disabled = false;
        });
    }
}

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

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

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

// Trigger initial state on load
document.addEventListener("DOMContentLoaded", function() {
    toggleCategoryFields();
});
</script>
</body>
</html>