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

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

$msg = "";

if (isset($_POST['register_walkin'])) {
    $title = htmlspecialchars($_POST['title']);
    $first_name = htmlspecialchars($_POST['first_name']);
    $last_name = htmlspecialchars($_POST['last_name']);
    $dob = htmlspecialchars($_POST['dob']);
    $gender = htmlspecialchars($_POST['gender']);
    $phone = htmlspecialchars($_POST['phone']);
    $email = htmlspecialchars($_POST['email']);
    $address = htmlspecialchars($_POST['address']);
    $kin_name = htmlspecialchars($_POST['next_of_kin_name']);
    $kin_phone = htmlspecialchars($_POST['next_of_kin_phone']);

    // Basic Validation
    if (empty($first_name) || empty($last_name) || empty($dob) || empty($phone)) {
        $msg = '<div class="alert alert-danger">Please fill in all required fields.</div>';
    } else {
        $conn->begin_transaction();
        try {
            // 1. Create User Account (Auto-generate password or set default?)
            // For now, setting a default password 'password123'
            $default_pass = password_hash('password123', PASSWORD_DEFAULT);
            $full_name = "$title $first_name $last_name";

            // Check email uniqueness if provided
            if (!empty($email)) {
                $check = $conn->query("SELECT user_id FROM users WHERE email='$email'");
                if ($check->num_rows > 0) {
                    throw new Exception("Email already registered.");
                }
            } else {
                // Generate a dummy email if not provided for walk-ins? Or allow null?
                // Users table usually requires email. Let's make a dummy one.
                $email = strtolower($first_name . $last_name . rand(1000, 9999)) . "@temp.com";
            }

            $stmt_user = $conn->prepare("INSERT INTO users (full_name, email, password, role_code, is_active) VALUES (?, ?, ?, 'PATIENT', 1)");
            $stmt_user->bind_param("sss", $full_name, $email, $default_pass);
            $stmt_user->execute();
            $user_id = $conn->insert_id;

            // 2. Create Patient Record
            $stmt_patient = $conn->prepare("INSERT INTO patients (user_id, date_of_birth, gender, phone_number, address, registration_type, next_of_kin_name, next_of_kin_phone) VALUES (?, ?, ?, ?, ?, 'WALK_IN', ?, ?)");
            $stmt_patient->bind_param("issssss", $user_id, $dob, $gender, $phone, $address, $kin_name, $kin_phone);
            $stmt_patient->execute();
            $patient_id = $conn->insert_id;

            $conn->commit();
            $_SESSION['success'] = "Patient registered successfully! Patient ID: " . $patient_id;
            // Redirect to check-in or profile?
            header("Location: patient_checkin.php?patient_id=" . $patient_id);
            exit();

        } catch (Exception $e) {
            $conn->rollback();
            $msg = '<div class="alert alert-danger">Error: ' . $e->getMessage() . '</div>';
        }
    }
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Walk-in Registration')); ?>
    <?php include 'layouts/head-css.php'; ?>
</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">New Walk-in Patient Registration</h4>
                            </div>
                        </div>
                    </div>

                    <div class="row justify-content-center">
                        <div class="col-lg-10">
                            <div class="card">
                                <div class="card-body">
                                    <?php echo $msg; ?>
                                    <form method="POST" action="">
                                        <h5 class="mb-3 text-primary">Personal Information</h5>
                                        <div class="row">
                                            <div class="col-md-2 mb-3">
                                                <label class="form-label">Title</label>
                                                <select name="title" class="form-select">
                                                    <option value="Mr.">Mr.</option>
                                                    <option value="Mrs.">Mrs.</option>
                                                    <option value="Ms.">Ms.</option>
                                                    <option value="Dr.">Dr.</option>
                                                </select>
                                            </div>
                                            <div class="col-md-5 mb-3">
                                                <label class="form-label">First Name <span
                                                        class="text-danger">*</span></label>
                                                <input type="text" name="first_name" class="form-control" required>
                                            </div>
                                            <div class="col-md-5 mb-3">
                                                <label class="form-label">Last Name <span
                                                        class="text-danger">*</span></label>
                                                <input type="text" name="last_name" class="form-control" required>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Date of Birth <span
                                                        class="text-danger">*</span></label>
                                                <input type="date" name="dob" class="form-control" required>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Gender <span
                                                        class="text-danger">*</span></label>
                                                <select name="gender" class="form-select" required>
                                                    <option value="MALE">Male</option>
                                                    <option value="FEMALE">Female</option>
                                                    <option value="OTHER">Other</option>
                                                </select>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Phone Number <span
                                                        class="text-danger">*</span></label>
                                                <input type="text" name="phone" class="form-control"
                                                    placeholder="0712345678" required>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Email Address (Optional)</label>
                                                <input type="email" name="email" class="form-control"
                                                    placeholder="patient@example.com">
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Physical Address</label>
                                                <input type="text" name="address" class="form-control"
                                                    placeholder="Residence/Location">
                                            </div>
                                        </div>

                                        <h5 class="mb-3 mt-4 text-primary">Emergency Contact (Next of Kin)</h5>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Name</label>
                                                <input type="text" name="next_of_kin_name" class="form-control">
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Phone</label>
                                                <input type="text" name="next_of_kin_phone" class="form-control">
                                            </div>
                                        </div>

                                        <div class="mt-4 text-end">
                                            <button type="submit" name="register_walkin"
                                                class="btn btn-primary w-md">Register Patient</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>

</html>