<?php
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';

// ==============================================================================
// 1. QUICK ACTIONS: TOGGLE STATUS & DELETE
// ==============================================================================
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_sample_types SET is_active = ? WHERE id = ?");
    $stmt->bind_param("ii", $new_status, $t_id);
    $stmt->execute();
    header("Location: manageSamples.php?msg=status_updated");
    exit;
}

if (isset($_GET['delete_id'])) {
    $d_id = (int)$_GET['delete_id'];
    $stmt = $conn->prepare("DELETE FROM lab_sample_types WHERE id = ?");
    $stmt->bind_param("i", $d_id);
    $stmt->execute();
    header("Location: manageSamples.php?msg=deleted");
    exit;
}

// ==============================================================================
// 2. FETCH ALL SAMPLES & NETWORK INTELLIGENCE
// ==============================================================================
// We dynamically count how many doctor's tests require this specific sample
$query = "
    SELECT 
        s.*, 
        (SELECT COUNT(*) FROM lab_test_samples m WHERE m.sample_id = s.id) AS mapped_tests
    FROM lab_sample_types s
    ORDER BY s.sample_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: #16a34a; }

/* Action Button */
.lis-btn-create { background: #f0fdf4; color: #166534; padding: 10px 20px; border-radius: 8px; font-weight: 600; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; border: 1px solid #bbf7d0; transition: 0.2s; font-size: 14px; }
.lis-btn-create:hover { background: #16a34a; color: #fff; box-shadow: 0 4px 6px rgba(22, 163, 74, 0.2); }

/* 5-Column Grid Navigation Matrix (Consistent across LIS Setup) */
.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-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); }

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

<div class="lis-module">
    <div class="lis-header-area">
        <div class="lis-page-title">
            <i class="fa-solid fa-vial-circle-check"></i> LIS Setup: Sample Dictionary
        </div>
        <a href="/rimax/application/views/system_setup/laboratory/addLabSample.php" data-title="Add New Sample" class="lis-btn-create">
            <i class="fa-solid fa-plus"></i> Add New Sample
        </a>
    </div>

    <div class="lis-nav">
        <a href="../../views/system_setup/laboratory/manageLabParameters.php" data-title="Test Parameters" 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="../../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" style="border-color:#166534; background:#dcfce7;">
            <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>

    <?php if(isset($_GET['msg'])): ?>
        <?php if($_GET['msg'] == 'status_updated'): ?>
            <div class="lis-alert lis-alert-success"><i class="fa-solid fa-circle-check"></i> Sample status updated successfully.</div>
        <?php elseif($_GET['msg'] == 'deleted'): ?>
            <div class="lis-alert lis-alert-error"><i class="fa-solid fa-trash-can"></i> Sample permanently removed.</div>
        <?php endif; ?>
    <?php endif; ?>

    <div class="table-container">
        <table class="lis-table">
            <thead>
                <tr>
                    <th width="5%">ID</th>
                    <th width="25%">Specimen Type</th>
                    <th width="25%">Required Container / Tube</th>
                    <th width="25%">LIS Network Status</th>
                    <th width="10%">Status</th>
                    <th width="10%" 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; color:#1e293b;"><?php echo htmlspecialchars($row['sample_name']); ?></strong>
                        </td>
                        <td>
                            <span style="background:#f1f5f9; padding:4px 10px; border-radius:6px; font-size:12px; font-weight:600; color:#334155; border:1px solid #cbd5e1; display:inline-flex; align-items:center; gap:6px;">
                                <i class="fa-solid fa-flask" style="color:#64748b;"></i> <?php echo htmlspecialchars($row['container_type'] ?? 'Standard Container'); ?>
                            </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> Required by <?php echo $row['mapped_tests']; ?> Test(s)</span>
                                <?php else: ?>
                                    <span style="color:#dc2626;"><i class="fa-solid fa-link-slash"></i> Not Mapped</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="../../views/system_setup/laboratory/updateSample.php?id=<?php echo $row['id']; ?>" data-title="Edit Specimen" class="btn-icon b-edit" title="Edit Specimen"><i class="fa-solid fa-pen"></i></a>
                                
                                <a href="../../views/system_setup/laboratory/mapLabParameters.php?sample_focus=<?php echo $row['id']; ?>" data-title="Map Tests" class="btn-icon b-view" title="Map this sample to a test"><i class="fa-solid fa-network-wired"></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 sample? Any tests that require this sample will lose their mapping!');" 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-vial-circle-check" style="font-size:40px; margin-bottom:15px; color:#e2e8f0;"></i><br>
                            <span style="font-size: 14px;">No specimen types found. Click "Add New Sample" to begin.</span>
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>