<?php
// Connect to the database
require_once __DIR__ . '/../../../dripend/includes/db.php';

// Dynamically compute browser base path for assets and actions (handles local subfolders or live root domain)
$current_script = str_replace('\\', '/', $_SERVER['SCRIPT_NAME']);
$app_root_pos = strpos($current_script, '/application/');
$base_path = ($app_root_pos !== false) ? substr($current_script, 0, $app_root_pos + 13) : '/application/';

// Fetch the live NHIS configuration directly from the database
$query = "SELECT * FROM nhis_setup WHERE id = 1 LIMIT 1";
$result = mysqli_query($conn, $query);
$nhis = mysqli_fetch_object($result);

// Fallback logic in case the database is empty or the row hasn't been inserted yet
if (!$nhis) {
    $nhis = (object)[
        'facility_code' => 'HSP-TER-001',
        'scheme_code' => '001',
        'provider_category' => '1 - Tertiary Care Hospital',
        'prescribing_level' => 'SD - Specialist / Teaching Hosp.',
        'enable_api_sync' => 1,
        'api_endpoint' => 'https://api.nhis.gov.gh/claims/v1/verify',
        'api_username' => '',
        'api_token' => '',
        'tariff_version' => '2024 G-DRG Tariffs (v4.1)',
        'default_attendance' => 'OPD (Outpatient)',
        'auto_bundle_claims' => 1,
        'xml_export_path' => 'C:/NHIS_Exports/ClaimIT/',
        'accept_referrals' => 1,
        'default_referring_facility' => ''
    ];
}

// Safely fetch recent mappings for the Live Preview table
$recent_mappings = [];
$check_tables = mysqli_query($conn, "SHOW TABLES LIKE 'mapping_service_nhis'");
if ($check_tables && mysqli_num_rows($check_tables) > 0) {
    $map_query = "SELECT s.service_name, s.service_type, g.gdrg_code, m.required_icd10_category, g.adult_tariff, g.child_tariff 
                  FROM mapping_service_nhis m 
                  JOIN service_catalog s ON m.internal_service_id = s.id 
                  JOIN nhis_gdrg_tariffs g ON m.gdrg_id = g.id 
                  ORDER BY m.mapped_at DESC LIMIT 5";
    $map_res = mysqli_query($conn, $map_query);
    if ($map_res) {
        while ($row = mysqli_fetch_assoc($map_res)) {
            $recent_mappings[] = $row;
        }
    }
}
?>

<link rel="stylesheet" href="<?php echo $base_path; ?>assets/css/nhis-config.css">

<style>
    .fac-split-layout {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
        margin-bottom: 20px;
    }
    .fac-panel-left, .fac-panel-right {
        flex: 1 1 calc(50% - 10px);
        min-width: 320px;
    }
    .dict-nav-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 15px;
        margin-bottom: 15px;
    }
    .preview-table-container {
        width: 100%;
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
    }
    @media (max-width: 768px) {
        .fac-panel-left, .fac-panel-right {
            flex: 1 1 100%;
        }
        .fac-form-row {
            flex-direction: column;
            gap: 10px;
        }
    }
</style>

<div class="fac-module">
    <div class="fac-header-area">
        <div class="fac-page-title"><i class="fa-solid fa-shield-halved"></i> NHIS Regulatory Setup</div>
        <div class="fac-page-subtitle">Manage Health Facility codes, accreditation levels, billing formats, and Claim Check Code (CCC) generation modes.</div>
    </div>

    <form id="nhisConfigForm" method="POST" action="<?php echo $base_path; ?>dripend/systemSetup/facility/updateNhisConfig.php">
        
        <div class="fac-split-layout">
            
            <div class="fac-panel fac-panel-left">
                <div class="fac-panel-title"><i class="fa-solid fa-file-contract"></i> NHIA Accreditation Details</div>
                
                <div class="info-box">
                    <strong><i class="fa-solid fa-circle-info"></i> Provider Tier Active: Tertiary Hospital (Category 1)</strong><br>
                    Because this system is configured for a Tertiary facility, high-tier G-DRGs (e.g. specialized surgeries) and complex prescribing levels are automatically unlocked for your clinicians.
                </div>

                <div class="fac-form-row">
                    <div class="fac-form-col">
                        <label>Health Facility Code (NHIA) <span style="color:#dc2626;">*</span></label>
                        <input type="text" name="facility_code" class="fac-input" value="<?php echo htmlspecialchars($nhis->facility_code); ?>" placeholder="e.g. 01020304" required>
                    </div>
                    <div class="fac-form-col">
                        <label>Default Scheme Code <span style="color:#dc2626;">*</span></label>
                        <input type="text" name="scheme_code" class="fac-input" value="<?php echo htmlspecialchars($nhis->scheme_code); ?>" placeholder="e.g. 001" required>
                    </div>
                </div>

                <div class="fac-form-row">
                    <div class="fac-form-col">
                        <label>Provider Category</label>
                        <select class="fac-input" name="provider_category">
                            <option value="1 - Tertiary Care Hospital" <?php echo ($nhis->provider_category == '1 - Tertiary Care Hospital') ? 'selected' : ''; ?>>1 - Tertiary Care Hospital</option>
                            <option value="2 - Secondary Care Hospital" <?php echo ($nhis->provider_category == '2 - Secondary Care Hospital') ? 'selected' : ''; ?>>2 - Secondary Care Hospital</option>
                            <option value="3 - Primary Care Hospital" <?php echo ($nhis->provider_category == '3 - Primary Care Hospital') ? 'selected' : ''; ?>>3 - Primary Care Hospital</option>
                        </select>
                    </div>
                    <div class="fac-form-col">
                        <label>Max Prescribing Level</label>
                        <select class="fac-input" name="prescribing_level">
                            <option value="SD - Specialist / Teaching Hosp." <?php echo ($nhis->prescribing_level == 'SD - Specialist / Teaching Hosp.') ? 'selected' : ''; ?>>SD - Specialist / Teaching Hosp.</option>
                            <option value="A - Primary Care" <?php echo ($nhis->prescribing_level == 'A - Primary Care') ? 'selected' : ''; ?>>A - Primary Care</option>
                            <option value="M - Midwifery" <?php echo ($nhis->prescribing_level == 'M - Midwifery') ? 'selected' : ''; ?>>M - Midwifery</option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="fac-panel fac-panel-right">
                <div class="fac-panel-title"><i class="fa-solid fa-server"></i> CCC Generation Mode</div>

                <div class="api-toggle-container">
                    <div>
                        <span class="api-toggle-text">Enable Automatic API Sync</span>
                        <span class="api-toggle-desc">Fetch Claim Check Codes directly from NHIS servers. Disables manual typing at front desk.</span>
                    </div>
                    <label class="switch">
                        <input type="checkbox" name="enable_api_sync" id="cccApiToggle" value="1" <?php echo ($nhis->enable_api_sync == 1) ? 'checked' : ''; ?> onchange="toggleApiSettings(this)">
                        <span class="slider"></span>
                    </label>
                </div>

                <div id="apiSettingsBlock" style="<?php echo ($nhis->enable_api_sync == 1) ? 'display:block;' : 'display:none;'; ?>">
                    <div class="fac-form-row">
                        <div class="fac-form-col">
                            <label>NHIS ClaimIT API Endpoint</label>
                            <input type="text" id="apiEndpointInput" class="fac-input" value="<?php echo htmlspecialchars($nhis->api_endpoint); ?>" placeholder="https://...">
                        </div>
                    </div>
                    <div class="fac-form-row">
                        <div class="fac-form-col">
                            <label>API Username</label>
                            <input type="text" id="apiUsernameInput" class="fac-input" value="<?php echo htmlspecialchars($nhis->api_username); ?>" placeholder="Enter API Username">
                        </div>
                    </div>
                    <div class="fac-form-row">
                        <div class="fac-form-col">
                            <label>Secure API Token / Key</label>
                            <input type="password" id="apiTokenInput" class="fac-input" value="<?php echo htmlspecialchars($nhis->api_token); ?>" placeholder="Enter secure token">
                        </div>
                    </div>
                    <div class="fac-form-row" style="margin-top: 15px; border-top: 1px solid #e2e8f0; padding-top: 15px;">
                        <div class="fac-form-col">
                            <button type="button" class="fac-btn-primary" style="background: #0f172a;" onclick="saveApiCredentials(this)">
                                <i class="fa-solid fa-lock"></i> Save API Credentials
                            </button>
                        </div>
                        <div class="fac-form-col">
                            <button type="button" class="fac-btn-primary" style="background: #3b82f6;" onclick="alert('UI Test: Firing test ping to NHIS server...')">
                                <i class="fa-solid fa-wifi"></i> Test Connection
                            </button>
                        </div>
                    </div>
                </div>
                
                <div id="manualSettingsBlock" style="<?php echo ($nhis->enable_api_sync == 0) ? 'display:block;' : 'display:none;'; ?> padding: 20px; text-align: center; color: #64748b;">
                    <i class="fa-solid fa-keyboard" style="font-size: 30px; margin-bottom: 10px; color: #cbd5e1;"></i><br>
                    <strong>Manual Mode Active</strong><br>
                    <span style="font-size: 13px;">Front desk clerks will manually type the CCC from the patient's card or slip.</span>
                </div>
            </div>
        </div>

        <div class="fac-split-layout">
            
            <div class="fac-panel fac-panel-left">
                <div class="fac-panel-title"><i class="fa-solid fa-file-invoice-dollar"></i> Claims Export & Billing Rules</div>

                <div class="fac-form-row">
                    <div class="fac-form-col">
                        <label>Active G-DRG Tariff Version <span style="color:#dc2626;">*</span></label>
                        <select class="fac-input" name="tariff_version">
                            <option value="2023 G-DRG Tariffs (v4.0)" <?php echo ($nhis->tariff_version == '2023 G-DRG Tariffs (v4.0)') ? 'selected' : ''; ?>>2023 G-DRG Tariffs (v4.0)</option>
                            <option value="2024 G-DRG Tariffs (v4.1)" <?php echo ($nhis->tariff_version == '2024 G-DRG Tariffs (v4.1)') ? 'selected' : ''; ?>>2024 G-DRG Tariffs (v4.1)</option>
                            <option value="Custom Facility Pricing" <?php echo ($nhis->tariff_version == 'Custom Facility Pricing') ? 'selected' : ''; ?>>Custom Facility Pricing</option>
                        </select>
                    </div>
                    <div class="fac-form-col">
                        <label>Default Attendance Type</label>
                        <select class="fac-input" name="default_attendance">
                            <option value="OPD (Outpatient)" <?php echo ($nhis->default_attendance == 'OPD (Outpatient)') ? 'selected' : ''; ?>>OPD (Outpatient)</option>
                            <option value="INP (Inpatient)" <?php echo ($nhis->default_attendance == 'INP (Inpatient)') ? 'selected' : ''; ?>>INP (Inpatient)</option>
                            <option value="EME (Emergency)" <?php echo ($nhis->default_attendance == 'EME (Emergency)') ? 'selected' : ''; ?>>EME (Emergency)</option>
                        </select>
                    </div>
                </div>

                <div class="api-toggle-container" style="background:#f8fafc;">
                    <div>
                        <span class="api-toggle-text">Auto-Bundle Claims on Discharge</span>
                        <span class="api-toggle-desc">Automatically group itemized services into G-DRG codes when a patient is marked as discharged.</span>
                    </div>
                    <label class="switch">
                        <input type="checkbox" name="auto_bundle_claims" value="1" <?php echo ($nhis->auto_bundle_claims == 1) ? 'checked' : ''; ?>>
                        <span class="slider"></span>
                    </label>
                </div>

                <div class="fac-form-row">
                    <div class="fac-form-col">
                        <label>ClaimIT XML Export Directory Path</label>
                        <input type="text" name="xml_export_path" class="fac-input" value="<?php echo htmlspecialchars($nhis->xml_export_path); ?>" placeholder="E.g., C:/Exports/">
                        <span style="font-size:11px; color:#64748b; margin-top:4px;">The local network or server folder where XML claims are deposited for the ClaimIT application.</span>
                    </div>
                </div>
            </div>

            <div class="fac-panel fac-panel-right">
                <div class="fac-panel-title"><i class="fa-solid fa-network-wired"></i> Affiliations & Referrals</div>

                <div class="api-toggle-container" style="border-color:#d1fae5; background:#ecfdf5;">
                    <div>
                        <span class="api-toggle-text" style="color:#065f46;">Accept External NHIS Referrals</span>
                        <span class="api-toggle-desc" style="color:#047857;">Allow billing for patients transferred from Primary/Secondary clinics.</span>
                    </div>
                    <label class="switch">
                        <input type="checkbox" id="referralToggle" name="accept_referrals" value="1" <?php echo ($nhis->accept_referrals == 1) ? 'checked' : ''; ?> onchange="toggleReferralSettings(this)">
                        <span class="slider"></span>
                    </label>
                </div>

                <div id="referralSettingsBlock" style="<?php echo ($nhis->accept_referrals == 1) ? 'display:block;' : 'display:none;'; ?>">
                    <div class="fac-form-row">
                        <div class="fac-form-col">
                            <label>Default Referring Facility Code (Optional)</label>
                            <input type="text" name="default_referring_facility" class="fac-input" value="<?php echo htmlspecialchars($nhis->default_referring_facility); ?>" placeholder="e.g. HSP-PRI-045">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="fac-split-layout">
            <div class="fac-panel" style="width: 100%; border-color: #10b981; border-top-width: 4px;">
                
                <div class="fac-panel-title" style="display:flex; justify-content:space-between; flex-wrap: wrap; gap: 10px;">
                    <span><i class="fa-solid fa-book-medical" style="color:#10b981;"></i> Tariff & Coding Dictionaries</span>
                    <a href="gdrg/gdrg_icd_mapping.php" data-title="Service to NHIS Mapping" class="fac-btn-outline"><i class="fa-solid fa-arrow-up-right-from-square"></i> Open Full Mapping Studio</a>
                </div>

                <div class="dict-nav-grid">
                    <a href="gdrg/nhis_tariffs.php" data-title="NHIS Tariffs Master" class="dict-card">
                        <div class="dict-icon" style="background:#d1fae5; color:#059669;"><i class="fa-solid fa-coins"></i></div>
                        <div class="dict-text">
                            <h4>G-DRG Tariffs Master</h4>
                            <p>Manage payouts for Adult, Child, & Maternal</p>
                        </div>
                    </a>
                    <a href="gdrg/icd10_dict.php" data-title="ICD-10 Dictionary" class="dict-card">
                        <div class="dict-icon" style="background:#e0e7ff; color:#4338ca;"><i class="fa-solid fa-book-journal-whills"></i></div>
                        <div class="dict-text">
                            <h4>ICD-10 Dictionary</h4>
                            <p>Manage active diagnosis classifications</p>
                        </div>
                    </a>
                    <a href="pharmacy/listMedicine.php" data-title="Master Medicine List" class="dict-card">
                        <div class="dict-icon" style="background:#fef3c7; color:#d97706;"><i class="fa-solid fa-pills"></i></div>
                        <div class="dict-text">
                            <h4>NHIS Medicines List</h4>
                            <p>Link generic drugs to NHIS formulary</p>
                        </div>
                    </a>
                </div>

                <div style="font-size: 13px; font-weight: 700; color: #1e293b; margin-bottom: 12px; margin-top: 15px;">
                    Recent Service Mappings Preview
                </div>

                <div class="preview-table-container">
                    <table class="preview-table">
                        <thead>
                            <tr>
                                <th>Internal Service Name</th>
                                <th>Type</th>
                                <th>Mapped NHIS Code (G-DRG)</th>
                                <th>Required ICD-10 Category</th>
                                <th>Adult Payout</th>
                                <th>Child Payout</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($recent_mappings)): ?>
                                <?php foreach ($recent_mappings as $map): ?>
                                    <tr>
                                        <td><strong><?php echo htmlspecialchars($map['service_name']); ?></strong></td>
                                        <td>
                                            <span class="preview-badge" style="background:#f3e8ff; color:#be185d; border-color:#fbcfe8;">
                                                <?php echo htmlspecialchars($map['service_type']); ?>
                                            </span>
                                        </td>
                                        <td><span style="font-family:monospace; background:#f1f5f9; padding:2px 6px; border-radius:4px;"><?php echo htmlspecialchars($map['gdrg_code']); ?></span></td>
                                        <td><span style="color:#64748b; font-size:12px;"><?php echo htmlspecialchars($map['required_icd10_category'] ?: 'Universal (Any)'); ?></span></td>
                                        <td><span class="price-tag">GHS <?php echo number_format($map['adult_tariff'], 2); ?></span></td>
                                        <td><span class="price-tag">GHS <?php echo number_format($map['child_tariff'], 2); ?></span></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6" style="text-align: center; color: #94a3b8; font-style: italic; padding: 20px;">
                                        <i class="fa-solid fa-link-slash" style="font-size: 20px; display: block; margin-bottom: 8px; color: #cbd5e1;"></i>
                                        No recent service mappings found. Open the Full Mapping Studio to begin mapping internal services to NHIS codes.
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

            </div>
        </div>

        <div style="background:#fff; border:1px solid #e2e8f0; border-radius:12px; padding: 20px; text-align: right; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.02); margin-top: 20px;">
            <button type="submit" class="fac-btn-primary" style="width: auto; display: inline-flex;" onclick="testFormSave(this)"><i class="fa-solid fa-floppy-disk"></i> Save All NHIS Configurations</button>
        </div>
    </form>
</div>

<script src="<?php echo $base_path; ?>assets/js/nhis-config.js"></script>