<?php
session_start();

// Enable development errors for debugging
ini_set('display_errors', 1);
error_reporting(E_ALL);

// 1. Correct Path to Database
require_once __DIR__ . '/../../dripend/includes/db.php';

if (!isset($conn) || !$conn) {
    die("<div style='padding:20px; background:#fee2e2; color:#991b1b; font-family:sans-serif;'>Fatal Error: Database connection failed. Please check includes/db.php</div>");
}

$error_message = "";
$success_data = null; // Used to trigger the JS popup

// ==============================================================================
// 2. FORM PROCESSING LOGIC (Synchronized with Enterprise Schema)
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // --- 1. CAPTURE CORE DEMOGRAPHICS ---
    // Safely capture inputs (Convert empty strings to NULL for unique columns)
    $patient_no         = $_POST['patient_no'] ?? '';
    $first_name         = trim($_POST['first_name'] ?? '');
    $middle_name        = trim($_POST['middle_name'] ?? '');
    $last_name          = trim($_POST['last_name'] ?? '');
    $dob                = $_POST['dob'] ?? '';
    $hometown           = trim($_POST['hometown'] ?? '');
    $patient_address    = trim($_POST['patient_address'] ?? '');
    $region             = trim($_POST['region'] ?? '');
    $town               = trim($_POST['town'] ?? '');
    
    // --- 2. TELECOM NUMBER CONCATENATION ---
    // We fetch the prefix the user selected (e.g. 024) and combine it with the 7 digits
    $network_prefix_raw = trim($_POST['mobile_prefix'] ?? '');
    $mobile_7_digits    = trim($_POST['mobile_digits'] ?? '');
    $mobile_network_id  = null;
    $mobile             = '';

    if (!empty($network_prefix_raw) && !empty($mobile_7_digits)) {
        // Query the database to find the exact ID for the selected telecom prefix
        $net_chk = $conn->prepare("SELECT id FROM dict_telecom_network WHERE prefix_code = ? LIMIT 1");
        $net_chk->bind_param("s", $network_prefix_raw);
        $net_chk->execute();
        $net_res = $net_chk->get_result();
        if ($net_row = $net_res->fetch_assoc()) {
            $mobile_network_id = $net_row['id'];
        }
        $net_chk->close();
        
        // Combine them for the final database entry (e.g. 024 + 1234567 = 0241234567)
        $mobile = $network_prefix_raw . $mobile_7_digits;
    }

    // --- 3. STRICT REGEX FORMATTING VALIDATION ---
    // Prevent bad data from entering the database
    
    // Ghana Card Validation (Must be exactly GHA-XXXXXXXXX-X)
    $ghana_card_no = !empty(trim($_POST['ghana_card_no'] ?? '')) ? trim(strtoupper($_POST['ghana_card_no'])) : null;
    if ($ghana_card_no && !preg_match("/^GHA-\d{9}-\d{1}$/", $ghana_card_no)) {
        $error_message .= "• Invalid Ghana Card format. Must be exactly GHA-XXXXXXXXX-X.<br>";
    }

    // Ghana Post GPS Validation (Must be like GA-123-4567 or WS-1234-5678)
    $residential_gps = !empty(trim($_POST['residential_gps'] ?? '')) ? trim(strtoupper($_POST['residential_gps'])) : null;
    if ($residential_gps && !preg_match("/^[A-Z]{2}-\d{3,4}-\d{4}$/", $residential_gps)) {
        $error_message .= "• Invalid Ghana Post GPS format. Must be like GA-123-4567 or WS-1234-5678.<br>";
    }

    // Email Validation
    $email = !empty(trim($_POST['email'] ?? '')) ? trim($_POST['email']) : null;
    if ($email && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error_message .= "• Invalid Email Address format.<br>";
    }

    // --- 4. CAPTURE INSURANCE & FLAGS ---
    $insurance_category = $_POST['insurance_category'] ?? 'cash';
    $nhis_no            = ($insurance_category === 'nhis' && !empty(trim($_POST['nhis_no'] ?? ''))) ? trim($_POST['nhis_no']) : null;
    $other_insurance_id = ($insurance_category === 'private' && !empty($_POST['other_insurance_id'])) ? (int)$_POST['other_insurance_id'] : null;
    $other_insurance_no = ($insurance_category === 'private' && !empty(trim($_POST['other_insurance_no'] ?? ''))) ? trim($_POST['other_insurance_no']) : null;
    
    // Dependent & Staff Flags (No mappings applied to insurance details, just raw boolean saves)
    $is_mother_dependent = isset($_POST['is_mother_dependent']) ? (int)$_POST['is_mother_dependent'] : 0;
    $is_staff            = isset($_POST['is_staff']) ? (int)$_POST['is_staff'] : 0;
    $is_staff_dependent  = isset($_POST['is_staff_dependent']) ? (int)$_POST['is_staff_dependent'] : 0;
    $is_first_time       = isset($_POST['is_first_time']) ? (int)$_POST['is_first_time'] : 1;

    // Emergency Address Logic
    $same_as_patient     = isset($_POST['same_as_patient']) ? 1 : 0;
    $emergency_address   = $same_as_patient ? $patient_address : trim($_POST['emergency_address'] ?? '');

    // --- 5. STRICT PHP DUPLICATE CHECKING ---
    // If NOT an infant using mother's details, enforce absolute uniqueness across identifiers.
    if ($is_mother_dependent === 0 && empty($error_message)) {
        
        if (!empty($mobile)) {
            $chk = $conn->prepare("SELECT id FROM patient WHERE mobile = ?");
            $chk->bind_param("s", $mobile);
            $chk->execute();
            if ($chk->get_result()->num_rows > 0) $error_message .= "• Mobile Number '$mobile' is already registered.<br>";
            $chk->close();
        }

        if (!empty($email)) {
            $chk = $conn->prepare("SELECT id FROM patient WHERE email = ?");
            $chk->bind_param("s", $email);
            $chk->execute();
            if ($chk->get_result()->num_rows > 0) $error_message .= "• Email Address '$email' is already registered.<br>";
            $chk->close();
        }
        
        if (!empty($ghana_card_no)) {
            $chk = $conn->prepare("SELECT id FROM patient WHERE ghana_card_no = ?");
            $chk->bind_param("s", $ghana_card_no);
            $chk->execute();
            if ($chk->get_result()->num_rows > 0) $error_message .= "• Ghana Card Number '$ghana_card_no' is already registered.<br>";
            $chk->close();
        }

        if ($insurance_category === 'nhis' && !empty($nhis_no)) {
            $chk = $conn->prepare("SELECT id FROM patient WHERE nhis_no = ?");
            $chk->bind_param("s", $nhis_no);
            $chk->execute();
            if ($chk->get_result()->num_rows > 0) $error_message .= "• NHIS Number '$nhis_no' already exists.<br>";
            $chk->close();
        }
        
        if ($insurance_category === 'private' && !empty($other_insurance_no)) {
            $chk = $conn->prepare("SELECT id FROM patient WHERE other_insurance_no = ?");
            $chk->bind_param("s", $other_insurance_no);
            $chk->execute();
            if ($chk->get_result()->num_rows > 0) $error_message .= "• Corporate Insurance Number '$other_insurance_no' already exists.<br>";
            $chk->close();
        }
    }

    // --- 6. FINAL DATABASE INSERTION ---
    // Only proceed with insertion if there are absolutely NO validation or duplicate errors
    if (empty($error_message)) {
        $emergency_name     = trim($_POST['emergency_name'] ?? '');
        $emergency_number   = trim($_POST['emergency_number'] ?? '');

        // Convert empty dropdowns to NULL for strict Foreign Keys
        $prefix_id             = !empty($_POST['prefix_id']) ? (int)$_POST['prefix_id'] : null;
        $gender_id             = !empty($_POST['gender_id']) ? (int)$_POST['gender_id'] : null;
        $marital_status_id     = !empty($_POST['marital_status_id']) ? (int)$_POST['marital_status_id'] : null;
        $occupation_id         = !empty($_POST['occupation_id']) ? (int)$_POST['occupation_id'] : null;
        $education_level_id    = !empty($_POST['education_level_id']) ? (int)$_POST['education_level_id'] : null;
        $religion_id           = !empty($_POST['religion_id']) ? (int)$_POST['religion_id'] : null;
        $smoking_status_id     = !empty($_POST['smoking_status_id']) ? (int)$_POST['smoking_status_id'] : null;
        $alcohol_status_id     = !empty($_POST['alcohol_status_id']) ? (int)$_POST['alcohol_status_id'] : null;
        $child_status_id       = !empty($_POST['child_status_id']) ? (int)$_POST['child_status_id'] : null;
        $emergency_relation_id = !empty($_POST['emergency_relation_id']) ? (int)$_POST['emergency_relation_id'] : null;

        // The query handles exactly 34 columns. 
        $sql = "INSERT INTO patient (
            patient_no, prefix_id, first_name, middle_name, last_name, gender_id, dob, mobile_network_id, hometown,
            mobile, email, patient_address, residential_gps, region, town, ghana_card_no, nhis_no, other_insurance_id, other_insurance_no,
            marital_status_id, occupation_id, education_level_id, religion_id, smoking_status_id, alcohol_status_id, child_status_id,
            emergency_name, emergency_number, emergency_relation_id, emergency_address, 
            is_staff, is_mother_dependent, is_staff_dependent, is_first_time
        ) VALUES (
            ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
        )";

        $stmt = $conn->prepare($sql);
        if (!$stmt) die("SQL Prepare Error: " . $conn->error);

        // BIND PARAMETERS EXPLANATION (Crucial for debugging)
        // There are exactly 34 variables being bound.
        // The type definition string below has exactly 34 characters (s = string, i = integer/null).
        // 1-10:   s i s s s i s i s s
        // 11-20:  s s s s s s s i s i
        // 21-30:  i i i i i i s s i s
        // 31-34:  i i i i
        $stmt->bind_param("sisssisissssssssisisiiiiiissisiiii",
            $patient_no, $prefix_id, $first_name, $middle_name, $last_name, $gender_id, $dob, $mobile_network_id, $hometown,
            $mobile, $email, $patient_address, $residential_gps, $region, $town, $ghana_card_no, $nhis_no, $other_insurance_id, $other_insurance_no,
            $marital_status_id, $occupation_id, $education_level_id, $religion_id, $smoking_status_id, $alcohol_status_id, $child_status_id,
            $emergency_name, $emergency_number, $emergency_relation_id, $emergency_address, 
            $is_staff, $is_mother_dependent, $is_staff_dependent, $is_first_time
        );

        if ($stmt->execute()) {
            
            // --- 7. FIRE SMS NOTIFICATION SCRIPT ---
            // Wrapped in a Try/Catch block. If the API is offline or out of credits,
            // the patient is STILL saved to the DB and the front-desk UX is not disrupted.
            try {
                if (file_exists('../../dripend/sendSMSNotifications/sendRegistrationSms.php')) {
                    require_once '../../dripend/sendSMSNotifications/sendRegistrationSms.php';
                }
            } catch (Exception $e) {
                error_log("SMS Dispatch Failed: " . $e->getMessage());
            }

            // Determine Redirect URL based on which button was clicked
            $submit_action = $_POST['submit_action'] ?? 'dashboard';
            $target_url = ($submit_action === 'save_and_book') 
                ? "../appointment/add_appointment.php?patient_id=" . urlencode($patient_no) 
                : "search_patient.php";

            // Resolve Detailed Insurance Name for the Success Popup only
            $provider_details = 'Cash / Out of Pocket';
            if ($insurance_category === 'nhis') {
                $provider_details = 'NHIS (ID: ' . ($nhis_no ? $nhis_no : 'Pending') . ')';
            } elseif ($insurance_category === 'private' && $other_insurance_id) {
                $ins_name = 'Corporate Provider';
                $ins_chk = $conn->prepare("SELECT insurance_name FROM insurance_type WHERE id = ?");
                $ins_chk->bind_param("i", $other_insurance_id);
                $ins_chk->execute();
                $ins_res = $ins_chk->get_result();
                if ($ins_row = $ins_res->fetch_assoc()) {
                    $ins_name = $ins_row['insurance_name'];
                }
                $ins_chk->close();
                $provider_details = $ins_name . ' (ID: ' . ($other_insurance_no ? $other_insurance_no : 'Pending') . ')';
            }

            // Pack the success payload for JavaScript
            $success_data = [
                'redirect_url'      => $target_url,
                'patient_no'        => $patient_no,
                'patient_name'      => trim("$first_name $last_name"),
                'insurance_details' => $provider_details
            ];
        } else {
            $error_message = "Database Error: " . $stmt->error;
        }
    }
}

// ==============================================================================
// 3. UI DATA PREPARATION
// ==============================================================================

function fetchLookup($conn, $table, $nameField) {
    $stmt = $conn->query("SELECT id, {$nameField} AS name FROM {$table} ORDER BY {$nameField} ASC");
    $rows = [];
    if ($stmt) while ($r = $stmt->fetch_assoc()) $rows[] = $r;
    return $rows;
}

// Dynamic Dictionary Fetches
$prefixes         = fetchLookup($conn, 'prefix', 'prefix_name');
$genders          = fetchLookup($conn, 'gender', 'gender_name');
$maritals         = fetchLookup($conn, 'marital_status', 'status_name');
$occupations      = fetchLookup($conn, 'occupation', 'occupation_name');
$educations       = fetchLookup($conn, 'education_level', 'education_name');
$religions        = fetchLookup($conn, 'religion', 'religion_name');
$smoking_statuses = fetchLookup($conn, 'dict_smoking_status', 'status_name');
$alcohol_statuses = fetchLookup($conn, 'dict_alcohol_status', 'status_name');
$insurances       = fetchLookup($conn, 'insurance_type', 'insurance_name');
$children         = fetchLookup($conn, 'child_status', 'child_name');
$relations        = fetchLookup($conn, 'emergency_relation', 'relation_name');

// Fetch Telecom Networks
$telecoms = [];
$tRes = $conn->query("SELECT prefix_code, network_name FROM dict_telecom_network ORDER BY network_name ASC");
if ($tRes) while ($tRow = $tRes->fetch_assoc()) $telecoms[] = $tRow;

// Fetch the Universal Yes/No Dictionary
$yes_no_options = [];
$ynRes = $conn->query("SELECT id, name FROM dict_yes_no ORDER BY id ASC");
if ($ynRes) while ($ynRow = $ynRes->fetch_assoc()) $yes_no_options[] = $ynRow;

// Fetch dynamic regions from DB
$ghana_regions = [];
$rRes = $conn->query("SELECT region_name FROM ghana_regions WHERE is_active = 1 ORDER BY region_name ASC");
if ($rRes) while ($rRow = $rRes->fetch_assoc()) $ghana_regions[] = $rRow['region_name'];

// Fetch distinct existing towns to seed the datalist for searching
$town_seed = [];
$tRes = $conn->query("SELECT DISTINCT town FROM patient WHERE town IS NOT NULL AND town != '' ORDER BY town ASC");
if ($tRes) while ($tRow = $tRes->fetch_assoc()) $town_seed[] = $tRow['town'];

$children_json = json_encode($children);

// Generate Next Patient No
$year = date('Y');
$month = date('m');
$patient_prefix = "DDC-K{$year}-{$month}-";
$res = $conn->query("SELECT patient_no FROM patient WHERE patient_no LIKE '{$patient_prefix}%' ORDER BY id DESC LIMIT 1");
$lastNum = 1;
if ($res && $res->num_rows > 0) {
    $row = $res->fetch_assoc();
    $suffix = substr($row['patient_no'], strlen($patient_prefix));
    if (ctype_digit($suffix)) $lastNum = intval($suffix) + 1;
}
$patient_no = $patient_prefix . str_pad($lastNum, 5, "0", STR_PAD_LEFT);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Register Patient | DripDental</title>
<style>
:root {
  --sidebar-width: 240px;
  --e-blue: #1e3a8a;
  --e-blue-light: #eff6ff;
  --e-green: #16a34a;
  --e-red: #ef4444;
  --e-yellow: #fffbeb;
  --e-yellow-border: #f59e0b;
  --bg-color: #f8fafc;
  --card-bg: #ffffff;
  --border-color: #e2e8f0;
  --text-main: #0f172a;
  --text-muted: #64748b;
}

* { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Segoe UI', system-ui, sans-serif; }

body { background: var(--bg-color); color: var(--text-main); overflow: hidden; }

/* SCROLLABLE LAYOUT FIX */
.page-wrapper {
  position: absolute; top: 0; left: var(--sidebar-width); width: calc(100% - var(--sidebar-width));
  height: 100vh; overflow-y: auto; padding: 30px 30px 60px 30px; background: var(--bg-color); display: block; 
}

.form-container { max-width: 1100px; margin: 0 auto; }
.page-title { font-size: 24px; font-weight: 800; color: var(--e-blue); margin: 0 0 20px 0; text-transform: uppercase; }

.t1-section { background: var(--card-bg); border: 1px solid var(--border-color); border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.02); }
.t1-header { background: #fff; border-bottom: 1px solid var(--border-color); padding: 12px 20px; font-size: 15px; font-weight: 700; color: var(--e-blue); }
.t1-body { padding: 20px; display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 15px; }

.form-group { display: flex; flex-direction: column; gap: 4px; }
label { font-size: 12px; font-weight: 700; color: var(--text-muted); text-transform: uppercase; }
.req { color: var(--e-red); }
input[type="text"], input[type="date"], input[type="email"], select { padding: 10px 12px; font-size: 14px; border: 1px solid #cbd5e1; border-radius: 6px; outline: none; background: #fff;}
input:focus, select:focus { border-color: var(--e-blue); box-shadow: 0 0 0 3px var(--e-blue-light); }
input[readonly], input:disabled { background: #f1f5f9; color: var(--text-muted); font-weight: 700; cursor: not-allowed; }

.mobile-group { display: flex; gap: 0; }
.mobile-group select { border-radius: 6px 0 0 6px; border-right: none; width: 120px; background: #f8fafc;}
.mobile-group input { border-radius: 0 6px 6px 0; flex: 1; }

.insurance-selector { grid-column: 1 / -1; margin-bottom: 10px; }
.ins-options { display: flex; gap: 20px; padding: 15px; background: #f8fafc; border: 1px solid var(--border-color); border-radius: 8px; }
.ins-radio-label { display: flex; align-items: center; gap: 8px; font-weight: 600; cursor: pointer; font-size: 14px; color: var(--text-main); }
.ins-radio-label input { width: 18px; height: 18px; cursor: pointer; }

.dynamic-field { display: none; grid-column: 1 / -1; padding: 15px; border-radius: 8px; border: 1px dashed #cbd5e1; margin-top: -5px; }
.dynamic-field.open { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 15px; }

.baby-alert { display: none; grid-column: 1 / -1; background: var(--e-yellow); border: 1px solid var(--e-yellow-border); padding: 15px; border-radius: 8px; align-items: center; justify-content: space-between; }
.baby-alert.open { display: flex; animation: slideDown 0.3s ease; }
.checkbox-wrap { display: flex; align-items: center; gap: 8px; font-weight: 700; color: #0f172a; cursor: pointer; font-size: 13px;}
.checkbox-wrap input { width: 18px; height: 18px; cursor: pointer; }

@keyframes slideDown { from{opacity:0; transform:translateY(-5px);} to{opacity:1; transform:translateY(0);} }

.form-actions { display: flex; justify-content: flex-end; gap: 15px; margin-top: 10px; }
.btn { padding: 12px 20px; border: none; border-radius: 6px; font-size: 14px; font-weight: 700; cursor: pointer; transition: 0.2s; }
.btn-dash { background: #334155; color: #fff; }
.btn-dash:hover { background: #1e293b; }
.btn-book { background: var(--e-green); color: #fff; }
.btn-book:hover { background: #15803d; }

/* MODAL STYLES */
.modal-overlay {
  position: fixed; top: 0; left: 0; width: 100%; height: 100%;
  background: rgba(15, 23, 42, 0.6); backdrop-filter: blur(4px);
  display: none; justify-content: center; align-items: center; z-index: 9999;
}
.modal-overlay.active { display: flex; animation: fadeIn 0.2s ease-in-out; }
.modal-content {
  background: #fff; padding: 30px; border-radius: 12px; width: 90%; max-width: 450px;
  box-shadow: 0 10px 25px rgba(0,0,0,0.1); text-align: center;
  transform: translateY(20px); transition: transform 0.3s ease;
}
.modal-overlay.active .modal-content { transform: translateY(0); }
.modal-icon { font-size: 45px; margin-bottom: 10px; }
.modal-icon.error { color: var(--e-red); }
.modal-title { font-size: 22px; font-weight: 800; color: var(--e-blue); margin-bottom: 15px; }
.modal-details {
  background: #f8fafc; padding: 18px; border-radius: 8px; text-align: left;
  border: 1px solid var(--border-color); margin-bottom: 20px;
}
.modal-details p { font-size: 15px; font-weight: 700; color: var(--text-main); margin: 8px 0; display:flex; justify-content:space-between; align-items:center; border-bottom: 1px dashed var(--border-color); padding-bottom:6px;}
.modal-details p:last-child { border-bottom: none; padding-bottom: 0; }
.modal-details span { font-weight: 800; color: var(--text-muted); font-size: 13px; text-transform:uppercase;}
.btn-modal-ok {
  width: 100%; padding: 14px; background: var(--e-blue); color: #fff;
  border: none; border-radius: 6px; font-size: 16px; font-weight: 700; cursor: pointer;
}
.btn-modal-ok:hover { background: #1e293b; }
@keyframes fadeIn { from{opacity:0;} to{opacity:1;} }
</style>
</head>
<body>

<?php include('../../dripend/statpages/sidebar.php'); ?>

<datalist id="ghana_regions">
    <?php foreach($ghana_regions as $r): ?>
        <option value="<?php echo htmlspecialchars($r); ?>">
    <?php endforeach; ?>
</datalist>

<datalist id="existing_towns">
    <?php foreach($town_seed as $t): ?>
        <option value="<?php echo htmlspecialchars($t); ?>">
    <?php endforeach; ?>
</datalist>

<div class="page-wrapper">
  <div class="form-container">
    
    <h1 class="page-title">Register New Patient</h1>

    <form id="regForm" method="post" action="addNewPatient.php">
      
      <div class="t1-section">
        <div class="t1-header">👤 Core Demographics</div>
        <div class="t1-body">
          <div class="form-group"><label>System ID</label><input type="text" name="patient_no" value="<?php echo htmlspecialchars($patient_no); ?>" readonly></div>
          
          <div class="form-group" style="grid-column: span 2; background:#e0f2fe; padding:8px 12px; border-radius:6px; border:1px solid #bae6fd;">
            <label style="color:#0284c7;">First time accessing healthcare in this facility?</label>
            <select name="is_first_time" style="border-color:#7dd3fc; font-weight:bold;">
              <?php foreach ($yes_no_options as $yn): ?>
                <option value="<?php echo $yn['id']; ?>" <?php echo ($yn['id'] == 1) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($yn['name']); ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="form-group"><label>Title</label>
            <select name="prefix_id">
              <option value="">Select</option>
              <?php foreach ($prefixes as $p): ?>
                <option value="<?php echo $p['id']; ?>"><?php echo htmlspecialchars($p['name']); ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="form-group"><label>First Name <span class="req">*</span></label><input type="text" name="first_name" required value="<?php echo htmlspecialchars($first_name ?? ''); ?>"></div>
          <div class="form-group"><label>Middle Name</label><input type="text" name="middle_name" value="<?php echo htmlspecialchars($middle_name ?? ''); ?>"></div>
          <div class="form-group"><label>Last Name <span class="req">*</span></label><input type="text" name="last_name" required value="<?php echo htmlspecialchars($last_name ?? ''); ?>"></div>
          
          <div class="form-group"><label>Gender <span class="req">*</span></label>
            <select name="gender_id" required>
              <option value="">Select</option>
              <?php foreach ($genders as $g): ?>
                <option value="<?php echo $g['id']; ?>"><?php echo htmlspecialchars($g['name']); ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          
          <div class="form-group"><label>Date of Birth <span class="req">*</span></label><input type="date" id="dobInput" name="dob" required></div>
          <div class="form-group"><label>Calculated Age</label><input type="text" id="ageOutput" readonly placeholder="Auto-calculated"></div>
          <div class="form-group"><label>Hometown</label><input type="text" name="hometown" placeholder="Ancestral town or origin" value="<?php echo htmlspecialchars($_POST['hometown'] ?? ''); ?>"></div>

          <input type="hidden" name="child_status_id" id="childStatus">

          <div class="form-group" id="babyDependentBox" style="display:none; background: var(--e-yellow); padding:12px; border-radius:6px; border:1px solid var(--e-yellow-border); grid-column: 1 / -1;">
            <label style="color:#92400e;">👶 Infant (0-3 Months): Dependent on Mother's Insurance?</label>
            <select name="is_mother_dependent" id="motherDependentSelect" style="border-color:#fcd34d; font-weight:bold; width: 300px;">
              <?php foreach ($yes_no_options as $yn): ?>
                <option value="<?php echo $yn['id']; ?>" <?php echo ($yn['id'] == 0) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($yn['name']); ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
          
        </div>
      </div>

      <div class="t1-section">
        <div class="t1-header">📍 Contact & Location Profile</div>
        <div class="t1-body">
          <div class="form-group" style="grid-column: span 2;">
            <label>Primary Mobile <span class="req">*</span></label>
            <div class="mobile-group">
              <select name="mobile_prefix" required>
                <option value="">Code</option>
                <?php foreach ($telecoms as $t): ?>
                    <option value="<?php echo htmlspecialchars($t['prefix_code']); ?>"><?php echo htmlspecialchars($t['prefix_code'] . ' - ' . $t['network_name']); ?></option>
                <?php endforeach; ?>
              </select>
              <input type="text" name="mobile_digits" required placeholder="XXXXXXX" maxlength="7" pattern="\d{7}" title="Must be exactly 7 digits">
            </div>
          </div>
          <div class="form-group"><label>Email Address</label><input type="email" name="email" placeholder="patient@example.com" value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>"></div>
          
          <div class="form-group" style="grid-column: span 2;"><label>Residential Address (Street/Landmark)</label><input type="text" name="patient_address" id="main_address" value="<?php echo htmlspecialchars($patient_address ?? ''); ?>"></div>
          <div class="form-group">
              <label>Residential GPS (Ghana Post)</label>
              <input type="text" name="residential_gps" placeholder="e.g. GA-123-4567" pattern="^[A-Za-z]{2}-\d{3,4}-\d{4}$" title="Format: GA-123-4567" value="<?php echo htmlspecialchars($_POST['residential_gps'] ?? ''); ?>" oninput="this.value = this.value.toUpperCase()">
          </div>

          <div class="form-group">
            <label>Region of Residence</label>
            <input type="text" name="region" list="ghana_regions" placeholder="Type to search region..." value="<?php echo htmlspecialchars($_POST['region'] ?? ''); ?>">
          </div>
          <div class="form-group">
            <label>Town / City of Residence</label>
            <input type="text" name="town" list="existing_towns" placeholder="Type to search or enter new town..." value="<?php echo htmlspecialchars($_POST['town'] ?? ''); ?>">
          </div>
        </div>
      </div>

      <div class="t1-section">
        <div class="t1-header">💼 Socio-Economic Data</div>
        <div class="t1-body">
          <div class="form-group"><label>Marital Status</label>
            <select name="marital_status_id"><option value="">Select</option>
              <?php foreach ($maritals as $m): ?><option value="<?php echo $m['id']; ?>"><?php echo htmlspecialchars($m['name']); ?></option><?php endforeach; ?>
            </select>
          </div>
          <div class="form-group"><label>Occupation</label>
            <select name="occupation_id"><option value="">Select</option>
              <?php foreach ($occupations as $o): ?><option value="<?php echo $o['id']; ?>"><?php echo htmlspecialchars($o['name']); ?></option><?php endforeach; ?>
            </select>
          </div>
          <div class="form-group"><label>Education Level</label>
            <select name="education_level_id"><option value="">Select</option>
              <?php foreach ($educations as $e): ?><option value="<?php echo $e['id']; ?>"><?php echo htmlspecialchars($e['name']); ?></option><?php endforeach; ?>
            </select>
          </div>
          <div class="form-group"><label>Religion</label>
            <select name="religion_id"><option value="">Select</option>
              <?php foreach ($religions as $r): ?><option value="<?php echo $r['id']; ?>"><?php echo htmlspecialchars($r['name']); ?></option><?php endforeach; ?>
            </select>
          </div>
          <div class="form-group"><label>Smoking Status</label>
            <select name="smoking_status_id"><option value="">Select</option>
              <?php foreach ($smoking_statuses as $sm): ?><option value="<?php echo $sm['id']; ?>"><?php echo htmlspecialchars($sm['name']); ?></option><?php endforeach; ?>
            </select>
          </div>
          <div class="form-group"><label>Alcohol Status</label>
            <select name="alcohol_status_id"><option value="">Select</option>
              <?php foreach ($alcohol_statuses as $al): ?><option value="<?php echo $al['id']; ?>"><?php echo htmlspecialchars($al['name']); ?></option><?php endforeach; ?>
            </select>
          </div>

          <div class="form-group" style="background:#eff6ff; padding:8px 12px; border-radius:6px; border:1px solid #bfdbfe;">
            <label style="color:#1d4ed8;">Is Patient a Staff Member?</label>
            <select name="is_staff" style="border-color:#93c5fd; font-weight:bold;">
              <?php foreach ($yes_no_options as $yn): ?>
                <option value="<?php echo $yn['id']; ?>" <?php echo ($yn['id'] == 0) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($yn['name']); ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="form-group" style="background:#f0fdf4; padding:8px 12px; border-radius:6px; border:1px solid #bbf7d0;">
            <label style="color:#166534;">Is Patient a Staff Dependent?</label>
            <select name="is_staff_dependent" style="border-color:#86efac; font-weight:bold;">
              <?php foreach ($yes_no_options as $yn): ?>
                <option value="<?php echo $yn['id']; ?>" <?php echo ($yn['id'] == 0) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($yn['name']); ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>

        </div>
      </div>

      <div class="t1-section">
        <div class="t1-header">🛡️ Identification & Insurance</div>
        <div class="t1-body">
          
          <div class="form-group" style="grid-column: span 2;">
              <label>Ghana Card (NIA) - Optional</label>
              <input type="text" name="ghana_card_no" placeholder="e.g. GHA-123456789-0" pattern="^GHA-\d{9}-\d{1}$" title="Format must be strictly GHA-XXXXXXXXX-X" oninput="this.value = this.value.toUpperCase()">
          </div>

          <div class="insurance-selector">
            <label style="margin-bottom:8px; display:block;">Is Patient NHIS or Private Insured?</label>
            <div class="ins-options">
              <label class="ins-radio-label"><input type="radio" name="insurance_category" value="cash" checked onclick="toggleIns('cash')"> Cash / Out of Pocket</label>
              <label class="ins-radio-label"><input type="radio" name="insurance_category" value="nhis" onclick="toggleIns('nhis')"> NHIS Subscriber</label>
              <label class="ins-radio-label"><input type="radio" name="insurance_category" value="private" onclick="toggleIns('private')"> Private / Corporate Insurance </label>
            </div>
          </div>

          <div class="dynamic-field" id="field-nhis">
            <div class="form-group"><label>NHIS Number <span class="req">*</span></label><input type="text" name="nhis_no" id="nhisInput" placeholder="Enter NHIS No."></div>
          </div>

          <div class="dynamic-field" id="field-private">
            <div class="form-group"><label>Private / Corporate Insurance Provider <span class="req">*</span></label>
              <select name="other_insurance_id" id="privateInput">
                <option value="">Choose Provider...</option>
                <?php foreach ($insurances as $i): ?>
                  <option value="<?php echo $i['id']; ?>"><?php echo htmlspecialchars($i['name']); ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="form-group"><label>Member Number <span class="req">*</span></label><input type="text" name="other_insurance_no" id="privateNumInput"></div>
          </div>
          
        </div>
      </div>

      <div class="t1-section" style="border-color: #fca5a5;">
        <div class="t1-header" style="background:#fee2e2; color:#b91c1c;">🚨 Emergency Next of Kin</div>
        <div class="t1-body">
          <div class="form-group"><label>Name</label><input type="text" name="emergency_name"></div>
          <div class="form-group"><label>Phone</label><input type="text" name="emergency_number"></div>
          <div class="form-group"><label>Relationship</label>
            <select name="emergency_relation_id"><option value="">Select</option>
              <?php foreach ($relations as $r): ?><option value="<?php echo $r['id']; ?>"><?php echo htmlspecialchars($r['name']); ?></option><?php endforeach; ?>
            </select>
          </div>
          
          <div class="form-group" style="grid-column: 1 / -1; margin-top:10px;">
            <label class="checkbox-wrap">
                <input type="checkbox" id="same_address_check" name="same_as_patient" value="1">
                Emergency Contact address is the same as Patient's Residential Address
            </label>
          </div>
          <div class="form-group" style="grid-column: 1 / -1;">
            <label>Emergency Contact Address</label>
            <input type="text" name="emergency_address" id="emergency_address_input" placeholder="Enter emergency contact's location...">
          </div>
        </div>
      </div>

      <div class="form-actions">
        <button type="submit" name="submit_action" value="dashboard" class="btn btn-dash">💾 Save & Search</button>
        <button type="submit" name="submit_action" value="save_and_book" class="btn btn-book">📅 Save & Book Appointment</button>
      </div>

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

<div class="modal-overlay" id="successModal">
  <div class="modal-content">
    <div class="modal-icon">✅</div>
    <div class="modal-title">Registration Successful</div>
    <div class="modal-details">
      <p><span>Patient ID:</span> <strong id="popPatientId" style="color:var(--e-blue); font-family:monospace; font-size:16px;"></strong></p>
      <p><span>Full Name:</span> <strong id="popPatientName"></strong></p>
      <p><span>Insurance Details:</span> <strong id="popInsuranceDetails" style="text-align:right;"></strong></p>
    </div>
    <button class="btn-modal-ok" id="btnModalOk">Okay, Continue</button>
  </div>
</div>

<div class="modal-overlay" id="errorModal">
  <div class="modal-content" style="border-top: 5px solid var(--e-red);">
    <div class="modal-icon error"><i class="fa-solid fa-circle-xmark"></i></div>
    <div class="modal-title" style="color:var(--e-red);">Validation Error</div>
    <div class="modal-details" style="background:#fee2e2; border-color:#fca5a5;">
      <p style="color:#991b1b; text-align:left; display:block; font-size:14px; line-height:1.6;" id="popErrorMessage"></p>
    </div>
    <button class="btn-modal-ok" style="background:var(--e-red);" onclick="document.getElementById('errorModal').classList.remove('active')">Review & Fix</button>
  </div>
</div>

<script>
// --- MODAL TRIGGER LOGIC ---
const successData = <?php echo json_encode($success_data); ?>;
const serverError = <?php echo json_encode($error_message); ?>;

if (serverError && serverError.trim() !== '') {
    document.getElementById('popErrorMessage').innerHTML = serverError;
    document.getElementById('errorModal').classList.add('active');
} else if (successData) {
    document.getElementById('popPatientId').innerText = successData.patient_no;
    document.getElementById('popPatientName').innerText = successData.patient_name;
    document.getElementById('popInsuranceDetails').innerHTML = successData.insurance_details;
    
    document.getElementById('successModal').classList.add('active');

    document.getElementById('btnModalOk').addEventListener('click', function() {
        window.location.href = successData.redirect_url;
    });
}

// --- FORM UI LOGIC ---
const childStatuses = <?php echo $children_json; ?>;
function getChildStatusId(searchTerm) {
  let matchedId = null;
  childStatuses.forEach(status => {
    if(status.name.toLowerCase().includes(searchTerm.toLowerCase())) matchedId = status.id;
  });
  return matchedId;
}

function toggleIns(type) {
  document.querySelectorAll('.dynamic-field').forEach(f => f.classList.remove('open'));
  if(type === 'nhis') document.getElementById('field-nhis').classList.add('open');
  if(type === 'private') document.getElementById('field-private').classList.add('open');
}

// Emergency Address Lock Logic
document.getElementById('same_address_check').addEventListener('change', function() {
    const emergInput = document.getElementById('emergency_address_input');
    if (this.checked) {
        emergInput.value = 'Same as Patient';
        emergInput.disabled = true;
    } else {
        emergInput.value = '';
        emergInput.disabled = false;
    }
});

document.getElementById('dobInput').addEventListener('change', function() {
  const dob = new Date(this.value); 
  const today = new Date();
  if(!this.value || dob > today) return;

  let ageYears = today.getFullYear() - dob.getFullYear();
  let ageMonths = today.getMonth() - dob.getMonth();
  if (ageMonths < 0 || (ageMonths === 0 && today.getDate() < dob.getDate())) { 
      ageYears--; ageMonths += 12; 
  }
  
  const diffDays = Math.ceil(Math.abs(today - dob) / (1000 * 60 * 60 * 24));
  
  document.getElementById('ageOutput').value = ageYears > 0 ? `${ageYears} Yrs` : (ageMonths > 0 ? `${ageMonths} Mos` : `${diffDays} Days`);

  // Secretly assign the child status id for the database
  const hiddenChildStatus = document.getElementById('childStatus');
  if(ageYears === 0) hiddenChildStatus.value = getChildStatusId('Infant') || ""; 
  else if (ageYears >= 1 && ageYears <= 12) hiddenChildStatus.value = getChildStatusId('Child') || "";
  else if (ageYears >= 13 && ageYears <= 17) hiddenChildStatus.value = getChildStatusId('Teenager') || "";
  else hiddenChildStatus.value = getChildStatusId('Adult') || "";

  // Show the Mother Dependent dropdown ONLY if baby is <= 92 days
  const babyBox = document.getElementById('babyDependentBox');
  if (diffDays <= 92) {
      babyBox.style.display = 'block';
  } else {
      babyBox.style.display = 'none';
      document.getElementById('motherDependentSelect').value = '0';
  }
});

// Front-end Validation Fallback
document.getElementById('regForm').addEventListener('submit', function(e) {
  const isNhis = document.querySelector('input[value="nhis"]').checked;
  const isPrivate = document.querySelector('input[value="private"]').checked;
  
  if (isNhis && !document.getElementById('nhisInput').value.trim()) {
    e.preventDefault(); 
    alert('Please enter the NHIS Number before saving.');
    document.getElementById('nhisInput').focus();
  }
  if (isPrivate && (!document.getElementById('privateInput').value || !document.getElementById('privateNumInput').value.trim())) {
    e.preventDefault(); 
    alert('Please select a Private / Corporate Insurance Provider and enter the Member Number before saving.');
  }
});
</script>
</body>
</html>