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

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

// Handle Quick Status Toggle (Activate/Deactivate)
if (isset($_GET['toggle_id']) && isset($_GET['current_status'])) {
    $t_id = (int)$_GET['toggle_id'];
    $new_status = ($_GET['current_status'] == 1) ? 0 : 1;
    $stmt = $conn->prepare("UPDATE lab_parameters SET is_active = ? WHERE id = ?");
    $stmt->bind_param("ii", $new_status, $t_id);
    $stmt->execute();
    header("Location: ../../views/system_setup/laboratory/manageLabParameters.php?msg=status_updated");
    exit;
}

// Handle Quick Delete
if (isset($_GET['delete_id'])) {
    $d_id = (int)$_GET['delete_id'];
    $stmt = $conn->prepare("DELETE FROM lab_parameters WHERE id = ?");
    $stmt->bind_param("i", $d_id);
    $stmt->execute();
    header("Location: ../../views/system_setup/laboratory/manageLabParameters.php?msg=deleted");
    exit;
}

// Fetch all parameters with a count of how many reference ranges they have attached
$query = "
    SELECT 
        p.*, 
        (SELECT COUNT(*) FROM lab_reference_ranges r WHERE r.parameter_id = p.id) AS range_count,
        (SELECT COUNT(*) FROM lab_test_parameter_mapping m WHERE m.parameter_id = p.id) AS mapped_tests
    FROM lab_parameters p
    ORDER BY p.parameter_name ASC
";
$res = $conn->query($query);
?>

<style>
/* Scoped styles specifically for the LIS Module to prevent bleeding into the master dashboard */
.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: #3b82f6; }

/* Action Button */
.btn-create { 
    background: #eff6ff; 
    color: #1d4ed8; 
    padding: 10px 20px; 
    border-radius: 8px; 
    font-weight: 600; 
    text-decoration: none; 
    display: inline-flex; 
    align-items: center; 
    gap: 8px; 
    border: 1px solid #bfdbfe;
    transition: 0.2s;
    font-size: 14px;
}
.btn-create:hover { background: #1d4ed8; color: #fff; box-shadow: 0 4px 6px rgba(29, 78, 216, 0.2); }

/* Grid Layout for 5 Cards - Fixes the stretching issue */
.lis-nav { 
    display: grid; 
    grid-template-columns: repeat(5, 1fr); 
    gap: 16px; 
    margin-bottom: 32px; 
}

/* Responsive collapse for smaller screens */
@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-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); }

/* Table Styles */
.table-container { 
    background: #fff; 
    border-radius: 10px; 
    border: 1px solid #e2e8f0; 
    overflow-x: auto; 
}
.lis-table { width: 100%; border-collapse: collapse; text-align: left; font-size: 13px; }
.lis-table th { padding: 16px; 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: 16px; border-bottom: 1px solid #f1f5f9; vertical-align: middle; color: #334155; }
.lis-table tr:last-child td { border-bottom: none; }
.lis-table tr:hover td { background: #f8fafc; }

/* Badges & Action Buttons */
.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; }
.bg-gray { background: #f1f5f9; color: #475569; border: 1px solid #cbd5e1; }

.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-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); }
</style>

<div class="lis-module">
    <!-- Header -->
    <div class="lis-header-area">
        <div class="lis-page-title">
            <i class="fa-solid fa-microscope"></i> LIS Setup: Lab Parameters
        </div>
        <!-- data-title added for the SPA Interceptor -->
        <a href="../../views/system_setup/laboratory/addLabParameter.php" data-title="Add New Parameter" class="btn-create">
            <i class="fa-solid fa-plus"></i> Create New Parameter
        </a>
    </div>

    <!-- Navigation Matrix (CSS Grid handles the 5 columns cleanly) -->
    <div class="lis-nav">
        <a href="../../views/system_setup/laboratory/manageLabParameters.php" data-title="Test Parameters" class="lis-card c-blue" style="border-color:#1e3a8a; background:#e0f2fe;">
            <i class="fa-solid fa-vials"></i>
            <div>
                <strong>1. Base Params</strong>
                <span>Manage names & units.</span>
            </div>
        </a>
        <a href="../../views/system_setup/laboratory/manageReferenceRanges.php" data-title="Reference Ranges" 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 href="../../views/system_setup/laboratory/manageSamples.php" data-title="Sample Types" 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="../../views/system_setup/laboratory/mapLabParameters.php" data-title="Map Tests" 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="../../views/system_setup/laboratory/mapLabDepartments.php" data-title="Lab Sub-Departments" 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>

    <!-- Alert Messages -->
    <?php if(isset($_GET['msg']) && $_GET['msg'] == 'status_updated'): ?>
        <div style="background:#dcfce7; color:#166534; padding:12px 16px; border-radius:8px; margin-bottom:20px; border:1px solid #bbf7d0; font-size: 14px;">
            <i class="fa-solid fa-circle-check"></i> Parameter status updated successfully.
        </div>
    <?php endif; ?>

    <!-- Data Table -->
    <div class="table-container">
        <table class="lis-table">
            <thead>
                <tr>
                    <th width="5%">ID</th>
                    <th width="25%">Parameter Name</th>
                    <th width="15%">Unit of Measure</th>
                    <th width="30%">LIS Network Status</th>
                    <th width="10%">Status</th>
                    <th width="15%" style="text-align:right;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if($res && $res->num_rows > 0): ?>
                    <?php while($row = $res->fetch_assoc()): ?>
                    <tr>
                        <td style="color:#94a3b8; font-weight:600;">#<?php echo $row['id']; ?></td>
                        <td>
                            <strong style="font-size:14px;"><?php echo htmlspecialchars($row['parameter_name']); ?></strong>
                            <div style="color:#64748b; font-size:11px; margin-top:4px;"><?php echo htmlspecialchars($row['description'] ?? ''); ?></div>
                        </td>
                        <td><span class="lis-badge bg-gray"><?php echo htmlspecialchars($row['unit_of_measure'] ?? 'N/A'); ?></span></td>
                        <td>
                            <div style="display:flex; gap:12px; font-size:12px; font-weight:500;">
                                <?php if($row['mapped_tests'] > 0): ?>
                                    <span style="color:#16a34a;"><i class="fa-solid fa-link"></i> Mapped (<?php echo $row['mapped_tests']; ?>)</span>
                                <?php else: ?>
                                    <span style="color:#dc2626;"><i class="fa-solid fa-link-slash"></i> Not Mapped</span>
                                <?php endif; ?>

                                <?php if($row['range_count'] > 0): ?>
                                    <span style="color:#16a34a;"><i class="fa-solid fa-chart-bar"></i> Ranges (<?php echo $row['range_count']; ?>)</span>
                                <?php else: ?>
                                    <span style="color:#dc2626;"><i class="fa-solid fa-triangle-exclamation"></i> No Ranges</span>
                                <?php endif; ?>
                            </div>
                        </td>
                        <td>
                            <?php if($row['is_active'] == 1): ?>
                                <span class="lis-badge bg-green">Active</span>
                            <?php else: ?>
                                <span class="lis-badge bg-red">Inactive</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="action-group">
                                <a href="viewLabParameter.php?id=<?php echo $row['id']; ?>" data-title="View Parameter" class="btn-icon b-view" title="View"><i class="fa-solid fa-eye"></i></a>
                                
                                <a href="../../views/system_setup/laboratory/updateLabParameter.php?id=<?php echo $row['id']; ?>" data-title="Edit Parameter" class="btn-icon b-edit" title="Edit"><i class="fa-solid fa-pen"></i></a>
                                
                                <a href="?toggle_id=<?php echo $row['id']; ?>&current_status=<?php echo $row['is_active']; ?>" class="btn-icon b-toggle" title="<?php echo $row['is_active'] ? 'Deactivate' : 'Activate'; ?>">
                                    <i class="fa-solid <?php echo $row['is_active'] ? 'fa-ban' : 'fa-check'; ?>"></i>
                                </a>
                                
                                <a href="?delete_id=<?php echo $row['id']; ?>" class="btn-icon b-delete" onclick="return confirm('WARNING: Are you sure you want to delete this parameter? This will delete all associated reference ranges and mappings!');" title="Delete">
                                    <i class="fa-solid fa-trash"></i>
                                </a>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="6" style="text-align:center; padding:50px; color:#94a3b8;">
                            <i class="fa-solid fa-flask-vial" style="font-size:40px; margin-bottom:15px; color:#e2e8f0;"></i><br>
                            <span style="font-size: 14px;">No laboratory parameters found. Click "Create New Parameter" to begin.</span>
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>