<?php
require_once 'layouts/session.php';
require_once 'layouts/dbconn.php';

/*
|--------------------------------------------------------------------------
| ACCESS CONTROL
|--------------------------------------------------------------------------
*/
$allowed_roles = [
    'SUPER_ADMIN',
    'HOSPITAL_ADMIN',
    'RECEPTIONIST',
    'ENT_DOCTOR',
    'ENT_CONSULTANT',
    'HEAD_NURSE',
    'LAB_TECHNICIAN'
];

if (!isset($_SESSION['role_code']) || !in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

/*
|--------------------------------------------------------------------------
| FILTERS
|--------------------------------------------------------------------------
*/
$ward_filter   = $_GET['ward']   ?? '';
$status_filter = $_GET['status'] ?? '';
$search        = trim($_GET['search'] ?? '');

/*
|--------------------------------------------------------------------------
| STATISTICS (SCHEMA-CORRECT)
|--------------------------------------------------------------------------
*/
$stats_sql = "
    SELECT 
        COUNT(DISTINCT pv.visit_id) AS total_patients,

        COUNT(DISTINCT CASE 
            WHEN pv.status = 'IN_CONSULTATION' 
            THEN pv.visit_id 
        END) AS admitted_patients,

        COUNT(DISTINCT CASE 
            WHEN pv.status = 'WAITING' 
            THEN pv.visit_id 
        END) AS in_progress,

        COUNT(DISTINCT CASE 
            WHEN pv.status = 'COMPLETED'
             AND DATE(pv.registration_date) = CURDATE()
            THEN pv.visit_id 
        END) AS discharged_today

    FROM patient_visits pv
    WHERE pv.status IN ('WAITING', 'IN_CONSULTATION')
      AND DATE(pv.registration_date) = CURDATE()
";

$stats = [
    'total_patients'     => 0,
    'admitted_patients'  => 0,
    'in_progress'        => 0,
    'discharged_today'   => 0
];

if ($result = $conn->query($stats_sql)) {
    $stats = $result->fetch_assoc();
}
?>

<?php include 'layouts/main.php'; ?>

<head>
<?php includeFileWithVariables('layouts/title-meta.php', ['title' => 'Ward Patients']); ?>
<?php include 'layouts/head-css.php'; ?>
<link href="assets/libs/datatables/datatables.min.css" rel="stylesheet">
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
</head>

<body>
<div id="layout-wrapper">
<?php include 'layouts/menu.php'; ?>

<div class="main-content">
<div class="page-content">
<div class="container-fluid">

<!-- PAGE TITLE -->
<div class="row">
    <div class="col-12">
        <div class="page-title-box d-flex justify-content-between">
            <h4>Ward Patients</h4>
            <ol class="breadcrumb m-0">
                <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                <li class="breadcrumb-item active">Ward Patients</li>
            </ol>
        </div>
    </div>
</div>

<!-- STATS -->
<div class="row">
    <div class="col-md-3">
        <div class="card">
            <div class="card-body">
                <h6>Total Patients</h6>
                <h3><?= number_format($stats['total_patients']) ?></h3>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card">
            <div class="card-body text-primary">
                <h6>Admitted</h6>
                <h3><?= number_format($stats['admitted_patients']) ?></h3>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card">
            <div class="card-body text-warning">
                <h6>In Progress</h6>
                <h3><?= number_format($stats['in_progress']) ?></h3>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card">
            <div class="card-body text-success">
                <h6>Discharged Today</h6>
                <h3><?= number_format($stats['discharged_today']) ?></h3>
            </div>
        </div>
    </div>
</div>

<!-- FILTERS -->
<div class="card mt-3">
<div class="card-body">
<form method="GET" class="row g-3">

<div class="col-md-4">
    <label>Search</label>
    <input type="text" name="search" class="form-control"
           value="<?= htmlspecialchars($search) ?>"
           placeholder="Patient name or number">
</div>

<div class="col-md-4">
    <label>Status</label>
    <select name="status" class="form-select">
        <option value="">All</option>
        <option value="IN_CONSULTATION" <?= $status_filter=='IN_CONSULTATION'?'selected':'' ?>>Admitted</option>
        <option value="WAITING" <?= $status_filter=='WAITING'?'selected':'' ?>>In Progress</option>
    </select>
</div>

<div class="col-md-4 d-flex align-items-end gap-2">
    <button class="btn btn-success">Filter</button>
    <a href="ward_patients.php" class="btn btn-secondary">Reset</a>
</div>

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

<!-- TABLE -->
<div class="card mt-3">
<div class="card-body">
<table id="wardPatientsTable" class="table table-striped">
<thead>
<tr>
    <th>Patient No</th>
    <th>Name</th>
    <th>Age / Gender</th>
    <th>Visit Date</th>
    <th>Status</th>
    <th>Actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>

</div>
</div>

<?php include 'layouts/footer.php'; ?>
</div>
</div>

<?php include 'layouts/vendor-scripts.php'; ?>
<script src="assets/libs/datatables/datatables.min.js"></script>

<script>
$(function () {
    $('#wardPatientsTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: 'ajax/get_ward_patients.php',
            type: 'POST',
            data: {
                status: '<?= $status_filter ?>',
                search: '<?= $search ?>'
            }
        },
        columns: [
            { data: 'patient_number' },
            { data: 'patient_name' },
            { data: 'age_gender' },
            { data: 'visit_date' },
            { data: 'status' },
            { data: 'actions', orderable: false }
        ],
        order: [[3, 'desc']]
    });
});
</script>

</body>
</html>
