<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

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

// Fetch Departments
$dept_sql = "SELECT * FROM departments WHERE is_active = 1";
$depts = $conn->query($dept_sql);

// Handle Check-in
if (isset($_POST['checkin'])) {
    $patient_id = $_POST['patient_id'];
    $dept_id = $_POST['dept_id'];
    $priority = $_POST['priority'] ?? 'NORMAL';
    $notes = htmlspecialchars($_POST['notes']);

    // Generate Queue Number (Simplified logic for now, or call procedure)
    // Using simple format: DEPT-ID-RAND
    $dept_row = $conn->query("SELECT department_code FROM departments WHERE department_id = $dept_id")->fetch_assoc();
    $dept_code = $dept_row['department_code'] ?? 'GEN';
    $queue_no = $dept_code . '-' . date('dm') . '-' . rand(100, 999);

    // Fetch patient details for denormalized columns
    $pat_data = $conn->query("SELECT p.patient_id, u.full_name, p.phone_number FROM patients p JOIN users u ON p.user_id=u.user_id WHERE p.patient_id=$patient_id")->fetch_assoc();
    $p_name = $pat_data['full_name'];
    // Generate valid patient number if missing or just use ID
    $p_number = str_pad($patient_id, 6, "0", STR_PAD_LEFT);

    $sql = "INSERT INTO patient_queue (department_id, patient_id, queue_number, priority_level, notes, queue_status, queue_entry_time, patient_name, patient_number, phone_number) 
            VALUES (?, ?, ?, ?, ?, 'WAITING', NOW(), ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("iissssss", $dept_id, $patient_id, $queue_no, $priority, $notes, $p_name, $p_number, $pat_data['phone_number']);

    if ($stmt->execute()) {
        $_SESSION['success'] = "Patient checked in successfully. Queue No: $queue_no";
        header("Location: waiting_room.php");
        exit();
    } else {
        $error = "Error checking in: " . $conn->error;
    }
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Patient Check-in')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/select2/css/select2.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">
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Patient Check-in</h4>
                            </div>
                        </div>
                    </div>

                    <div class="row justify-content-center">
                        <div class="col-lg-6">
                            <div class="card">
                                <div class="card-body">
                                    <?php if (isset($error)): ?>
                                        <div class="alert alert-danger"><?php echo $error; ?></div><?php endif; ?>
                                    <form method="POST">
                                        <div class="mb-3">
                                            <label class="form-label">Search Patient</label>
                                            <select class="form-select select2" name="patient_id" required>
                                                <option value="">Select Patient...</option>
                                                <!-- Ajax loading would be better, but fetching recent 50 for now -->
                                                <?php
                                                $p_sql = "SELECT p.patient_id, u.full_name, p.phone_number FROM patients p JOIN users u ON p.user_id = u.user_id ORDER BY p.updated_at DESC LIMIT 50";
                                                $p_res = $conn->query($p_sql);
                                                while ($p = $p_res->fetch_assoc()) {
                                                    echo "<option value='" . $p['patient_id'] . "'>" . $p['full_name'] . " (" . $p['phone_number'] . ")</option>";
                                                }
                                                ?>
                                            </select>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Department / Service Point</label>
                                            <select class="form-select" name="dept_id" required>
                                                <?php while ($d = $depts->fetch_assoc()): ?>
                                                    <option value="<?php echo $d['department_id']; ?>">
                                                        <?php echo $d['department_name']; ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Priority</label>
                                            <select class="form-select" name="priority">
                                                <option value="NORMAL">Normal</option>
                                                <option value="URGENT">Urgent</option>
                                                <option value="EMERGENCY">Emergency</option>
                                            </select>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Notes (Reason for Visit)</label>
                                            <textarea class="form-control" name="notes" rows="3"></textarea>
                                        </div>
                                        <button type="submit" name="checkin" class="btn btn-primary w-100">Check
                                            In</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/select2/js/select2.min.js"></script>
    <script>
        $(document).ready(function () {
            $('.select2').select2();
        });
    </script>
</body>

</html>