<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
ini_set('display_errors', 0);
error_reporting(0);

// Up 3 levels from views/system_setup/laboratory to application/ root directory
require_once __DIR__ . '/../../../dripend/includes/db.php';

// Sniff application baseline directory structures dynamically
$requestRoot = '';
if (strpos($_SERVER['SCRIPT_NAME'], '/application/') !== false) {
    $requestRoot = explode('/application/', $_SERVER['SCRIPT_NAME'])[0] . '/application';
} else {
    $requestRoot = dirname(dirname(dirname($_SERVER['SCRIPT_NAME'])));
}
$requestRoot = rtrim($requestRoot, '/\\');

// Fetch options directly from database to enforce zero hardcoding rules
$genders = [];
$resG = $conn->query("SELECT 'Universal' AS gender_name UNION SELECT gender_name FROM gender ORDER BY gender_name DESC");
if ($resG) {
    while($row = $resG->fetch_assoc()) {
        $genders[] = $row;
    }
}

// Fetch only 'Numeric' parameters since qualitative profiles do not utilize numeric boundaries
$numeric_params = [];
$resP = $conn->query("SELECT id, parameter_name, unit_of_measure FROM lab_parameters WHERE result_type = 'Numeric' AND is_active = 1 ORDER BY parameter_name ASC");
if ($resP) {
    while($row = $resP->fetch_assoc()) {
        $numeric_params[] = $row;
    }
}

$selected_param_id = isset($_GET['param_id']) ? (int)$_GET['param_id'] : 0;
$active_param_details = null;
$existing_ranges = [];

if ($selected_param_id > 0) {
    $stmtParam = $conn->prepare("SELECT parameter_name, unit_of_measure FROM lab_parameters WHERE id = ?");
    $stmtParam->bind_param("i", $selected_param_id);
    $stmtParam->execute();
    $active_param_details = $stmtParam->get_result()->fetch_assoc();
    $stmtParam->close();

    $stmtRanges = $conn->prepare("SELECT * FROM lab_reference_ranges WHERE parameter_id = ? ORDER BY gender_target ASC, min_age_years ASC");
    $stmtRanges->bind_param("i", $selected_param_id);
    $stmtRanges->execute();
    $resR = $stmtRanges->get_result();
    while($row = $resR->fetch_assoc()) {
        $existing_ranges[] = $row;
    }
    $stmtRanges->close();
}
?>

<style>
.lis-module { width: 100%; animation: fadeIn 0.3s ease-in-out; }
.lis-header-area { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; }
.lis-page-title { font-size: 22px; font-weight: 700; color: #0f172a; display: flex; align-items: center; gap: 10px; }
.lis-page-title i { color: #b45309; }

/* 5-Column Grid Navigation Matrix */
.lis-nav { display: grid; grid-template-columns: repeat(5, 1fr); gap: 16px; margin-bottom: 32px; }
@media (max-width: 1200px) { .lis-nav { grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); } }

.lis-card { padding: 16px; border-radius: 10px; text-decoration: none; border: 1px solid transparent; transition: 0.3s; display: flex; align-items: center; gap: 12px; background: #fff; color: inherit; }
.lis-card i { font-size: 22px; }
.lis-card div strong { display: block; font-size: 13px; font-weight: 700; margin-bottom: 4px; }
.lis-card div span { font-size: 11px; opacity: 0.85; line-height: 1.3; display: block; }

.c-blue { background: #eff6ff; color: #1e3a8a; border-color: #bfdbfe; }
.c-blue:hover { transform: translateY(-3px); box-shadow: 0 8px 12px rgba(30,58,138,0.1); }
.c-orange { background: #fffbeb; color: #b45309; border-color: #fde68a; }
.c-orange:hover { transform: translateY(-3px); box-shadow: 0 8px 12px rgba(180,83,9,0.1); }
.c-green { background: #f0fdf4; color: #166534; border-color: #bbf7d0; }
.c-green:hover { transform: translateY(-3px); box-shadow: 0 8px 12px rgba(22,101,52,0.1); }
.c-purple { background: #faf5ff; color: #831843; border-color: #fbcfe8; }
.c-purple:hover { transform: translateY(-3px); box-shadow: 0 8px 12px rgba(131,24,67,0.1); }
.c-red { background: #fef2f2; color: #991b1b; border-color: #fecaca; }
.c-red:hover { transform: translateY(-3px); box-shadow: 0 8px 12px rgba(153,27,27,0.1); }

/* Split Layout for Configuration Panels */
.lis-split-layout { display: flex; gap: 24px; flex-wrap: wrap; align-items: flex-start; }
.lis-panel { background: #fff; border-radius: 12px; padding: 24px; border: 1px solid #e2e8f0; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.02); }
.lis-panel-left { flex: 1; min-width: 320px; }
.lis-panel-right { flex: 2; min-width: 500px; }
.lis-panel-title { font-size: 15px; font-weight: 700; color: #1e293b; margin-bottom: 20px; padding-bottom: 12px; border-bottom: 1px solid #e2e8f0; display:flex; align-items:center; gap:8px;}

/* Forms Layout */
.lis-form-row { display: flex; gap: 16px; margin-bottom: 16px; flex-wrap: wrap; }
.lis-form-col { flex: 1; display: flex; flex-direction: column; gap: 6px; min-width: 120px; }
.lis-form-col label { font-size: 11px; font-weight: 700; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; }
.lis-input { padding: 10px 14px; border-radius: 6px; border: 1px solid #cbd5e1; font-size: 13px; outline: none; width: 100%; background: #f8fafc; color: #334155; transition: 0.2s; box-sizing: border-box; }
.lis-input:focus { border-color: #3b82f6; background: #fff; box-shadow: 0 0 0 3px #eff6ff; }

.lis-btn-primary { background: #3b82f6; color: #fff; border: none; padding: 12px 20px; border-radius: 8px; font-weight: 600; font-size: 13px; cursor: pointer; transition: 0.2s; width: 100%; margin-top: 10px; display: flex; justify-content: center; align-items: center; gap: 8px;}
.lis-btn-primary:hover { background: #2563eb; transform: translateY(-1px); box-shadow: 0 4px 6px rgba(37,99,235,0.2); }

/* Table & Badges */
.table-container { overflow-x: auto; }
.lis-table { width: 100%; border-collapse: collapse; text-align: left; font-size: 13px; }
.lis-table th { padding: 14px; color: #64748b; background: #f8fafc; border-bottom: 1px solid #e2e8f0; text-transform: uppercase; font-size: 11px; font-weight: 700; letter-spacing: 0.5px; }
.lis-table td { padding: 14px; border-bottom: 1px solid #f1f5f9; vertical-align: middle; color: #334155; }
.lis-table tr:hover td { background: #f8fafc; }

.lis-badge { padding: 5px 10px; border-radius: 12px; font-size: 10px; font-weight: 700; text-transform: uppercase; display: inline-block; }
.bg-green { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
.bg-red { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }

/* Action Links */
.action-group { display: flex; gap: 6px; justify-content: flex-end; }
.btn-icon { width: 30px; height: 30px; border-radius: 6px; display: inline-flex; align-items: center; justify-content: center; font-size: 13px; cursor: pointer; border: 1px solid transparent; text-decoration: none; transition: 0.2s; color: inherit; }
.b-view { background: #f1f5f9; color: #475569; border-color: #cbd5e1; }
.b-edit { background: #fef3c7; color: #b45309; border-color: #fde68a; }
.b-toggle { background: #e0f2fe; color: #0369a1; border-color: #bae6fd; }
.b-delete { background: #fee2e2; color: #dc2626; border-color: #fecaca; }
.btn-icon:hover { filter: brightness(0.95); transform: translateY(-1px); }

/* Message Boxes */
.lis-alert { padding: 14px 16px; border-radius: 8px; margin-bottom: 24px; font-size: 14px; font-weight: 600; display: none; align-items: center; gap: 10px; }
.lis-alert-success { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
.lis-alert-error { background: #fef2f2; color: #991b1b; border: 1px solid #fecaca; }
</style>

<script>
    window.rimaxAppRoot = '<?php echo $requestRoot; ?>';
    window.currentSelectedParamId = <?php echo $selected_param_id; ?>;
</script>

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" onload="
    if (typeof window.initReferenceRangesModule === 'function') {
        window.initReferenceRangesModule();
    } else {
        const script = document.createElement('script');
        script.src = window.rimaxAppRoot + '/assets/js/referenceRanges.js?v=' + new Date().getTime();
        script.onload = () => window.initReferenceRangesModule();
        document.head.appendChild(script);
    }
    this.remove();
" style="display:none;">

<div class="lis-module">
    <div class="lis-header-area">
        <div class="lis-page-title"><i class="fa-solid fa-chart-line"></i> Parameter Reference Ranges</div>
    </div>

    <div class="lis-nav">
        <a href="javascript:void(0);" onclick="if(typeof loadContent==='function'){loadContent('Laboratory Settings','laboratory/manageLabParameters.php','Laboratory','system_setup',null,true);}" class="lis-card c-blue">
            <i class="fa-solid fa-vials"></i>
            <div>
                <strong>1. Base Params</strong>
                <span>Manage names & units.</span>
            </div>
        </a>
        <a href="javascript:void(0);" onclick="if(typeof loadContent==='function'){loadContent('Laboratory Settings','laboratory/manageReferenceRanges.php','Laboratory','system_setup',null,true);}" class="lis-card c-orange" style="border-color:#b45309; background:#fef3c7;">
            <i class="fa-solid fa-chart-line"></i>
            <div>
                <strong>2. Ref. Ranges</strong>
                <span>Define high/low limits.</span>
            </div>
        </a>
        <a href="javascript:void(0);" onclick="if(typeof loadContent==='function'){loadContent('Laboratory Settings','laboratory/manageSamples.php','Laboratory','system_setup',null,true);}" class="lis-card c-green">
            <i class="fa-solid fa-vial-circle-check"></i>
            <div>
                <strong>3. Samples</strong>
                <span>Dictionary & containers.</span>
            </div>
        </a>
        <a href="javascript:void(0);" onclick="if(typeof loadContent==='function'){loadContent('Laboratory Settings','laboratory/mapLabParameters.php','Laboratory','system_setup',null,true);}" class="lis-card c-purple">
            <i class="fa-solid fa-link"></i>
            <div>
                <strong>4. Map Tests</strong>
                <span>Link params & samples.</span>
            </div>
        </a>
        <a href="javascript:void(0);" onclick="if(typeof loadContent==='function'){loadContent('Laboratory Settings','laboratory/mapLabDepartments.php','Laboratory','system_setup',null,true);}" class="lis-card c-red">
            <i class="fa-solid fa-sitemap"></i>
            <div>
                <strong>5. Sub-Depts</strong>
                <span>Categorize Lab Benches.</span>
            </div>
        </a>
    </div>

    <div id="rangeGlobalSuccessAlert" class="lis-alert lis-alert-success"></div>
    <div id="rangeGlobalErrorAlert" class="lis-alert lis-alert-error"></div>

    <div class="lis-split-layout">
        
        <div class="lis-panel lis-panel-left">
            <div class="lis-panel-title"><i class="fa-solid fa-filter"></i> Select Parameter</div>
            
            <form id="paramFilterForm" autocomplete="off">
                <div class="lis-form-col">
                    <label for="paramSelectDropdown">Select a Numeric Parameter</label>
                    <select id="paramSelectDropdown" name="param_id" class="lis-input">
                        <option value="">-- Choose Parameter --</option>
                        <?php foreach($numeric_params as $p): ?>
                            <option value="<?php echo $p['id']; ?>" <?php if($selected_param_id == $p['id']) echo 'selected'; ?>>
                                <?php echo htmlspecialchars($p['parameter_name']); ?> (<?php echo htmlspecialchars($p['unit_of_measure'] ?? '-'); ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </form>

            <div id="addNewRuleContainer" style="display: <?php echo ($selected_param_id > 0) ? 'block' : 'none'; ?>; margin-top: 24px; border-top: 1px solid #e2e8f0; padding-top: 24px;">
                <div class="lis-panel-title" style="color:#b45309; border-bottom:none; margin-bottom:12px;">
                    <i class="fa-solid fa-plus-circle"></i> Add New Reference Rule
                </div>
                
                <form id="addReferenceRangeForm" novalidate>
                    <input type="hidden" id="hiddenParameterId" name="parameter_id" value="<?php echo $selected_param_id; ?>">

                    <div class="lis-form-row">
                        <div class="lis-form-col">
                            <label for="gender_target">Target Demographic Group</label>
                            <select name="gender_target" id="gender_target" class="lis-input">
                                <?php foreach($genders as $g): ?>
                                    <option value="<?php echo htmlspecialchars($g['gender_name']); ?>">
                                        <?php echo htmlspecialchars($g['gender_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="lis-form-row">
                        <div class="lis-form-col">
                            <label for="min_age_years">Min Age (Years)</label>
                            <input type="number" name="min_age_years" id="min_age_years" class="lis-input" value="0" min="0" required>
                        </div>
                        <div class="lis-form-col">
                            <label for="max_age_years">Max Age (Years)</label>
                            <input type="number" name="max_age_years" id="max_age_years" class="lis-input" value="150" min="0" required>
                        </div>
                    </div>

                    <div style="background:#f8fafc; padding:16px; border-radius:8px; border:1px solid #e2e8f0; margin-top:10px; margin-bottom:16px;">
                        <span id="volumetricUnitHeader" style="display:block; font-size:12px; font-weight:700; color:#3b82f6; margin-bottom:12px;">
                            Normal Reference Range limits (<?php echo htmlspecialchars($active_param_details['unit_of_measure'] ?? ''); ?>)
                        </span>
                        <div class="lis-form-row" style="margin-bottom:0;">
                            <div class="lis-form-col">
                                <label for="min_value">Min Normal Value</label>
                                <input type="number" step="0.0001" name="min_value" id="min_value" class="lis-input" style="background:#fff;">
                            </div>
                            <div class="lis-form-col">
                                <label for="max_value">Max Normal Value</label>
                                <input type="number" step="0.0001" name="max_value" id="max_value" class="lis-input" style="background:#fff;">
                            </div>
                        </div>
                    </div>

                    <div style="background:#fef2f2; padding:16px; border-radius:8px; border:1px dashed #fca5a5; margin-bottom:20px;">
                        <span style="display:block; font-size:12px; font-weight:700; color:#b91c1c; margin-bottom:12px;">
                            <i class="fa-solid fa-triangle-exclamation"></i> Critical / Panic Limits (Optional)
                        </span>
                        <div class="lis-form-row" style="margin-bottom:0;">
                            <div class="lis-form-col">
                                <label for="critical_low" style="color:#991b1b;">Critical Low (<)</label>
                                <input type="number" step="0.0001" name="critical_low" id="critical_low" class="lis-input" style="background:#fff; border-color:#fecaca;">
                            </div>
                            <div class="lis-form-col">
                                <label for="critical_high" style="color:#991b1b;">Critical High (>)</label>
                                <input type="number" step="0.0001" name="critical_high" id="critical_high" class="lis-input" style="background:#fff; border-color:#fecaca;">
                            </div>
                        </div>
                    </div>

                    <button type="submit" id="btnSaveRangeRule" class="lis-btn-primary">
                        <i class="fa-solid fa-floppy-disk"></i> Save Range Rule
                    </button>
                </form>
            </div>
        </div>

        <div class="lis-panel lis-panel-right">
            <div class="lis-panel-title"><i class="fa-solid fa-table-list"></i> Configured Ranges</div>
            
            <div id="rangesTableContainer" class="table-container">
                <?php if($selected_param_id > 0): ?>
                    <table class="lis-table">
                        <thead>
                            <tr>
                                <th width="30%">Gender / Age Context</th>
                                <th width="40%">Configured Ranges</th>
                                <th width="15%">Status</th>
                                <th width="15%" style="text-align:right;">Actions</th>
                            </tr>
                        </thead>
                        <tbody id="rangesTableBody">
                            <?php if(!empty($existing_ranges)): ?>
                                <?php foreach($existing_ranges as $r): ?>
                                <tr data-row-id="<?php echo $r['id']; ?>">
                                    <td>
                                        <span style="font-weight:700; color:#1e293b; display:block; margin-bottom:4px;"><?php echo htmlspecialchars($r['gender_target']); ?></span>
                                        <span style="font-size:11px; color:#64748b;"><i class="fa-solid fa-clock"></i> <?php echo $r['min_age_years']; ?> to <?php echo $r['max_age_years']; ?> yrs</span>
                                    </td>
                                    <td>
                                        <span style="background:#e0f2fe; color:#0369a1; padding:4px 10px; border-radius:6px; font-weight:700; font-size:12px; display:inline-block; margin-bottom:6px; border:1px solid #bae6fd;">
                                            <?php echo ($r['min_value'] !== null) ? (float)$r['min_value'] : '0'; ?> - <?php echo ($r['max_value'] !== null) ? (float)$r['max_value'] : '∞'; ?>
                                        </span>
                                        <div style="font-size:11px; color:#b91c1c; line-height:1.5; font-weight:500;">
                                            <?php if($r['critical_low'] !== null) echo "Crit Low: &lt; " . (float)$r['critical_low'] . "<br>"; ?>
                                            <?php if($r['critical_high'] !== null) echo "Crit High: &gt; " . (float)$r['critical_high']; ?>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="lis-badge <?php echo ($r['is_active'] == 1) ? 'bg-green' : 'bg-red'; ?>">
                                            <?php echo ($r['is_active'] == 1) ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div class="action-group">
                                            <button type="button" class="btn-icon b-toggle btn-toggle-status-range" data-id="<?php echo $r['id']; ?>" data-status="<?php echo $r['is_active']; ?>" title="Toggle Visibility">
                                                <i class="fa-solid <?php echo ($r['is_active'] == 1) ? 'fa-ban' : 'fa-check'; ?>"></i>
                                            </button>
                                            <button type="button" class="btn-icon b-delete btn-delete-range-rule" data-id="<?php echo $r['id']; ?>" title="Drop Rule">
                                                <i class="fa-solid fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" style="text-align:center; padding:40px; color:#94a3b8;">
                                        <i class="fa-solid fa-ruler-horizontal" style="font-size:32px; margin-bottom:12px; color:#cbd5e1;"></i><br>
                                        <span style="font-size:14px; font-weight:500;">No ranges defined for this parameter configuration.</span>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <div id="selectionPlaceholderNotice" style="text-align:center; padding:80px 20px; color:#94a3b8;">
                        <i class="fa-solid fa-hand-pointer" style="font-size:48px; margin-bottom:16px; color:#e2e8f0;"></i><br>
                        <span style="font-size: 15px; font-weight: 500;">Please select a parameter from the left panel to examine or construct range metrics.</span>
                    </div>
                <?php endif; ?>
            </div>
        </div>

    </div>
</div>