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

session_start();
include('includes/db.php');
include('includes/header.php');

/* ------------ Auto Logout ------------ */
$timeout_duration = 1800;
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > $timeout_duration) {
    session_unset();
    session_destroy();
    header("Location: login.php?timeout=1");
    exit;
}
$_SESSION['LAST_ACTIVITY'] = time();

/* ------------ Auth ------------ */
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

/* ------------ Facility Check ------------ */
$facility_id = $_SESSION['facility_id'] ?? null;
if (!$facility_id) {
    $_SESSION['flash'] = ["message" => "No facility assigned to your account.", "color" => "#dc3545"];
    header("Location: dashboard.php");
    exit;
}

/* ================= HELPER ================= */
function calculate_age($dob) {
    if (!$dob || $dob === '0000-00-00') {
        return '';
    }

    try {
        $dobDate = new DateTime($dob);
        $now     = new DateTime();
        $diff    = $now->diff($dobDate);

        // 1 year or more → years only
        if ($diff->y >= 1) {
            return $diff->y . ' Year' . ($diff->y > 1 ? 's' : '');
        }

        // Less than 1 year but at least 1 month → months only
        if ($diff->m >= 1) {
            return $diff->m . ' Month' . ($diff->m > 1 ? 's' : '');
        }

        // Less than 1 month → days
        return $diff->d . ' Day' . ($diff->d > 1 ? 's' : '');

    } catch (Exception $e) {
        return '';
    }
}


/* ------------ Date Filters ------------ */
$from_date = $_GET['from_date'] ?? '';
$to_date   = $_GET['to_date'] ?? '';

$where = ["pt.facility_id = :facility_id"];
$params = [':facility_id' => $facility_id];

if (!empty($from_date) && !empty($to_date)) {
    $where[] = "DATE(lo.created_at) BETWEEN :from_date AND :to_date";
    $params[':from_date'] = $from_date;
    $params[':to_date']   = $to_date;
}

$whereSQL = $where ? "WHERE " . implode(" AND ", $where) : "";

/* ------------ FETCH LAB ORDERS + AGE + INSURANCE ------------ */
$sql = "
    SELECT 
        lo.*,
        p.name AS test_name,
        pt.first_name,
        pt.middle_name,
        pt.last_name,
        pt.d_o_b,
        u.username AS requested_by_name,
        vt.visit_date,
        TIMESTAMPDIFF(YEAR, pt.d_o_b, CURDATE()) AS patient_age,
        ip.name AS insurance_name,
        v.insurance_card_number
    FROM lab_orders lo
    LEFT JOIN products p            ON lo.product_id = p.id
    LEFT JOIN patients pt           ON lo.patient_id = pt.id
    LEFT JOIN users u               ON lo.requested_by = u.id
    LEFT JOIN visit_tickets vt      ON lo.visit_ticket_id = vt.id
    LEFT JOIN visits v              ON vt.visit_id = v.id
    LEFT JOIN insurance_partners ip ON v.insurance_id = ip.id
    $whereSQL
    ORDER BY lo.created_at DESC
";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$lab_orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>


<nav class="header-navbar navbar navbar-with-menu navbar-fixed-top navbar-semi-dark navbar-shadow">
    <?php include('includes/navbar.php'); ?>
</nav>

<div class="main-menu menu-fixed menu-dark menu-accordion menu-shadow">
    <?php include('includes/sidebar.php'); ?>
</div>

<div class="app-content content container-fluid">
<div class="content-wrapper">

<h3 class="text-center mb-2">All Laboratory Orders</h3>
<hr>

<!-- 🔍 DATE FILTER -->
<form method="GET" class="row mb-2">
    <div class="col-md-3">
        <label>From Date</label>
        <input type="date" name="from_date" class="form-control"
               value="<?= htmlspecialchars($from_date) ?>">
    </div>
    <div class="col-md-3">
        <label>To Date</label>
        <input type="date" name="to_date" class="form-control"
               value="<?= htmlspecialchars($to_date) ?>">
    </div>
    <div class="col-md-3 align-self-end">
        <button class="btn btn-primary">Filter</button>
        <a href="lab_orders_list.php" class="btn btn-secondary">Reset</a>
    </div>
</form>

<div class="card">
<div class="card-body">

<div class="table-responsive">
<table id="labOrdersTable" class="table table-bordered table-striped table-sm" id="Table">
<thead class="thead-dark">
<tr>
    <th>#</th>
    <th>Patient</th>
    <th>Age</th>
    <th>Insurance & Card No</th>
    <th>Lab Test</th>
    <th>Requested By</th>
    <th>Visit Date</th>
    <th>Created At</th>
</tr>
</thead>
<tbody>
<?php foreach ($lab_orders as $i => $o): ?>
<tr>
    <td><?= $i + 1 ?></td>

    <td>
        <?= htmlspecialchars(trim(
            $o['first_name'].' '.($o['middle_name'] ?: '').' '.$o['last_name']
        )) ?>
    </td>

    <td><?= calculate_age($o['d_o_b']) ?></td>

    <td>
        <div><?= htmlspecialchars($o['insurance_name'] ?? 'Cash') ?></div>
        <div>
            <small class="text">
            <?= htmlspecialchars($o['insurance_card_number'] ?? '-') ?>
            </small>
        </div>
    </td>

    <td>
        <div><?= htmlspecialchars($o['test_name']) ?></div>
        <div>
        <div>
            <?php if ($o['status'] === 'completed'): ?>
                <span class="btn btn-success btn-sm ">Completed</span>
            <?php else: ?>
                <span class="btn btn-warning btn-sm text-dark">Pending</span>
            <?php endif; ?>
        </div>
    </td>

    <td><?= htmlspecialchars($o['requested_by_name']) ?></td>

    <td><?= htmlspecialchars($o['visit_date']) ?></td>

    <td><?= htmlspecialchars($o['created_at']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>

</div>
</div>

</div>
</div>

<?php include('includes/footer.php'); ?>

<!-- DataTables -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.dataTables.min.css">

<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>

<script>
$(document).ready(function () {
    $('#labOrdersTable').DataTable({
        dom: 'Bfrtip',
        buttons: ['excel','csv','pdf','print'],
        pageLength: 10,
        order: [[7, 'desc']], // Created At column
        responsive: true
    });
});
</script>


<style>
.table-sm td, .table-sm th { padding: .35rem; }
</style>
