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

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

// Fetch Insurance Providers for dropdown
$providers_sql = "SELECT * FROM insurance_providers WHERE active_status = 1";
$providers_res = $conn->query($providers_sql);

$msg = "";

if (isset($_POST['register_insurance'])) {
    // Similar fields to walkin + Insurance Details
    $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']);
    $provider_id = (int) $_POST['provider_id'];
    $policy_no = htmlspecialchars($_POST['policy_number']);
    $member_no = htmlspecialchars($_POST['member_number']); // Extra field often needed

    // Basic Validation
    if (empty($first_name) || empty($last_name) || empty($provider_id) || empty($policy_no)) {
        $msg = '<div class="alert alert-danger">Please fill in all required fields.</div>';
    } else {
        $conn->begin_transaction();
        try {
            $default_pass = password_hash('password123', PASSWORD_DEFAULT);
            $full_name = "$first_name $last_name";

            if (empty($email))
                $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;

            $stmt_patient = $conn->prepare("INSERT INTO patients (user_id, date_of_birth, gender, phone_number, insurance_provider_id, insurance_policy_number, registration_type) VALUES (?, ?, ?, ?, ?, ?, 'INSURANCE')");
            $stmt_patient->bind_param("isssis", $user_id, $dob, $gender, $phone, $provider_id, $policy_no);
            $stmt_patient->execute();
            $patient_id = $conn->insert_id;

            $conn->commit();
            // Redirect to pre-auth or checkin
            header("Location: insurance_preauth.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' => 'Insurance 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 Insurance 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-success">Insurance Information</h5>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Insurance Provider <span
                                                        class="text-danger">*</span></label>
                                                <select name="provider_id" class="form-select" required>
                                                    <option value="">Select Provider</option>
                                                    <?php while ($prov = $providers_res->fetch_assoc()): ?>
                                                        <option value="<?php echo $prov['provider_id']; ?>">
                                                            <?php echo htmlspecialchars($prov['provider_name']); ?></option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Policy / Member Number <span
                                                        class="text-danger">*</span></label>
                                                <input type="text" name="policy_number" class="form-control" required>
                                            </div>
                                        </div>

                                        <h5 class="mb-3 mt-4 text-primary">Patient Details</h5>
                                        <div class="row">
                                            <div class="col-md-6 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-6 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</label>
                                                <select name="gender" class="form-select">
                                                    <option value="MALE">Male</option>
                                                    <option value="FEMALE">Female</option>
                                                </select>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Phone</label>
                                                <input type="text" name="phone" class="form-control">
                                            </div>
                                        </div>

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

</html>