<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Assuming db.php is handled by the wrapper, but safeguarded here.
if (!isset($conn)) {
    require_once __DIR__ . '/../../../dripend/includes/db.php';
}

$msg = '';
$error = '';

// ==============================================================================
// 1. NATIVE POST PROCESSING (Bypasses AJAX/JSON wrapper conflicts)
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // A. Handle Append Recipe
    if (isset($_POST['map_test_recipe'])) {
        $service_id = (int)$_POST['service_id'];
        $parameter_ids = $_POST['parameter_ids'] ?? [];
        $sample_ids = $_POST['sample_ids'] ?? [];

        if ($service_id === 0) {
            $error = "Please select a valid Test from the catalog.";
        } else {
            $conn->begin_transaction();
            try {
                if (!empty($parameter_ids)) {
                    $stmtMax = $conn->prepare("SELECT MAX(display_order) AS max_order FROM lab_test_parameter_mapping WHERE service_id = ?");
                    $stmtMax->bind_param("i", $service_id);
                    $stmtMax->execute();
                    $resMax = $stmtMax->get_result()->fetch_assoc();
                    $order = ($resMax['max_order'] ?? 0) + 1;
                    $stmtMax->close();

                    $stmtInsParams = $conn->prepare("INSERT IGNORE INTO lab_test_parameter_mapping (service_id, parameter_id, display_order) VALUES (?, ?, ?)");
                    foreach ($parameter_ids as $pid) {
                        $pid = (int)$pid;
                        $stmtInsParams->bind_param("iii", $service_id, $pid, $order);
                        $stmtInsParams->execute();
                        if ($stmtInsParams->affected_rows > 0) $order++; 
                    }
                }

                if (!empty($sample_ids)) {
                    $stmtInsSamples = $conn->prepare("INSERT IGNORE INTO lab_test_samples (service_id, sample_id) VALUES (?, ?)");
                    foreach ($sample_ids as $sid) {
                        $sid = (int)$sid;
                        $stmtInsSamples->bind_param("ii", $service_id, $sid);
                        $stmtInsSamples->execute();
                    }
                }
                
                $conn->commit();
                $msg = "Test recipe successfully mapped and saved.";
            } catch (Exception $e) {
                $conn->rollback();
                $error = "Failed to update test configuration: " . $e->getMessage();
            }
        }
    } 
    
    // B. Handle Quick Delete
    elseif (isset($_POST['clear_service_id'])) {
        $sid = (int)$_POST['clear_service_id'];
        $conn->begin_transaction();
        try {
            $conn->query("DELETE FROM lab_test_parameter_mapping WHERE service_id = $sid");
            $conn->query("DELETE FROM lab_test_samples WHERE service_id = $sid");
            $conn->commit();
            $msg = "Test mapping completely unlinked.";
        } catch (Exception $e) {
            $conn->rollback();
            $error = "Failed to clear mapping: " . $e->getMessage();
        }
    }
}

// ==============================================================================
// 2. DYNAMIC DATABASE FETCHING (Fully Responsive, No Hardcoded Strings)
// ==============================================================================

// Group services dynamically based on the SQL foreign key relations
$services_by_dept = [];
$qServices = "
    SELECT sc.id, sc.service_name, d.department_name
    FROM service_catalog sc
    LEFT JOIN departments d ON sc.department_id = d.id
    WHERE sc.is_active = 1
    ORDER BY d.department_name ASC, sc.service_name ASC
";
$resS = $conn->query($qServices);
if ($resS) {
    while($row = $resS->fetch_assoc()) {
        $dept = $row['department_name'] ?: 'Uncategorized';
        $services_by_dept[$dept][] = $row;
    }
}

// Fetch Parameters
$parameters = [];
$resP = $conn->query("SELECT id, parameter_name, result_type FROM lab_parameters WHERE is_active = 1 ORDER BY parameter_name ASC");
if ($resP) while($row = $resP->fetch_assoc()) $parameters[] = $row;

// Fetch Samples
$samples = [];
$resSamp = $conn->query("SELECT id, sample_name, container_type FROM lab_sample_types WHERE is_active = 1 ORDER BY sample_name ASC");
if ($resSamp) while($row = $resSamp->fetch_assoc()) $samples[] = $row;

// Mapped Data Directory
$mapped_tests = [];
$qMap = "
    SELECT 
        s.id AS service_id, 
        s.service_name,
        d.department_name,
        (SELECT GROUP_CONCAT(p.parameter_name ORDER BY m.display_order ASC SEPARATOR ' • ') FROM lab_test_parameter_mapping m JOIN lab_parameters p ON m.parameter_id = p.id WHERE m.service_id = s.id) AS mapped_params,
        (SELECT GROUP_CONCAT(st.sample_name SEPARATOR ' • ') FROM lab_test_samples sm JOIN lab_sample_types st ON sm.sample_id = st.id WHERE sm.service_id = s.id) AS mapped_samples,
        (SELECT COUNT(*) FROM lab_test_parameter_mapping WHERE service_id = s.id) AS param_count,
        (SELECT COUNT(*) FROM lab_test_samples WHERE service_id = s.id) AS sample_count
    FROM service_catalog s
    LEFT JOIN departments d ON s.department_id = d.id
    HAVING param_count > 0 OR sample_count > 0
    ORDER BY d.department_name ASC, s.service_name ASC
";
$resMap = $conn->query($qMap);
if ($resMap) while($row = $resMap->fetch_assoc()) $mapped_tests[] = $row;

// Pass mappings to JS for UI filtering
$js_mappings = [];
$mapQ1 = $conn->query("SELECT service_id, parameter_id FROM lab_test_parameter_mapping");
if($mapQ1) while($row = $mapQ1->fetch_assoc()) {
    $sid = $row['service_id'];
    if(!isset($js_mappings[$sid])) $js_mappings[$sid] = ['params' => [], 'samples' => []];
    $js_mappings[$sid]['params'][] = (string)$row['parameter_id'];
}
$mapQ2 = $conn->query("SELECT service_id, sample_id FROM lab_test_samples");
if($mapQ2) while($row = $mapQ2->fetch_assoc()) {
    $sid = $row['service_id'];
    if(!isset($js_mappings[$sid])) $js_mappings[$sid] = ['params' => [], 'samples' => []];
    $js_mappings[$sid]['samples'][] = (string)$row['sample_id'];
}
?>

<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; flex-wrap: wrap; gap: 15px; }
.lis-page-title { font-size: 22px; font-weight: 700; color: #0f172a; display: flex; align-items: center; gap: 10px; }
.lis-page-title i { color: #831843; }
.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; }
.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-orange { background: #fffbeb; color: #b45309; border-color: #fde68a; }
.c-green { background: #f0fdf4; color: #166534; border-color: #bbf7d0; }
.c-purple { background: #faf5ff; color: #831843; border-color: #fbcfe8; }
.c-red { background: #fef2f2; color: #991b1b; border-color: #fecaca; }
.lis-split-layout { display: flex; gap: 24px; flex-wrap: wrap; align-items: stretch; }
.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; overflow-x: auto; }
.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;}
.lis-form-col { display: flex; flex-direction: column; gap: 8px; margin-bottom: 20px; }
.lis-form-col label { font-size: 11px; font-weight: 700; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; }
.lis-input-control { padding: 10px 14px; border-radius: 8px; border: 1px solid #cbd5e1; font-size: 13px; outline: none; width: 100%; font-weight:600; background: #f8fafc; color: #1e293b; transition: 0.2s;}
.lis-input-control:focus { border-color: #d946ef; box-shadow: 0 0 0 3px #fae8ff; background: #fff; }
.lis-checkbox-grid { display: grid; grid-template-columns: 1fr; gap: 8px; max-height: 250px; overflow-y: auto; padding-right: 10px; border: 1px solid #e2e8f0; border-radius: 8px; padding: 12px; background: #f8fafc; }
.lis-chk-label { display: flex; align-items: center; gap: 10px; font-size: 13px; font-weight: 600; cursor: pointer; padding: 8px; border-radius: 6px; transition: 0.2s; color:#334155;}
.lis-chk-label:hover { background: #e2e8f0; }
.lis-chk-input { width: 16px; height: 16px; accent-color: #9d174d; cursor: pointer; }
.lis-param-meta { font-size: 10px; color: #475569; font-weight: 600; margin-left: auto; background: #e2e8f0; padding: 3px 8px; border-radius: 12px; text-transform:uppercase; letter-spacing: 0.5px;}
.lis-btn-primary { background: #9d174d; color: #fff; border: none; padding: 12px 24px; border-radius: 8px; font-weight: 600; font-size: 14px; cursor: pointer; transition: 0.2s; width: 100%; display: flex; justify-content: center; align-items: center; gap: 8px; margin-top: 10px;}
.lis-btn-primary:hover { background: #831843; transform: translateY(-1px); box-shadow: 0 4px 6px rgba(131, 24, 67, 0.2);}
.lis-table { width: 100%; border-collapse: collapse; text-align: left; font-size: 13px; }
.lis-table th { padding: 14px; color: #64748b; border-bottom: 1px solid #e2e8f0; text-transform: uppercase; font-size: 11px; font-weight: 700; background: #f8fafc; letter-spacing: 0.5px;}
.lis-table td { padding: 14px; border-bottom: 1px solid #f1f5f9; vertical-align: middle; line-height: 1.6; color: #334155;}
.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; }
.b-view { background: #f1f5f9; color: #475569; border-color: #cbd5e1; }
.b-edit { background: #fef3c7; color: #b45309; border-color: #fde68a; }
.b-arrange { background: #e0e7ff; color: #0369a1; border-color: #bae6fd; } 
.b-delete { background: #fee2e2; color: #dc2626; border-color: #fecaca; }
.lis-alert { padding: 14px 16px; border-radius: 8px; margin-bottom: 24px; font-size: 14px; font-weight: 600; display: flex; 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; }
.lis-search-wrapper { position: relative; width: 100%; max-width: 320px; }
.lis-search-wrapper i { position: absolute; left: 14px; top: 12px; color: #94a3b8; }
.lis-search-wrapper input { padding-left: 38px; width: 100%; border: 1px solid #cbd5e1; border-radius: 8px; padding-top: 10px; padding-bottom: 10px; font-size: 13px; outline: none; background: #f8fafc; transition: 0.2s; }
</style>

<div class="lis-module">
    <div class="lis-header-area">
        <div class="lis-page-title"><i class="fa-solid fa-link"></i> LIS Setup: Map Parameters & Samples</div>
    </div>

    <?php if ($msg): ?>
        <div class="lis-alert lis-alert-success"><i class="fa-solid fa-check-circle"></i> <?php echo htmlspecialchars($msg); ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="lis-alert lis-alert-error"><i class="fa-solid fa-triangle-exclamation"></i> <?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <div class="lis-split-layout">
        
        <div class="lis-panel lis-panel-left">
            <div class="lis-panel-title" style="color:#831843; border-color:#fbcfe8;"><i class="fa-solid fa-plug"></i> Append Configuration to Test</div>
            
            <form method="POST" action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']); ?>">
                <input type="hidden" name="map_test_recipe" value="1">
                
                <div class="lis-form-col">
                    <label>1. Select Doctor's Order (Lab Test) <span style="color:#dc2626;">*</span></label>
                    <select name="service_id" id="lis_service_id_select" class="lis-input-control" required>
                        <option value="">-- Search & Choose Test --</option>
                        <?php foreach($services_by_dept as $deptName => $services): ?>
                            <optgroup label="<?php echo htmlspecialchars($deptName); ?>">
                                <?php foreach($services as $s): ?>
                                    <option value="<?php echo $s['id']; ?>"><?php echo htmlspecialchars($s['service_name']); ?></option>
                                <?php endforeach; ?>
                            </optgroup>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="lis-form-col">
                    <label>2. Add Required Specimen / Samples</label>
                    <div class="lis-checkbox-grid">
                        <?php foreach($samples as $samp): ?>
                            <label class="lis-chk-label">
                                <input type="checkbox" name="sample_ids[]" class="lis-chk-input lis-chk-sample" value="<?php echo $samp['id']; ?>">
                                <?php echo htmlspecialchars($samp['sample_name']); ?>
                                <span class="lis-param-meta" style="background:#dcfce7; color:#166534;"><?php echo htmlspecialchars($samp['container_type']); ?></span>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="lis-form-col">
                    <label>3. Add Lab Result Parameters</label>
                    <div class="lis-checkbox-grid">
                        <?php foreach($parameters as $p): ?>
                            <label class="lis-chk-label">
                                <input type="checkbox" name="parameter_ids[]" class="lis-chk-input lis-chk-param" value="<?php echo $p['id']; ?>">
                                <?php echo htmlspecialchars($p['parameter_name']); ?>
                                <span class="lis-param-meta"><?php echo htmlspecialchars($p['result_type']); ?></span>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>

                <button type="submit" class="lis-btn-primary" onclick="this.innerHTML='<i class=\'fa-solid fa-spinner fa-spin\'></i> Saving...';"><i class="fa-solid fa-link"></i> Add to Test Recipe</button>
            </form>
        </div>

        <div class="lis-panel lis-panel-right">
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 20px; border-bottom: 1px solid #e2e8f0; padding-bottom: 16px; flex-wrap:wrap; gap: 15px;">
                <div class="lis-panel-title" style="border:none; padding:0; margin:0;"><i class="fa-solid fa-network-wired"></i> Configured Test Panels Directory</div>
                <div class="lis-search-wrapper">
                    <i class="fa-solid fa-search"></i>
                    <input type="text" id="lisMapTestSearch" placeholder="Search lab tests (e.g. FBC)...">
                </div>
            </div>
            
            <table class="lis-table" id="lisMappingTable">
                <thead>
                    <tr>
                        <th width="30%">Billable Lab Test</th>
                        <th width="25%">Required Samples</th>
                        <th width="30%">Measurement Parameters</th>
                        <th width="15%" style="text-align:right;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(!empty($mapped_tests)): ?>
                        <?php foreach($mapped_tests as $mt): ?>
                        <tr class="lis-mapped-row">
                            <td>
                                <strong style="color:#1e293b; font-size:14px; display:block; margin-bottom:4px;"><?php echo htmlspecialchars($mt['service_name']); ?></strong>
                                <span style="font-size:11px; color:#64748b; font-weight:600;"><i class="fa-solid fa-layer-group"></i> <?php echo htmlspecialchars($mt['department_name'] ?: 'Uncategorized'); ?></span>
                            </td>
                            <td>
                                <?php if($mt['sample_count'] > 0): ?>
                                    <span style="color:#16a34a; font-weight:700; font-size:11px; display:block;"><i class="fa-solid fa-vial"></i> <?php echo $mt['sample_count']; ?> Sample(s)</span>
                                    <div style="color:#475569; font-size:12px; margin-top:4px;"><?php echo htmlspecialchars($mt['mapped_samples']); ?></div>
                                <?php else: ?>
                                    <span style="color:#dc2626; font-size:11px; font-weight:600;"><i class="fa-solid fa-triangle-exclamation"></i> No Sample</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if($mt['param_count'] > 0): ?>
                                    <span style="color:#0284c7; font-weight:700; font-size:11px; display:block;"><i class="fa-solid fa-microscope"></i> <?php echo $mt['param_count']; ?> Parameter(s)</span>
                                    <div style="color:#475569; font-size:12px; margin-top:4px; line-height:1.5;"><?php echo htmlspecialchars($mt['mapped_params']); ?></div>
                                <?php else: ?>
                                    <span style="color:#dc2626; font-size:11px; font-weight:600;"><i class="fa-solid fa-triangle-exclamation"></i> No Params</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="action-group">
                                    <a href="laboratory/viewTestMapping.php?service_id=<?php echo $mt['service_id']; ?>" class="btn-icon b-view"><i class="fa-solid fa-eye"></i></a>
                                    <a href="laboratory/updateTestMapping.php?service_id=<?php echo $mt['service_id']; ?>" class="btn-icon b-edit"><i class="fa-solid fa-pen"></i></a>
                                    
                                    <form method="POST" action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']); ?>" style="display:inline;">
                                        <input type="hidden" name="clear_service_id" value="<?php echo $mt['service_id']; ?>">
                                        <button type="submit" class="btn-icon b-delete" onclick="return confirm('WARNING: Are you sure you want to completely unlink all samples and parameters from this test?');"><i class="fa-solid fa-trash"></i></button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="4" style="text-align:center; padding:40px; color:#94a3b8;">No tests configured.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
const lisExistingMappings = <?php echo json_encode($js_mappings); ?>;
const serviceSelectEl = document.getElementById('lis_service_id_select');

if(serviceSelectEl) {
    serviceSelectEl.addEventListener('change', function() {
        const serviceId = this.value;
        const mappedData = lisExistingMappings[serviceId] || { params: [], samples: [] };
        
        document.querySelectorAll('.lis-chk-sample').forEach(box => {
            if(mappedData.samples.includes(box.value)) {
                box.closest('.lis-chk-label').style.display = 'none'; 
                box.checked = false; 
            } else { box.closest('.lis-chk-label').style.display = 'flex'; }
        });
        
        document.querySelectorAll('.lis-chk-param').forEach(box => {
            if(mappedData.params.includes(box.value)) {
                box.closest('.lis-chk-label').style.display = 'none';
                box.checked = false;
            } else { box.closest('.lis-chk-label').style.display = 'flex'; }
        });
    });
}

const searchEl = document.getElementById('lisMapTestSearch');
if(searchEl) {
    searchEl.addEventListener('input', function(e) {
        let filter = e.target.value.toLowerCase();
        document.querySelectorAll('.lis-mapped-row').forEach(row => {
            let textValue = row.getElementsByTagName('td')[0].innerText;
            row.style.display = (textValue.toLowerCase().indexOf(filter) > -1) ? "" : "none";
        });
    });
}
</script>