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

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

// ==============================================================================
// 1. SMART DATE RANGE FILTERING
// ==============================================================================
// Defaults to today if no dates are provided
$date_from_raw = $_GET['date_from'] ?? date('Y-m-d');
$date_to_raw = $_GET['date_to'] ?? date('Y-m-d');
$is_all_backlog = ($date_from_raw === 'ALL');

$date_from_sql = $conn->real_escape_string($date_from_raw . ' 00:00:00');
$date_to_sql = $conn->real_escape_string($date_to_raw . ' 23:59:59');

$pending_requests = [];

// ==============================================================================
// 2. FETCH INCOMING CLINICAL REQUESTS (Pending Status)
// ==============================================================================
$qPending = "
    SELECT 
        clr.id AS request_id, 
        clr.patient_no, 
        COALESCE(sc.service_name, clr.test_name) AS test_name, 
        clr.priority, 
        clr.request_date, 
        clr.notes,
        p.first_name, 
        p.last_name, 
        TIMESTAMPDIFF(YEAR, p.dob, CURDATE()) AS age,
        g.gender_name AS gender,
        CONCAT('Dr. ', COALESCE(s.first_name, 'Unknown'), ' ', COALESCE(s.last_name, '')) AS doctor
    FROM clinical_lab_requests clr
    JOIN patient p ON clr.patient_no = p.patient_no
    LEFT JOIN gender g ON p.gender_id = g.id
    LEFT JOIN service_catalog sc ON clr.service_id = sc.id
    LEFT JOIN staff s ON clr.requested_by = s.staff_id
    WHERE clr.status = 'Pending'
";

if (!$is_all_backlog) {
    $qPending .= " AND clr.request_date >= '$date_from_sql' AND clr.request_date <= '$date_to_sql'";
}

$qPending .= " ORDER BY clr.priority ASC, clr.request_date ASC";

$resPending = $conn->query($qPending);
if ($resPending) {
    while($row = $resPending->fetch_assoc()) {
        $pending_requests[] = $row;
    }
}

// Side Bar Details
$domain = 'https://dripdental.kqmucpub.com';
$iconPath = $domain . '/dripend/assets/icons/dashboard';
$current_page = basename($_SERVER['PHP_SELF']); 
$userName = isset($_SESSION['user_full_name']) ? $_SESSION['user_full_name'] : 'Dr. Admin';
$userRole = isset($_SESSION['user_role']) ? $_SESSION['user_role'] : 'Administrator';
$userInitial = strtoupper(substr($userName, 0, 1));
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laboratory Reception | Tier 1 LIS</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">

<style>
:root {
  --sidebar-width: 300px;
  --transition-speed: 0.35s;
  --bg-app: #f4f7f9;
  --bg-card: #ffffff;
  --brand-secondary: #2563eb;
  --success: #10b981;
  --danger: #ef4444;
  --warning: #f59e0b;
  --border-light: #e2e8f0;
  --text-main: #0f172a;
  --text-muted: #64748b;
  --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Inter', sans-serif; background: var(--bg-app); color: var(--text-main); -webkit-font-smoothing: antialiased; }

.main-content { margin-left: var(--sidebar-width); padding: 25px 30px; display: flex; flex-direction: column; min-height: 100vh; transition: margin-left var(--transition-speed); }
@media (max-width: 1024px) { .main-content { margin-left: 0; } }
.container { max-width: 1400px; margin: 0 auto; width: 100%; flex: 1; display: flex; flex-direction: column; }

/* Quick Navigation Modules */
.module-nav-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-bottom: 25px; }
.module-card { background: var(--bg-card); border: 1px solid var(--border-light); border-radius: 8px; padding: 18px 20px; display: flex; align-items: center; gap: 15px; text-decoration: none; box-shadow: var(--shadow-sm); transition: all 0.2s; }
.module-card:hover { transform: translateY(-3px); box-shadow: var(--shadow-md); border-color: var(--brand-secondary); }
.icon-box { width: 48px; height: 48px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 20px; flex-shrink:0; }
.module-card .info h3 { font-size: 15px; color: var(--text-main); margin-bottom: 2px; font-weight: 700;}
.module-card .info p { font-size: 12px; color: var(--text-muted); font-weight: 500;}

/* Filter Bar */
.filter-bar { display: flex; gap: 15px; background: var(--bg-card); padding: 15px 25px; border-radius: 8px; border: 1px solid var(--border-light); box-shadow: var(--shadow-sm); margin-bottom: 20px; align-items: flex-end; }
.filter-bar .form-group { flex: 1; }
.filter-bar label { display: block; font-size: 11px; font-weight: 700; color: var(--text-muted); margin-bottom: 6px; text-transform: uppercase; letter-spacing: 0.5px; }
.input-control { width: 100%; padding: 10px 12px; border: 1px solid var(--border-light); border-radius: 6px; font-size: 14px; font-weight: 600; outline: none; transition: 0.2s; background: #fff; }
.input-control:focus { border-color: var(--brand-secondary); box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1); }

/* Table Elements */
.card { background: var(--bg-card); border-radius: 8px; border: 1px solid var(--border-light); box-shadow: var(--shadow-sm); overflow: hidden; margin-bottom: 20px; }
.card-header { padding: 15px 20px; border-bottom: 1px solid var(--border-light); background: #f8fafc; display: flex; justify-content: space-between; align-items: center; }
.card-header h2 { font-size: 16px; font-weight: 700; color: var(--text-main); display: flex; align-items: center; gap: 8px;}

.table-wrapper { overflow-x: auto; width: 100%; }
table { width: 100%; border-collapse: collapse; text-align: left; }
th, td { padding: 15px 20px; border-bottom: 1px solid var(--border-light); vertical-align: middle; }
th { font-size: 12px; text-transform: uppercase; color: var(--text-muted); background: #ffffff; font-weight: 700; white-space: nowrap;}
tr:hover { background: #f8fafc; }
.custom-checkbox { width: 16px; height: 16px; cursor: pointer; accent-color: var(--brand-secondary); }

.badge { padding: 4px 10px; border-radius: 6px; font-size: 11px; font-weight: 700; text-transform: uppercase;}
.badge-routine { background: #e0f2fe; color: #0284c7; }
.badge-urgent { background: #fef08a; color: #b45309; }
.badge-stat { background: #fee2e2; color: #e11d48; }

.actions-bar { padding: 15px 20px; background: #f8fafc; border-top: 1px solid var(--border-light); display: flex; justify-content: flex-end; }
.btn { padding: 10px 20px; border-radius: 6px; font-size: 13px; font-weight: 600; cursor: pointer; transition: all 0.2s; border: none; display: inline-flex; align-items: center; gap: 8px; }
.btn-primary { background: var(--brand-secondary); color: #fff; }
.btn-primary:hover { background: #1d4ed8; }
.btn-outline { background: transparent; border: 1px solid var(--border-light); color: var(--text-main); }
.btn-outline:hover { background: #f1f5f9; }

#toast-container { position: fixed; top: 30px; right: 30px; z-index: 9999; display: flex; flex-direction: column; gap: 10px; }
.toast { background: #fff; border-left: 4px solid var(--brand-secondary); padding: 16px 20px; border-radius: 4px; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1); display: flex; align-items: center; gap: 12px; min-width: 300px; transform: translateX(120%); transition: transform 0.3s ease; }
.toast.show { transform: translateX(0); }
.toast.success { border-left-color: var(--success); }
.toast.error { border-left-color: var(--danger); }
.toast-icon { font-size: 20px; color: var(--brand-secondary);}

.enterprise-footer { text-align: center; font-size: 12px; color: var(--text-muted); font-weight: 500; padding: 20px 0;}
</style>
</head>
<body>

<?php include('../../dripend/statpages/sidebar.php'); ?>

<div class="main-content" id="mainContent">
  <div class="container">

    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
      <h1 style="font-size: 22px; color: var(--text-main); font-weight: 800;"><i class="fa-solid fa-laptop-medical" style="color: var(--brand-secondary); margin-right: 8px;"></i> Laboratory Command Center</h1>
    </div>

    <!-- Quick Navigation Modules -->
    <div class="module-nav-grid">
        <a href="collect_sample.php" class="module-card">
            <div class="icon-box" style="background: #dcfce7; color: #059669;"><i class="fa-solid fa-vial"></i></div>
            <div class="info">
                <h3>Sample Collection</h3>
                <p>Phlebotomy & Receptacles</p>
            </div>
        </a>
        <a href="add_lab_result.php" class="module-card">
            <div class="icon-box" style="background: #e0e7ff; color: #4f46e5;"><i class="fa-solid fa-microscope"></i></div>
            <div class="info">
                <h3>Result Entry</h3>
                <p>Bench Testing & Interfaces</p>
            </div>
        </a>
        <a href="verify_lab_results.php" class="module-card">
            <div class="icon-box" style="background: #fce7f3; color: #e11d48;"><i class="fa-solid fa-file-signature"></i></div>
            <div class="info">
                <h3>Pathologist Verification</h3>
                <p>Review & Digital Release</p>
            </div>
        </a>
    </div>

    <!-- Smart Date Filter -->
    <div class="filter-bar">
        <div class="form-group">
            <label>Request Date From</label>
            <input type="date" id="dateFrom" class="input-control" value="<?= $is_all_backlog ? '' : htmlspecialchars($date_from_raw) ?>">
        </div>
        <div class="form-group">
            <label>Request Date To</label>
            <input type="date" id="dateTo" class="input-control" value="<?= $is_all_backlog ? '' : htmlspecialchars($date_to_raw) ?>">
        </div>
        <div style="display: flex; gap: 10px;">
            <button class="btn btn-primary" onclick="applyDateFilter()"><i class="fa-solid fa-filter"></i> Apply Filter</button>
            <button class="btn btn-outline" onclick="viewAllBacklog()"><i class="fa-solid fa-layer-group"></i> View Entire Backlog</button>
        </div>
    </div>

    <!-- Incoming Requests Queue -->
    <div class="card">
        <div class="card-header">
            <h2><i class="fa-solid fa-inbox"></i> Pending Incoming Requests (Step 1: Reception)</h2>
            <span style="font-size: 13px; color: var(--text-muted); font-weight: 600;">Showing: <?= $is_all_backlog ? 'All Time' : htmlspecialchars(date('d-M-Y', strtotime($date_from_raw)) . ' to ' . date('d-M-Y', strtotime($date_to_raw))) ?></span>
        </div>
        <div class="table-wrapper">
            <table id="receptionTable">
                <thead>
                    <tr>
                        <th style="width: 5%; text-align: center;">
                            <input type="checkbox" id="masterCheck" class="custom-checkbox" onchange="toggleAll(this)">
                        </th>
                        <th>Request Date</th>
                        <th>Patient Details</th>
                        <th>Requested Test</th>
                        <th>Priority</th>
                        <th>Requesting Physician</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(empty($pending_requests)): ?>
                        <tr><td colspan="6" style="text-align: center; padding: 40px; color: var(--text-muted); font-weight: 500;">No pending laboratory requests found for the selected dates.</td></tr>
                    <?php else: ?>
                        <?php foreach($pending_requests as $req): ?>
                        <tr class="req-row">
                            <td style="text-align: center;">
                                <input type="checkbox" class="custom-checkbox row-check" value="<?= $req['request_id'] ?>" onchange="evaluateActionBtn()">
                            </td>
                            <td style="font-size: 13px; font-weight: 600; color: var(--text-main);">
                                <?= date('d-M-Y h:i A', strtotime($req['request_date'])) ?>
                            </td>
                            <td>
                                <div style="font-weight: 700; color: var(--text-main); font-size: 14px;"><?= htmlspecialchars($req['first_name'] . ' ' . $req['last_name']) ?></div>
                                <div style="font-size: 12px; color: var(--text-muted); margin-top: 2px;">
                                    <?= htmlspecialchars($req['patient_no']) ?> | <?= htmlspecialchars($req['age']) ?> Yrs | <?= htmlspecialchars($req['gender']) ?>
                                </div>
                            </td>
                            <td>
                                <div style="font-weight: 600; color: var(--brand-secondary); font-size: 13px;"><?= htmlspecialchars($req['test_name']) ?></div>
                                <?php if(!empty($req['notes'])): ?>
                                    <div style="font-size: 11px; color: var(--text-muted); font-style: italic; margin-top: 2px;"><i class="fa-solid fa-comment-medical"></i> <?= htmlspecialchars($req['notes']) ?></div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php 
                                    $badgeClass = 'badge-routine';
                                    if($req['priority'] == 'Urgent') $badgeClass = 'badge-urgent';
                                    if($req['priority'] == 'STAT') $badgeClass = 'badge-stat';
                                ?>
                                <span class="badge <?= $badgeClass ?>"><?= htmlspecialchars($req['priority']) ?></span>
                            </td>
                            <td style="font-size: 13px; font-weight: 600; color: var(--text-main);">
                                <?= htmlspecialchars($req['doctor']) ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <div class="actions-bar">
            <button class="btn btn-primary" id="btnAccept" onclick="acceptSelected()" disabled>
                <i class="fa-solid fa-check-double"></i> Accept Selected into Laboratory
            </button>
        </div>
    </div>

    <div class="enterprise-footer">
      Laboratory Management System v2.4.1 | Powered by Afritechs Gh Ltd
    </div>

  </div>
</div>

<div id="toast-container"></div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="../../assets/js/lab_reception.js"></script>

</body>
</html>