<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

/* ================= Session Timeout (12 hours) ================= */
$SESSION_TIMEOUT = 43200;

if (isset($_SESSION['LAST_ACTIVITY'])) {
    if (time() - $_SESSION['LAST_ACTIVITY'] > $SESSION_TIMEOUT) {
        session_unset();
        session_destroy();
        header("Location: login.php?timeout=1");
        exit;
    }
}
$_SESSION['LAST_ACTIVITY'] = time();

include('includes/db.php');
include('includes/header.php');


// ---------------- CSRF Token ----------------
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

// ---------------- Facility Context ----------------
if (empty($_SESSION['facility_id'])) {
    $_SESSION['flash'] = ['message' => 'No facility assigned to your account.', 'color' => '#dc3545'];
    header('Location: login.php');
    exit;
}
$facility_id = (int) $_SESSION['facility_id'];



// ---------------- Helpers ----------------
function is_valid_rwanda_phone($phone) {
    return preg_match('/^07\d{8}$/', $phone);
}

function calculate_age($dob) {
    if (!$dob) return '';
    return (new DateTime())->diff(new DateTime($dob))->y;
}

function e($value) {
    return htmlspecialchars((string)($value ?? ''), ENT_QUOTES, 'UTF-8');
}


// ---------------- Handle CRUD ----------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!isset($_POST['csrf']) || $_POST['csrf'] !== $_SESSION['csrf_token']) {
        die("Invalid CSRF token");
    }

    // ---------- CREATE PATIENT ----------
    if (isset($_POST['create'])) {

        $first_name = trim($_POST['first_name'] ?? '');
        $middle_name = trim($_POST['middle_name'] ?? '');
        $last_name = trim($_POST['last_name'] ?? '');
        $d_o_b = $_POST['d_o_b'] ?? null;
        $gender = $_POST['gender'] ?? null;
        $marital_status = $_POST['marital_status'] ?? null;
        $nationality = trim($_POST['nationality'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $secondary_phone = trim($_POST['secondary_phone'] ?? '');
        $emergency_contact_name = trim($_POST['emergency_contact_name'] ?? '');
        $emergency_contact_phone = trim($_POST['emergency_contact_phone'] ?? '');
        $country = trim($_POST['country'] ?? '');
        $province = trim($_POST['province'] ?? '');
        $district = trim($_POST['district'] ?? '');
        $sector = trim($_POST['sector'] ?? '');
        $cell = trim($_POST['cell'] ?? '');
        $village = trim($_POST['village'] ?? '');

        // -------- Validations --------
        if ($first_name === '' || $last_name === '' || !$d_o_b || !$gender) {
            $_SESSION['flash'] = ['message'=>'Required fields missing', 'color'=>'#dc3545'];
            header('Location: '.$_SERVER['PHP_SELF']); exit;
        }

        if (!is_valid_rwanda_phone($phone)) {
            $_SESSION['flash'] = ['message'=>'Invalid primary phone number', 'color'=>'#dc3545'];
            header('Location: '.$_SERVER['PHP_SELF']); exit;
        }

        if ($emergency_contact_phone && !is_valid_rwanda_phone($emergency_contact_phone)) {
            $_SESSION['flash'] = ['message'=>'Invalid emergency phone number', 'color'=>'#dc3545'];
            header('Location: '.$_SERVER['PHP_SELF']); exit;
        }

        try {
            $pdo->beginTransaction();

            // Fetch facility
            $stmtFacility = $pdo->prepare("SELECT name FROM facility WHERE id = ?");
            $stmtFacility->execute([$facility_id]);
            $facility = $stmtFacility->fetch(PDO::FETCH_ASSOC);

            if (!$facility) {
                throw new Exception('Facility not found');
            }

            $facility_abbr = strtoupper(implode('', array_map(
                fn($w) => $w[0],
                explode(' ', $facility['name'])
            )));

            $current_year = date('Y');

            // ---- SAFE FILE ID GENERATION ----
            $stmtLast = $pdo->prepare("
                SELECT file_id
                FROM patients
                WHERE facility_id = ?
                  AND file_id LIKE ?
                ORDER BY id DESC
                LIMIT 1
            ");
            $stmtLast->execute([
                $facility_id,
                $facility_abbr . '-' . $current_year . '-%'
            ]);

            $lastFileId = $stmtLast->fetchColumn();
            $nextNumber = $lastFileId ? ((int) substr($lastFileId, -4)) + 1 : 1;
            $file_id = $facility_abbr . '-' . $current_year . '-' . str_pad($nextNumber, 4, '0', STR_PAD_LEFT);

            // ---- INSERT PATIENT ----
            $stmt = $pdo->prepare("
                INSERT INTO patients
                (file_id, facility_id, first_name, middle_name, last_name, d_o_b, gender, marital_status, nationality,
                 phone, secondary_phone, emergency_contact_name, emergency_contact_phone,
                 country, province, district, sector, cell, village)
                VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
            ");

            $stmt->execute([
                $file_id, $facility_id,
                $first_name, $middle_name ?: null, $last_name,
                $d_o_b, $gender, $marital_status ?: null, $nationality ?: null,
                $phone, $secondary_phone ?: null,
                $emergency_contact_name ?: null, $emergency_contact_phone ?: null,
                $country ?: null, $province ?: null, $district ?: null,
                $sector ?: null, $cell ?: null, $village ?: null
            ]);

            $pdo->commit();

            $_SESSION['flash'] = [
                'message' => "Patient added successfully! File ID: $file_id",
                'color' => '#28a745'
            ];

        } catch (Throwable $e) {
            $pdo->rollBack();
            $_SESSION['flash'] = [
                'message' => 'Failed to create patient. Please try again.',
                'color' => '#dc3545'
            ];
        }

        header('Location: '.$_SERVER['PHP_SELF']);
        exit;
    }

    // ---------- UPDATE PATIENT (UNCHANGED LOGIC) ----------
    if (isset($_POST['update'])) {

        $id = (int) ($_POST['id'] ?? 0);
        if ($id <= 0) {
            $_SESSION['flash'] = ['message'=>'Invalid patient ID', 'color'=>'#dc3545'];
            header('Location: '.$_SERVER['PHP_SELF']); exit;
        }

        $stmtCheck = $pdo->prepare("SELECT 1 FROM patients WHERE id=? AND facility_id=?");
        $stmtCheck->execute([$id, $facility_id]);

        if (!$stmtCheck->fetchColumn()) {
            $_SESSION['flash'] = ['message'=>'Unauthorized update', 'color'=>'#dc3545'];
            header('Location: '.$_SERVER['PHP_SELF']); exit;
        }

        $stmt = $pdo->prepare("
            UPDATE patients SET
            first_name=?, middle_name=?, last_name=?, d_o_b=?, gender=?, marital_status=?, nationality=?,
            phone=?, secondary_phone=?, emergency_contact_name=?, emergency_contact_phone=?,
            country=?, province=?, district=?, sector=?, cell=?, village=?
            WHERE id=?
        ");

        $stmt->execute([
            trim($_POST['first_name']), trim($_POST['middle_name']) ?: null, trim($_POST['last_name']),
            $_POST['d_o_b'], $_POST['gender'], $_POST['marital_status'] ?: null, $_POST['nationality'] ?: null,
            $_POST['phone'], $_POST['secondary_phone'] ?: null,
            $_POST['emergency_contact_name'] ?: null, $_POST['emergency_contact_phone'] ?: null,
            $_POST['country'] ?: null, $_POST['province'] ?: null, $_POST['district'] ?: null,
            $_POST['sector'] ?: null, $_POST['cell'] ?: null, $_POST['village'] ?: null,
            $id
        ]);

        $_SESSION['flash'] = ['message'=>'Patient updated successfully!', 'color'=>'#28a745'];
        header('Location: '.$_SERVER['PHP_SELF']);
        exit;
    }
}

// ---------------- Fetch Patients ----------------
$stmt = $pdo->prepare("
    SELECT p.*, f.name AS facility_name,
           CASE
               WHEN p.d_o_b IS NULL OR p.d_o_b = '0000-00-00' THEN NULL
               WHEN TIMESTAMPDIFF(YEAR, p.d_o_b, CURDATE()) >= 1 
                   THEN CONCAT(TIMESTAMPDIFF(YEAR, p.d_o_b, CURDATE()), ' Year', 
                               IF(TIMESTAMPDIFF(YEAR, p.d_o_b, CURDATE()) > 1, 's', ''))
               ELSE CONCAT(TIMESTAMPDIFF(MONTH, p.d_o_b, CURDATE()), ' Month', 
                           IF(TIMESTAMPDIFF(MONTH, p.d_o_b, CURDATE()) > 1, 's', ''))
           END AS age
    FROM patients p
    LEFT JOIN facility f ON p.facility_id = f.id
    WHERE p.facility_id = ?
    ORDER BY p.id DESC
");

$stmt->execute([$facility_id]);
$patients = $stmt->fetchAll(PDO::FETCH_ASSOC);

$currentPage = basename($_SERVER['PHP_SELF']);
?>




<!-- Navbar and Sidebar -->
<nav class="header-navbar navbar navbar-with-menu navbar-fixed-top navbar-semi-dark navbar-shadow">
  <?php include('includes/navbar.php'); ?>
</nav>
<div class="main-menu menu-fixed menu-dark menu-accordion menu-shadow">
  <?php include('includes/sidebar.php'); ?>
</div>

<div class="app-content content container-fluid">
  <div class="content-wrapper">
    <div class="col-xs-12">
      <div class="card">
        <div class="card-header">
          <h4 class="card-title">Patients Management</h4>
        </div>
        <div class="card-body collapse in">
          <div class="card-block card-dashboard">
            <div class="row mb-2">
              <div class="col-lg-4 col-md-6 col-sm-12">
                <button type="button" class="btn btn-outline-primary btn-md" data-toggle="modal" data-target="#addPatientModal">Add Patient</button>
              </div>
            </div>

            <div class="table-responsive">
              <table class="table table-hover mb-0" id="Table">
                <thead>
                  <tr>
                    <th>File ID</th>
                    <th>Full Name</th>
                    <th>Gender & Age</th>
                    <th>Phone</th>
                    <th>Address Info</th>
                    <th>Emergency Contact</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tbody>
                  <?php $counter = 1; foreach($patients as $p): ?>
                  <tr>
                    <td><?= htmlspecialchars($p['file_id']) ?></td>
                    <td><?= htmlspecialchars($p['first_name'] . ' ' . ($p['middle_name'] ? $p['middle_name'].' ' : '') . $p['last_name']) ?></td>
                    
                    <td>
                        <div><?= htmlspecialchars($p['gender']) ?></div>
                        <div>
                            <?php
$dob = $p['d_o_b'] ?? null;

if ($dob && $dob !== '0000-00-00') {
    $birthDate = new DateTime($dob);
    $today = new DateTime();
    $diff = $today->diff($birthDate);

    if ($diff->y >= 1) {
        // 1 year or more → show years only
        echo htmlspecialchars($diff->y) . ' Year' . ($diff->y > 1 ? 's' : '');
    } elseif ($diff->m >= 1) {
        // Less than 1 year but ≥ 1 month → show months only
        $months = $diff->m + ($diff->y * 12); // diff->y is 0 here, just in case
        echo htmlspecialchars($months) . ' Month' . ($months > 1 ? 's' : '');
    } else {
        // Less than 1 month → show days
        $days = $diff->d;
        echo htmlspecialchars($days) . ' Day' . ($days > 1 ? 's' : '');
    }
}
?>

                        </div>
                    </td>
                    <td><?= htmlspecialchars($p['phone'] . ' ' . $p['secondary_phone'] . '') ?></td>
                   <td>
    <?=
        '<div>' . htmlspecialchars($p['country']  ?? '', ENT_QUOTES, 'UTF-8') . '</div>' .
        '<div>' . htmlspecialchars($p['province'] ?? '', ENT_QUOTES, 'UTF-8') . '</div>' .
        '<div>' . htmlspecialchars($p['district'] ?? '', ENT_QUOTES, 'UTF-8') . '</div>' .
        '<div>' . htmlspecialchars($p['sector']   ?? '', ENT_QUOTES, 'UTF-8') . '</div>' .
        '<div>' . htmlspecialchars($p['cell']     ?? '', ENT_QUOTES, 'UTF-8') . '</div>' .
        '<div>' . htmlspecialchars($p['village']  ?? '', ENT_QUOTES, 'UTF-8') . '</div>'
    ?>
</td>


                    <td><?= htmlspecialchars($p['emergency_contact_name'] . ' ' . $p['emergency_contact_phone'] . '') ?></td>
                    <td>
                      <div class="d-flex gap-2">
                        <button class="btn btn-sm btn-primary"
                                data-toggle="modal"
                                data-target="#editModal<?= $p['id'] ?>">
                          Edit
                        </button>

                        <a href="view_patient.php?id=<?= $p['id'] ?>" 
                           class="btn btn-sm btn-info">
                          View
                        </a>

                        <a href="new_visit.php?patient_id=<?= $p['id'] ?>" 
                           class="btn btn-sm btn-success">
                          New Visit
                        </a>
                      </div>
                    </td>
                  </tr>

                  <!-- Edit Modal -->
                  <div class="modal fade" id="editModal<?= $p['id'] ?>" tabindex="-1">
  <div class="modal-dialog modal-md">
    <div class="modal-content">
      <form method="post" class="patient-form" data-mode="edit">
        <input type="hidden" name="csrf" value="<?= e($csrf) ?>">
        <input type="hidden" name="id" value="<?= (int)$p['id'] ?>">

        <div class="modal-header">
          <h4>Edit Patient</h4>
        </div>

        <div class="modal-body">

          <!-- Names -->
          <div class="row">
            <div class="col-md-4">
              <label>First Name *</label>
              <input type="text" name="first_name" class="form-control validate-required"
                     value="<?= e($p['first_name']) ?>">
            </div>

            <div class="col-md-4">
              <label>Middle Name</label>
              <input type="text" name="middle_name" class="form-control"
                     value="<?= e($p['middle_name']) ?>">
            </div>

            <div class="col-md-4">
              <label>Last Name *</label>
              <input type="text" name="last_name" class="form-control validate-required"
                     value="<?= e($p['last_name']) ?>">
            </div>
          </div>

          <!-- DOB / Gender / Marital -->
          <div class="row mt-2">
            <div class="col-md-4">
              <label>D.O.B *</label>
              <input type="date" name="d_o_b" class="form-control validate-required"
                     value="<?= e($p['d_o_b']) ?>">
            </div>

            <div class="col-md-4">
              <label>Gender *</label>
              <select name="gender" class="form-control validate-required">
                <option value="">-- Select Gender --</option>
                <option value="Male"   <?= $p['gender'] === 'Male' ? 'selected' : '' ?>>Male</option>
                <option value="Female" <?= $p['gender'] === 'Female' ? 'selected' : '' ?>>Female</option>
                <option value="Other"  <?= $p['gender'] === 'Other' ? 'selected' : '' ?>>Other</option>
              </select>
            </div>

            <div class="col-md-4">
              <label>Marital Status</label>
              <select name="marital_status" class="form-control">
                <option value="">-- Select Status --</option>
                <option value="Single"   <?= $p['marital_status'] === 'Single' ? 'selected' : '' ?>>Single</option>
                <option value="Married"  <?= $p['marital_status'] === 'Married' ? 'selected' : '' ?>>Married</option>
                <option value="Divorced" <?= $p['marital_status'] === 'Divorced' ? 'selected' : '' ?>>Divorced</option>
                <option value="Widowed"  <?= $p['marital_status'] === 'Widowed' ? 'selected' : '' ?>>Widowed</option>
              </select>
            </div>
          </div>

          <!-- Phones -->
          <div class="row mt-2">
            <div class="col-md-4">
              <label>Nationality</label>
              <input type="text" name="nationality" class="form-control"
                     value="<?= e($p['nationality']) ?>">
            </div>

            <div class="col-md-4">
              <label>Primary Phone *</label>
              <input type="text" name="phone" class="form-control validate-phone"
                     value="<?= e($p['phone']) ?>">
            </div>

            <div class="col-md-4">
              <label>Secondary Phone</label>
              <input type="text" name="secondary_phone" class="form-control validate-optional-phone"
                     value="<?= e($p['secondary_phone']) ?>">
            </div>
          </div>

          <!-- Emergency -->
          <div class="row mt-2">
            <div class="col-md-6">
              <label>Emergency Contact Name</label>
              <input type="text" name="emergency_contact_name" class="form-control"
                     value="<?= e($p['emergency_contact_name']) ?>">
            </div>

            <div class="col-md-6">
              <label>Emergency Contact Phone</label>
              <input type="text" name="emergency_contact_phone" class="form-control validate-optional-phone"
                     value="<?= e($p['emergency_contact_phone']) ?>">
            </div>
          </div>

          <!-- Address (ALL OPTIONAL) -->
          <div class="row mt-2">
            <div class="col-md-4">
              <label>Country of Residence</label>
              <input type="text" name="country" class="form-control" value="<?= e($p['country']) ?>">
            </div>

            <div class="col-md-4">
              <label>Province/State</label>
              <input type="text" name="province" class="form-control" value="<?= e($p['province']) ?>">
            </div>

            <div class="col-md-4">
              <label>District</label>
              <input type="text" name="district" class="form-control" value="<?= e($p['district']) ?>">
            </div>
          </div>

          <div class="row mt-2">
            <div class="col-md-4">
              <label>Sector</label>
              <input type="text" name="sector" class="form-control" value="<?= e($p['sector']) ?>">
            </div>

            <div class="col-md-4">
              <label>Cell</label>
              <input type="text" name="cell" class="form-control" value="<?= e($p['cell']) ?>">
            </div>

            <div class="col-md-4">
              <label>Village</label>
              <input type="text" name="village" class="form-control" value="<?= e($p['village']) ?>">
            </div>
          </div>

        </div>

        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary btn-md" data-dismiss="modal">
            Close
          </button>
          <button type="submit" name="update" class="btn btn-outline-primary btn-md">
            Update
          </button>
        </div>

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


                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Add Patient Modal -->
<div class="modal fade" id="addPatientModal" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <form method="post" id="addPatientForm" class="patient-form" data-mode="add">
        <input type="hidden" name="csrf" value="<?= $csrf ?>">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <label class="modal-title">Add Patient</label>
        </div>

        <div class="modal-body">


          <!-- Rest of Add Patient fields remain intact -->
          <div class="row">
            <div class="col-md-4">
              <label>First Name *</label>
              <input type="text" name="first_name" class="form-control validate-required" placeholder="First name">
              <small class="invalid-feedback"></small>
            </div>
            <div class="col-md-4">
              <label>Middle Name</label>
              <input type="text" name="middle_name" class="form-control" placeholder="Middle name">
              <small class="invalid-feedback"></small>
            </div>
            <div class="col-md-4">
              <label>Last Name *</label>
              <input type="text" name="last_name" class="form-control validate-required" placeholder="Last name">
              <small class="invalid-feedback"></small>
            </div>
          </div>

          <div class="row mt-2">
            <div class="col-md-4">
              <label>D.O.B *</label>
              <input type="date" name="d_o_b" class="form-control validate-required" required>
              <small class="invalid-feedback"></small>
            </div>
            <div class="col-md-4">
              <label>Gender *</label>
              <select name="gender" class="form-control validate-required" required>
                <option value="">-- Select Gender --</option>
                <option value="male">Male</option>
                <option value="female">Female</option>
                <option value="other">Other</option>
              </select>
              <small class="invalid-feedback"></small>
            </div>
            <div class="col-md-4">
              <label>Marital Status</label>
              <select name="marital_status" class="form-control">
                <option value="">-- Select Status --</option>
                <option value="single">Single</option>
                <option value="married">Married</option>
                <option value="divorced">Divorced</option>
                <option value="widowed">Widowed</option>
              </select>
            </div>
          </div>

          <div class="row mt-2">
            <div class="col-md-4">
              <label>Nationality</label>
              <input type="text" name="nationality" class="form-control" placeholder="Nationality">
            </div>
            <div class="col-md-4">
              <label>Primary Phone *</label>
              <input type="text" name="phone" class="form-control validate-phone" placeholder="07XXXXXXXX" required>
              <small class="invalid-feedback"></small>
            </div>
            <div class="col-md-4">
              <label>Secondary Phone</label>
              <input type="text" name="secondary_phone" class="form-control" placeholder="07XXXXXXXX">
            </div>
          </div>

          <div class="row mt-2">
            <div class="col-md-6">
              <label>Emergency Contact Name</label>
              <input type="text" 
                     name="emergency_contact_name" 
                     class="form-control" 
                     placeholder="Emergency contact">
            </div>
            <div class="col-md-6">
              <label>Emergency Contact Phone</label>
              <input type="text" 
                     name="emergency_contact_phone" 
                     class="form-control" 
                     placeholder="07XXXXXXXX">
            </div>
          </div>

          <!-- Address Section - ALL OPTIONAL -->
          <div class="row mt-2">
            <div class="col-md-4">
              <label>Country of Residence</label>
              <input type="text" name="country" class="form-control" placeholder="Country" value="Rwanda">
            </div>
            <div class="col-md-4">
              <label>Kigali City / Province</label>
              <select name="province" class="form-control" id="province-select">
                <option value="">-- Select Province (Optional) --</option>
                <option value="Eastern Province">Eastern Province</option>
                <option value="Northern Province">Northern Province</option>
                <option value="Western Province">Western Province</option>
                <option value="Southern Province">Southern Province</option>
                <option value="Kigali">Kigali</option>
              </select>
            </div>
            <div class="col-md-4">
              <label>District</label>
              <select name="district" class="form-control" id="district-select">
                <option value="">-- Select District (Optional) --</option>
              </select>
            </div>
          </div>

          <div class="row mt-2">
            <div class="col-md-4">
              <label>Sector</label>
              <select name="sector" class="form-control" id="sector-select">
                <option value="">-- Select Sector (Optional) --</option>
              </select>
            </div>
            <div class="col-md-4">
              <label>Cell</label>
              <input type="text" name="cell" class="form-control" placeholder="Cell (Optional)">
            </div>
            <div class="col-md-4">
              <label>Village</label>
              <input type="text" name="village" class="form-control" placeholder="Village (Optional)">
            </div>
          </div>

        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary btn-md" data-dismiss="modal">Close</button>
          <button type="submit" name="create" class="btn btn-outline-primary btn-md form-submit-btn">Save</button>
        </div>
      </form>
    </div>
  </div>
</div>


<style>
.toast-message{
  position:fixed;
  top:20px;
  right:20px;
  z-index:9999;
  padding:.75rem 1rem;
  border-radius:.25rem;
  opacity:0.95;
  color: #fff;
  font-weight: 600;
  box-shadow: 0 2px 6px rgba(0,0,0,0.2);
}
.invalid-feedback { color: #dc3545; display:block; margin-top:4px; }
</style>

<script>
// Complete Rwanda Address Data - Using the exact structure you provided
const rwandaData = {
  "Eastern Province": {
    "Nyagatare": ["Rwimiyaga", "Karangazi", "Nyagatare", "Katabagemu", "Rukomo", "Tabagwe", "Musheli", "Gatunda", "Mimuli", "Karama", "Matimba", "Mukama", "Rwempasha", "Kiyombe"],
    "Bugesera": ["Gashora", "Juru", "Kamabuye", "Ntarama", "Mareba", "Mayange", "Musenyi", "Mwogo", "Ngeruka", "Nyamata", "Nyarugenge", "Rilima", "Ruhuha", "Rweru"],
    "Ngoma": ["Gashanda", "Jarama", "Karembo", "Kazo", "Kibungo", "Mugesera", "Murama", "Mutenderi", "Remera", "Rukira", "Rukumberi", "Rurenge", "Sake", "Zaza"],
    "Rwamagana": ["Fumbwe", "Gahengeri", "Gishari", "Karenge", "Kigabiro", "Muhazi", "Munyaga", "Munyiginya", "Musha", "Muyumbu", "Mwulire", "Nyakariro", "Nzige", "Rubona", "Shyara"],
    "Gatsibo": ["Gasange", "Gatsibo", "Gitoki", "Kabarore", "Kageyo", "Kiramuruzi", "Kiziguro", "Muhura", "Murambi", "Ngarama", "Nyagihanga", "Remera", "Rugarama", "Rwimbogo"],
    "Kayonza": ["Gahini", "Kabare", "Kabarondo", "Mukarange", "Murama", "Murundi", "Mwiri", "Ndego", "Nyamirama", "Rukara", "Ruramira", "Rwinkwavu"],
    "Kirehe": ["Gahara", "Gatore", "Kigarama", "Kigina", "Kirehe", "Mahama", "Mpanga", "Musaza", "Mushikiri", "Nasho", "Nyamugari", "Nyarubuye"]
  },
  "Northern Province": {
    "Burera": ["Bungwe", "Butaro", "Cyanika", "Cyeru", "Gahunga", "Gatebe", "Gitovu", "Kagogo", "Kinoni", "Kinyababa", "Kivuye", "Nemba", "Rugarama", "Rugendabari", "Ruhunde", "Rusarabuge", "Rwerere"],
    "Gicumbi": ["Bukure", "Bwisige", "Byumba", "Cyumba", "Giti", "Kaniga", "Manyagiro", "Miyove", "Kageyo", "Muko", "Mutete", "Nyamiyaga", "Nyankenke II", "Rubaya", "Rukomo", "Rushaki"],
    "Rulindo": ["Base", "Burega", "Bushoki", "Buyoga", "Cyinzuzi", "Cyungo", "Kinihira", "Kisaro", "Masoro", "Mukarange", "Mbogo", "Murambi", "Ngoma", "Ntarabana", "Rukozo", "Rusiga", "Shyorongi", "Tumba"],
    "Gakenke": ["Busengo", "Coko", "Cyabingo", "Gakenke", "Gashenyi", "Mugunga", "Janja", "Kamubuga", "Karambo", "Kivuruga", "Mataba", "Minazi", "Muhondo", "Muyongwe", "Muzo", "Nemba", "Ruli", "Rusasa", "Rushashi"],
    "Musanze": ["Busogo", "Cyuve", "Gacaca", "Gashaki", "Gataraga", "Kimonyi", "Kinigi", "Muhoza", "Muko", "Musanze", "Nkotsi", "Nyange", "Remera", "Rwaza", "Shingiro"]
  },
  "Western Province": {
    "Karongi": ["Bwishyura", "Gishyita", "Gishari", "Gitesi", "Mubuga", "Murambi", "Murundi", "Mutuntu", "Rubengera", "Rugabano", "Ruganda", "Rwankuba", "Twumba"],
    "Nyabihu": ["Bigogwe", "Jenda", "Jomba", "Kabatwa", "Karago", "Kintobo", "Mukamira", "Muringa", "Rambura", "Rugera", "Rurembo", "Shyira"],
    "Rubavu": ["Bugeshi", "Busasamana", "Cyanzarwe", "Gisenyi", "Kanama", "Kanzenze", "Mudende", "Nyakiliba", "Nyamyumba", "Nyundo", "Rubavu", "Rugerero"],
    "Rutsiro": ["Boneza", "Gihango", "Kigeyo", "Kivumu", "Manihira", "Mukura", "Musasa", "Mushonyi", "Mushubati", "Nyabirasi", "Ruhango", "Rusebeya"],
    "Nyamasheke": ["Ruharambuga", "Bushekeri", "Bushenge", "Cyato", "Gihombo", "Kagano", "Kanjongo", "Karambi", "Kirimbi", "Macuba", "Mahembe", "Nyabitekeri", "Rangiro", "Shangi"],
    "Rusizi": ["Bugarama", "Butare", "Bweyeye", "Gikundamvura", "Gashonga", "Giheke", "Gihundwe", "Gitambi", "Kamembe", "Karengera", "Muganza", "Mururu", "Nkanka", "Nkombo", "Nkungu", "Nyakabuye", "Nyakarenzo", "Nzahaha", "Rwimbogo"]
  },
  "Southern Province": {
    "Gisagara": ["Gikonko", "Gishubi", "Kansi", "Kibilizi", "Kigembe", "Mamba", "Muganza", "Mugombwa", "Mukindo", "Musha", "Ndora", "Nyanza", "Save"],
    "Kamonyi": ["Gacurabwenge", "Karama", "Kayenzi", "Kayumbu", "Mugina", "Musambira", "Ngamba", "Nyamiyaga", "Nyarubaka", "Rugalika", "Rukoma", "Runda"],
    "Nyamagabe": ["Buruhukiro", "Cyanika", "Gatare", "Kaduha", "Kamegeli", "Kibirizi", "Kibumbwe", "Kitabi", "Mbazi", "Mugano", "Musange", "Musebeya", "Mushubi", "Gasaka", "Tare", "Uwinkingi"],
    "Nyaruguru": ["Cyahinda", "Busanze", "Kibeho", "Mata", "Munini", "Kivu", "Ngera", "Ngoma", "Nyabimata", "Nyagisozi", "Muganza", "Ruheru", "Ruramba", "Rusenge"]
  },
  "Kigali": {
    "Gasabo": ["Bumbogo", "Gatsata", "Jali", "Gikomero", "Gisozi", "Jabana", "Kinyinya", "Ndera", "Nduba", "Rusororo", "Rutunga", "Kacyiru", "Kimihurura", "Kimironko", "Remera"],
    "Kicukiro": ["Gahanga", "Gatenga", "Gikondo", "Kagarama", "Kanombe", "Kicukiro", "Masaka", "Niboye", "Nyarugunga"],
    "Nyarugenge": ["Gitega", "Kanyinya", "Kigali", "Kimisagara", "Mageragere", "Muhima", "Nyakabanda", "Nyamirambo", "Nyarugenge", "Rwezamenyo"]
  }
};

// Optional Address Dropdown Management
function initializeAddressDropdowns() {
    const provinceSelect = document.getElementById('province-select');
    const districtSelect = document.getElementById('district-select');
    const sectorSelect = document.getElementById('sector-select');
    
    if (!provinceSelect) return;
    
    // Initialize district select with empty option
    districtSelect.innerHTML = '<option value="">-- Select District (Optional) --</option>';
    sectorSelect.innerHTML = '<option value="">-- Select Sector (Optional) --</option>';
    
    // Province change - OPTIONAL
    provinceSelect.addEventListener('change', function() {
        const province = this.value;
        
        // Clear downstream selects
        districtSelect.innerHTML = '<option value="">-- Select District (Optional) --</option>';
        sectorSelect.innerHTML = '<option value="">-- Select Sector (Optional) --</option>';
        
        if (province && rwandaData[province]) {
            // Populate districts for selected province
            Object.keys(rwandaData[province]).forEach(district => {
                const option = document.createElement('option');
                option.value = district;
                option.textContent = district;
                districtSelect.appendChild(option);
            });
        } else {
            // If no province selected or empty, show all districts from all provinces
            districtSelect.innerHTML = '<option value="">-- Select District (Optional) --</option>';
            const allDistricts = new Set();
            
            // Collect all unique districts from all provinces
            Object.values(rwandaData).forEach(provinceData => {
                Object.keys(provinceData).forEach(district => {
                    allDistricts.add(district);
                });
            });
            
            // Add all districts to dropdown
            allDistricts.forEach(district => {
                const option = document.createElement('option');
                option.value = district;
                option.textContent = district;
                districtSelect.appendChild(option);
            });
        }
    });
    
    // District change - OPTIONAL
    districtSelect.addEventListener('change', function() {
        const district = this.value;
        const province = provinceSelect.value;
        
        // Clear sector
        sectorSelect.innerHTML = '<option value="">-- Select Sector (Optional) --</option>';
        
        if (district) {
            if (province && rwandaData[province] && rwandaData[province][district]) {
                // Populate sectors for selected district in selected province
                rwandaData[province][district].forEach(sector => {
                    const option = document.createElement('option');
                    option.value = sector;
                    option.textContent = sector;
                    sectorSelect.appendChild(option);
                });
            } else {
                // If no province selected or district not in selected province,
                // find sectors from any province that has this district
                const allSectors = new Set();
                
                Object.values(rwandaData).forEach(provinceData => {
                    if (provinceData[district]) {
                        provinceData[district].forEach(sector => {
                            allSectors.add(sector);
                        });
                    }
                });
                
                // Add all sectors to dropdown
                allSectors.forEach(sector => {
                    const option = document.createElement('option');
                    option.value = sector;
                    option.textContent = sector;
                    sectorSelect.appendChild(option);
                });
            }
        }
    });
}

// Form Validation - REMOVED validation for address fields
(function(){
  const rwandaPhoneRe = /^07\d{8}$/;

  function validateInput(input) {
    const val = (input.value || "").trim();
    const feedback = input.parentElement.querySelector(".invalid-feedback");
    let ok = true;
    let msg = "";

    // Only validate required fields and phone numbers
    // Address fields are optional, so no validation needed
    
    if (input.classList.contains("validate-required")) {
      if (val === "") { ok = false; msg = "This field is required"; }
    }

    if (ok && input.classList.contains("validate-phone")) {
      if (!rwandaPhoneRe.test(val)) { ok = false; msg = "Enter a valid Rwanda phone (07XXXXXXXX)"; }
    }

    // Optional phone fields - no validation
    if (feedback) feedback.textContent = ok ? "" : msg;
    return ok;
  }

  function validateForm(form) {
    let allOk = true;

    // Only validate required and phone fields, NOT address fields
    form.querySelectorAll(".validate-required, .validate-phone")
      .forEach(input => {
        if (!validateInput(input)) allOk = false;
      });

    const btn = form.querySelector(".form-submit-btn");
    if (btn) btn.disabled = !allOk;

    return allOk;
  }

  function attachFormListeners(form) {
    if (!form) return;

    const inputs = form.querySelectorAll(".validate-required, .validate-phone");

    inputs.forEach(input => {
      input.addEventListener("input", () => validateForm(form));
      input.addEventListener("change", () => validateForm(form));
    });

    // INITIAL VALIDATION AFTER CONTENT IS POPULATED
    setTimeout(() => validateForm(form), 120);
  }

  document.addEventListener("DOMContentLoaded", function() {
    // Initialize address dropdowns (optional)
    initializeAddressDropdowns();

    // Add form
    attachFormListeners(document.getElementById("addPatientForm"));

    // Edit modals
    document.querySelectorAll('[id^="editModal"]').forEach(modalEl => {

      modalEl.addEventListener("shown.bs.modal", function () {
        const form = modalEl.querySelector(".patient-form");

        // reset button and errors before validating populated fields
        form.querySelector(".form-submit-btn").disabled = false;

        modalEl.querySelectorAll(".invalid-feedback").forEach(fb => fb.textContent = "");

        attachFormListeners(form);
      });

      modalEl.addEventListener("hidden.bs.modal", function () {
        modalEl.querySelectorAll(".invalid-feedback").forEach(el => el.textContent = "");
        const btn = modalEl.querySelector(".form-submit-btn");
        if (btn) btn.disabled = true;
      });

    });
  });

})();
</script>


<?php include('includes/footer.php'); ?>

<?php if(isset($_SESSION['flash'])): ?>
<script>
  window.onload = function() {
    const toast = document.createElement('div');
    toast.className = 'toast-message';
    toast.style.background = '<?= $_SESSION['flash']['color'] ?>';
    toast.innerText = '<?= $_SESSION['flash']['message'] ?>';
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 4000);
  }
</script>
<?php unset($_SESSION['flash']); endif; ?>