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

// Adjust path based on your folder structure
require_once __DIR__ . '/../../../dripend/includes/db.php';

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

// ==============================================================================
// 1. NATIVE FORM SUBMISSION: MAP TESTS TO LAB BENCHES
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['map_sub_dept'])) {
    $sub_dept_id = (int)$_POST['sub_dept_id'];
    $service_ids = $_POST['service_ids'] ?? [];

    if ($sub_dept_id === 0) {
        $error = "Please select a valid Lab Sub-Department.";
    } else {
        $conn->begin_transaction();
        try {
            // STEP A: Unlink all tests currently assigned to THIS selected sub-department.
            // This ensures if a user unchecks a box, it is removed cleanly.
            $stmtClear = $conn->prepare("UPDATE service_catalog SET lab_sub_dept_id = NULL WHERE lab_sub_dept_id = ?");
            $stmtClear->bind_param("i", $sub_dept_id);
            $stmtClear->execute();
            $stmtClear->close();

            // STEP B: Assign the newly checked tests to this sub-department
            if (!empty($service_ids)) {
                $placeholders = implode(',', array_fill(0, count($service_ids), '?'));
                $stmtUpdate = $conn->prepare("UPDATE service_catalog SET lab_sub_dept_id = ? WHERE id IN ($placeholders)");
                
                // Dynamically build the bind_param types ('i' for sub_dept_id + 'i' for each service_id)
                $types = 'i' . str_repeat('i', count($service_ids));
                $params = array_merge([$sub_dept_id], $service_ids);
                
                $stmtUpdate->bind_param($types, ...$params);
                $stmtUpdate->execute();
                $stmtUpdate->close();
            }
            
            $conn->commit();
            $msg = "Bench allocations successfully saved to the service catalog.";
        } catch (Exception $e) {
            $conn->rollback();
            $error = "Failed to update sub-department configuration: " . $e->getMessage();
        }
    }
}

// Handle clearing an entire sub-department's mappings via Action Button
if (isset($_POST['clear_sub_dept_id'])) {
    $sdid = (int)$_POST['clear_sub_dept_id'];
    $conn->begin_transaction();
    try {
        $conn->query("UPDATE service_catalog SET lab_sub_dept_id = NULL WHERE lab_sub_dept_id = $sdid");
        $conn->commit();
        $msg = "All tests successfully unlinked from the selected bench.";
    } catch (Exception $e) {
        $conn->rollback();
        $error = "Failed to clear sub-department mapping: " . $e->getMessage();
    }
}

// ==============================================================================
// 2. DYNAMIC DATABASE FETCHING
// ==============================================================================

// Fetch Active Lab Sub-Departments (Benches)
$sub_departments = [];
$resSD = $conn->query("SELECT id, sub_dept_name FROM lab_sub_departments WHERE is_active = 1 ORDER BY sub_dept_name ASC");
if ($resSD) while($row = $resSD->fetch_assoc()) $sub_departments[] = $row;

// Fetch Lab Services (Filtering by the native Department ID 8 which is Laboratory)
$services = [];
$qServices = "
    SELECT 
        sc.id, 
        sc.service_name, 
        sc.lab_sub_dept_id AS current_bench_id, 
        lsd.sub_dept_name AS current_bench
    FROM service_catalog sc
    LEFT JOIN lab_sub_departments lsd ON sc.lab_sub_dept_id = lsd.id
    WHERE sc.is_active = 1 
    AND sc.department_id = 8
    ORDER BY sc.service_name ASC
";
$resS = $conn->query($qServices);
if ($resS) while($row = $resS->fetch_assoc()) $services[] = $row;

// Fetch Directory Summary of Mapped Tests
$mapped_directory = [];
$qDir = "
    SELECT 
        lsd.id AS sub_dept_id,
        lsd.sub_dept_name,
        COUNT(sc.id) AS test_count,
        GROUP_CONCAT(sc.service_name ORDER BY sc.service_name ASC SEPARATOR ' • ') AS mapped_tests
    FROM lab_sub_departments lsd
    LEFT JOIN service_catalog sc ON lsd.id = sc.lab_sub_dept_id
    WHERE lsd.is_active = 1
    GROUP BY lsd.id
    ORDER BY lsd.sub_dept_name ASC
";
$resDir = $conn->query($qDir);
if ($resDir) while($row = $resDir->fetch_assoc()) $mapped_directory[] = $row;

// Build JSON Array for JavaScript Availability Logic
$js_sub_mappings = [];
foreach ($services as $s) {
    if (!empty($s['current_bench_id'])) {
        $js_sub_mappings[$s['id']] = $s['current_bench_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: #dc2626; }

.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; cursor:pointer; }
.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); }

.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: 360px; }
.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: #dc2626; box-shadow: 0 0 0 3px #fee2e2; background: #fff; }

.lis-checkbox-grid { display: grid; grid-template-columns: 1fr; gap: 8px; max-height: 400px; 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; position: relative;}
.lis-chk-label:hover { background: #e2e8f0; }
.lis-chk-input { width: 16px; height: 16px; accent-color: #dc2626; 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: #dc2626; 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: #991b1b; transform: translateY(-1px); box-shadow: 0 4px 6px rgba(220, 38, 38, 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;}
.lis-table tr:hover td { background: #f8fafc; }

.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-delete { background: #fee2e2; color: #dc2626; border-color: #fecaca; }
.btn-icon:hover { filter: brightness(0.95); transform: translateY(-1px); }

.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; }
.lis-search-wrapper input:focus { border-color: #dc2626; background: #fff; box-shadow: 0 0 0 3px #fee2e2; }

/* Styles for UNAVAILABLE / LOCKED mapped items */
.lis-locked-item { opacity: 0.45; pointer-events: none; background: #f1f5f9; border: 1px dashed #cbd5e1; }
.lis-locked-icon { display: none; margin-left: 6px; color: #94a3b8; font-size: 11px; }
.lis-locked-item .lis-locked-icon { display: inline-block; }
</style>

<div class="lis-module">
    <div class="lis-header-area">
        <div class="lis-page-title"><i class="fa-solid fa-sitemap"></i> LIS Setup: Map Lab Sub-Departments (Benches)</div>
    </div>

    <div class="lis-nav">
        <a onclick="loadContent('Test Parameters', '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 onclick="loadContent('Reference Ranges', 'laboratory/manageReferenceRanges.php', 'Laboratory', 'system_setup', null, true);" class="lis-card c-orange">
            <i class="fa-solid fa-chart-line"></i><div><strong>2. Ref. Ranges</strong><span>Define high/low limits.</span></div>
        </a>
        <a onclick="loadContent('Sample Types', '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 onclick="loadContent('Map Tests', '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 onclick="loadContent('Lab Sub-Departments', 'laboratory/mapLabDepartments.php', 'Laboratory', 'system_setup', null, true);" class="lis-card c-red" style="border-color:#dc2626; background:#fee2e2;">
            <i class="fa-solid fa-sitemap"></i><div><strong>5. Sub-Depts</strong><span>Categorize Lab Benches.</span></div>
        </a>
    </div>

    <?php if(!empty($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(!empty($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:#dc2626; border-color:#fecaca;"><i class="fa-solid fa-folder-plus"></i> Assign Tests to Bench</div>
            
            <form method="POST" action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']); ?>">
                <input type="hidden" name="map_sub_dept" value="1">
                
                <div class="lis-form-col">
                    <label>1. Select Lab Sub-Department <span style="color:#dc2626;">*</span></label>
                    <select name="sub_dept_id" id="lis_sub_dept_select" class="lis-input-control" required>
                        <option value="">-- Select Lab Bench --</option>
                        <?php foreach($sub_departments as $sd): ?>
                            <option value="<?php echo $sd['id']; ?>"><?php echo htmlspecialchars($sd['sub_dept_name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="lis-form-col">
                    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:4px;">
                        <label style="margin:0;">2. Select Lab Tests (Locks Assigned Tests)</label>
                        <input type="text" id="lisTestCheckboxSearch" placeholder="Filter tests..." style="font-size:11px; padding:4px 8px; border:1px solid #cbd5e1; border-radius:4px; outline:none; background:#fff; width:130px;">
                    </div>
                    
                    <div class="lis-checkbox-grid" id="lis_test_checkbox_grid">
                        <?php foreach($services as $s): ?>
                            <label class="lis-chk-label" data-search-name="<?php echo strtolower($s['service_name']); ?>">
                                <input type="checkbox" name="service_ids[]" class="lis-chk-input lis-service-checkbox" value="<?php echo $s['id']; ?>">
                                <span class="lis-test-display-name"><?php echo htmlspecialchars($s['service_name']); ?></span>
                                <i class="fa-solid fa-lock lis-locked-icon" title="Assigned to another bench"></i>
                                
                                <?php if(!empty($s['current_bench'])): ?>
                                    <span class="lis-param-meta lis-bench-badge" style="background:#e0f2fe; color:#0369a1;">
                                        <?php echo htmlspecialchars($s['current_bench']); ?>
                                    </span>
                                <?php else: ?>
                                    <span class="lis-param-meta lis-bench-badge" style="background:#f1f5f9; color:#64748b;">Unassigned</span>
                                <?php endif; ?>
                            </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 Assignments...';"><i class="fa-solid fa-sitemap"></i> Save Bench Allocation</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 Lab Benches Directory</div>
                
                <div class="lis-search-wrapper">
                    <i class="fa-solid fa-search"></i>
                    <input type="text" id="lisSubDeptSearch" placeholder="Search sub-departments or tests...">
                </div>
            </div>
            
            <table class="lis-table" id="lisSubDeptTable">
                <thead>
                    <tr>
                        <th width="30%">Lab Sub-Department (Bench)</th>
                        <th width="55%">Allocated Billable Tests</th>
                        <th width="15%" style="text-align:right;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(!empty($mapped_directory)): ?>
                        <?php foreach($mapped_directory as $row): ?>
                        <tr class="lis-subdept-row">
                            <td>
                                <strong style="color:#1e293b; font-size:14px; display:block; margin-bottom:2px;"><?php echo htmlspecialchars($row['sub_dept_name']); ?></strong>
                                <span style="color:#64748b; font-size:11px; font-weight:600;"><i class="fa-solid fa-flask"></i> <?php echo $row['test_count']; ?> Test(s) Assigned</span>
                            </td>
                            <td>
                                <?php if($row['test_count'] > 0): ?>
                                    <div style="color:#475569; font-size:12px; line-height:1.6; max-height: 80px; overflow-y:auto;"><?php echo htmlspecialchars($row['mapped_tests']); ?></div>
                                <?php else: ?>
                                    <span style="color:#dc2626; font-size:11px; font-weight:600;"><i class="fa-solid fa-triangle-exclamation"></i> No tests routed to this bench.</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="action-group">
                                    <form method="POST" action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']); ?>" style="display:inline;">
                                        <input type="hidden" name="clear_sub_dept_id" value="<?php echo $row['sub_dept_id']; ?>">
                                        <button type="submit" class="btn-icon b-delete" onclick="return confirm('Are you sure you want to completely unlink all mapped tests from the <?php echo htmlspecialchars($row['sub_dept_name']); ?> bench?');" title="Clear All Mappings from Bench"><i class="fa-solid fa-trash"></i></button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="3" style="text-align:center; padding:60px 20px; color:#94a3b8;">
                                <i class="fa-solid fa-sitemap" style="font-size:40px; margin-bottom:15px; color:#cbd5e1;"></i><br>
                                <span style="font-size:14px; font-weight:500;">No lab sub-departments defined or configured.</span>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

    </div>
</div>

<script>
// 1. INJECT DB MAPPING DICTIONARY INTO JAVASCRIPT
const lisSubDeptMappings = <?php echo json_encode($js_sub_mappings); ?>;

// 2. DYNAMIC WORKSTATION SYNC TO LOCK UNAVAILABLE ITEMS
const subDeptSelect = document.getElementById('lis_sub_dept_select');
if (subDeptSelect) {
    subDeptSelect.addEventListener('change', function() {
        const selectedId = parseInt(this.value) || 0;
        const checkBoxes = document.querySelectorAll('.lis-service-checkbox');
        
        checkBoxes.forEach(box => {
            const serviceId = box.value;
            const currentMappedBenchId = parseInt(lisSubDeptMappings[serviceId]) || 0;
            const labelEl = box.closest('.lis-chk-label');
            const badgeEl = labelEl.querySelector('.lis-bench-badge');

            // Hard Reset to Default Open State
            labelEl.classList.remove('lis-locked-item');
            labelEl.style.background = "";
            box.disabled = false;
            
            if (badgeEl) {
                badgeEl.style.background = "#f1f5f9";
                badgeEl.style.color = "#64748b";
            }

            // Apply Locks based on Dropdown Selection
            if (selectedId > 0) {
                if (currentMappedBenchId === selectedId) {
                    // Test belongs to currently selected bench -> Highlight & Check
                    box.checked = true;
                    labelEl.style.background = "#fee2e2";
                    if(badgeEl) { badgeEl.style.background = "#dc2626"; badgeEl.style.color = "#fff"; }
                } else if (currentMappedBenchId > 0) {
                    // Test belongs to a DIFFERENT bench -> UNAVAILABLE & LOCKED
                    box.checked = false;
                    box.disabled = true; // Security Lock
                    labelEl.classList.add('lis-locked-item'); // UX Feedback
                    if(badgeEl) { badgeEl.style.background = "#e2e8f0"; badgeEl.style.color = "#475569"; }
                } else {
                    // Test is completely unassigned -> Available for selection
                    box.checked = false;
                }
            } else {
                // No dropdown selected -> reset form visualization
                box.checked = false;
                if (currentMappedBenchId > 0 && badgeEl) {
                    badgeEl.style.background = "#e0f2fe";
                    badgeEl.style.color = "#0369a1";
                }
            }
        });
    });
}

// 3. FAST CHECKBOX LIVE SEARCH FILTERING
const cbSearch = document.getElementById('lisTestCheckboxSearch');
if (cbSearch) {
    cbSearch.addEventListener('input', function(e) {
        const query = e.target.value.toLowerCase().trim();
        const labels = document.querySelectorAll('#lis_test_checkbox_grid .lis-chk-label');
        
        labels.forEach(label => {
            const searchName = label.getAttribute('data-search-name') || '';
            if (searchName.includes(query)) {
                label.style.display = "flex";
            } else {
                label.style.display = "none";
            }
        });
    });
}

// 4. LIGHTNING DIRECTORY LIVE FILTERING
const searchEl = document.getElementById('lisSubDeptSearch');
if (searchEl) {
    searchEl.addEventListener('input', function(e) {
        const filter = e.target.value.toLowerCase().trim();
        const rows = document.querySelectorAll('.lis-subdept-row');

        rows.forEach(row => {
            const textContent = row.textContent || row.innerText;
            if (textContent.toLowerCase().indexOf(filter) > -1) {
                row.style.display = "";
            } else {
                row.style.display = "none";
            }
        });
    });
}
</script>