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

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

// ---------------- CSRF Token ----------------
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];
/* ================= Auto Logout ================= */
$timeout_duration = 43200;

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > $timeout_duration) {
    session_unset();
    session_destroy();
    header("Location: login.php?timeout=1");
    exit;
}
// ---------------- AUTH ----------------
if (!isset($_SESSION['facility_id'])) {
    $_SESSION['flash'] = ['message'=>'Session expired','color'=>'#dc3545'];
    header("Location: login.php");
    exit;
}
$facility_id = (int) $_SESSION['facility_id'];

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

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

        if ($diff->y >= 1) {
            return $diff->y . ' Year' . ($diff->y > 1 ? 's' : '');
        }

        if ($diff->m >= 1) {
            return $diff->m . ' Month' . ($diff->m > 1 ? 's' : '');
        }

        return $diff->d . ' Day' . ($diff->d > 1 ? 's' : '');

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

/* ================= FILTER INPUT ================= */
$from_date = $_GET['from_date'] ?? '';
$to_date   = $_GET['to_date'] ?? '';
$view_all  = isset($_GET['view_all']);

// ---------------- AUTO UPDATE STATUS ----------------
$pdo->prepare("
    UPDATE lab_orders 
    SET status = 'completed' 
    WHERE result_value IS NOT NULL 
      AND result_value != ''
      AND facility_id = ?
")->execute([$facility_id]);

/* ================= FETCH GROUPED LAB ORDERS ================= */
$where  = [];
$params = [$facility_id];

/*
 | DEFAULT = DAILY LAB ORDERS
 | No filters → TODAY only
 */
if (!$view_all && !$from_date && !$to_date) {
    $where[] = 'DATE(lo.created_at) = CURDATE()';
}

/* Date range filter */
if ($from_date && $to_date) {
    $where[] = 'DATE(lo.created_at) BETWEEN ? AND ?';
    $params[] = $from_date;
    $params[] = $to_date;
}

/* INSURANCE PATIENTS ONLY */
$where[] = 'v.insurance_id IS NOT NULL';

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

$stmt = $pdo->prepare("
    SELECT 
        vt.id AS visit_ticket_id,
        vt.visit_id AS main_visit_id,

        p.id AS patient_id,
        p.first_name, p.middle_name, p.last_name, p.file_id,
        p.d_o_b, p.gender,

        doc.username AS doctor_name,
        ip.name AS insurance_name,

        GROUP_CONCAT(pr.name ORDER BY lo.created_at DESC SEPARATOR ', ') AS lab_tests,

        MAX(lo.created_at) AS latest_order_date,
        MAX(lo.id) AS latest_order_id,

        COUNT(lo.id) AS total_orders,
        SUM(lo.status = 'completed') AS completed_count,
        SUM(lo.status = 'pending') AS pending_count

    FROM lab_orders lo
    JOIN patients p        ON p.id = lo.patient_id
    JOIN products pr       ON pr.id = lo.product_id
    JOIN visit_tickets vt  ON vt.id = lo.visit_ticket_id
    JOIN visits v          ON v.id = vt.visit_id
    LEFT JOIN users doc    ON doc.id = v.treated_by
    LEFT JOIN insurance_partners ip ON ip.id = v.insurance_id

    WHERE lo.facility_id = ?
    $whereSQL

    GROUP BY vt.id

    ORDER BY 
        MAX(lo.created_at) DESC,
        MAX(lo.id) DESC
");
$stmt->execute($params);
$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 data-scroll-to-active="true" 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">
<div class="col-xs-12">
<div class="card">

<div class="card-header d-flex justify-content-between align-items-center">
    <h4 class="card-title">Insurance Lab Orders</h4>
    <a href="all_patients.php" class="btn btn-outline-primary btn-lg">All Patients</a>
</div>

<div class="card-body collapse in">
<div class="card-block card-dashboard">

<!-- ================= FILTER BAR ================= -->
<form method="get" class="row mb-2">
    <div class="col-md-3">
        <input type="date" name="from_date" value="<?= htmlspecialchars($from_date) ?>" class="form-control">
    </div>
    <div class="col-md-3">
        <input type="date" name="to_date" value="<?= htmlspecialchars($to_date) ?>" class="form-control">
    </div>
    <div class="col-md-6">
        <button class="btn btn-primary">Filter</button>
        <a href="lab_orders.php?view_all=1" class="btn btn-success">View All</a>
        <a href="lab_orders.php" class="btn btn-outline-danger">Reset</a>
    </div>
</form>

<div class="table-responsive">
<table class="table table-hover mb-0" id="Table">
<thead>
<tr>
    <th>File ID</th>
    <th>Patient Names</th>
    <th>Age & Gender</th>
    <th>Insurance</th>
    <th>Requested By</th>
    <th>Order Date</th>
    <th>Status</th>
    <th>Action</th>
</tr>
</thead>

<tbody>
<?php foreach($orders as $o): ?>
<tr>
    <td><?= htmlspecialchars($o['file_id']) ?></td>

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

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

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

    <td><?= htmlspecialchars($o['doctor_name'] ?: 'Unknown') ?></td>

    <td><?= date("Y-m-d H:i:s", strtotime($o['latest_order_date'])) ?></td>

    <td>
        <?php if ($o['total_orders'] == $o['completed_count']): ?>
            <button class="btn btn-success btn-sm" style="width:90px;">Completed</button>
        <?php else: ?>
            <button class="btn btn-warning btn-sm" style="width:90px; color:black;">Pending</button>
        <?php endif; ?>
    </td>

    <td>
        <?php
        $stmt_lab = $pdo->prepare("
            SELECT id 
            FROM lab_orders 
            WHERE visit_ticket_id = ?
              AND facility_id = ?
            ORDER BY id ASC
            LIMIT 1
        ");
        $stmt_lab->execute([
            $o['visit_ticket_id'],
            $facility_id
        ]);
        $first_order = $stmt_lab->fetch(PDO::FETCH_ASSOC);
        ?>

        <?php if ($first_order): ?>
            <a href="view_lab_order.php?id=<?= $first_order['id'] ?>"
               class="btn btn-sm btn-outline-info">View</a>
        <?php endif; ?>
    </td>
</tr>
<?php endforeach; ?>
</tbody>

</table>
</div>

</div>
</div>

</div>
</div>
</div>
</div>

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

<style>
.toast-message {
    position: fixed;
    top: 20px;
    right: 20px;
    padding: 12px 20px;
    color: #fff;
    border-radius: 5px;
    z-index: 9999;
    box-shadow: 0 2px 8px rgba(0,0,0,0.2);
    font-size: 14px;
}
</style>

<script>
function showToast(message, color='#dc3545'){
    var toast = document.createElement('div');
    toast.className = 'toast-message';
    toast.style.background = color;
    toast.innerText = message;
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 4000);
}

<?php if(isset($_SESSION['flash'])): ?>
showToast('<?= addslashes($_SESSION['flash']['message']) ?>','<?= $_SESSION['flash']['color'] ?>');
<?php unset($_SESSION['flash']); endif; ?>
</script>
