<?php
require_once __DIR__ . '/Includes.php';

$pdo->exec("CREATE TABLE IF NOT EXISTS classes (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

// Ensure users table exists for login bootstrap.
$pdo->exec("CREATE TABLE IF NOT EXISTS users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(150) NOT NULL UNIQUE,
  password_hash VARCHAR(255) NOT NULL,
  role ENUM('admin', 'teacher', 'hop', 'accountant', 'ancillary', 'parent') NOT NULL DEFAULT 'teacher',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");
ensure_auth_security_columns($pdo);

$pdo->exec("CREATE TABLE IF NOT EXISTS password_reset_requests (
  id INT AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  email VARCHAR(150) NOT NULL,
  requested_password_hash VARCHAR(255) NOT NULL,
  status ENUM('pending','approved','rejected') NOT NULL DEFAULT 'pending',
  requester_note VARCHAR(255) NULL,
  admin_note VARCHAR(255) NULL,
  requested_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  reviewed_at DATETIME NULL,
  reviewed_by INT NULL,
  CONSTRAINT fk_prr_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_prr_reviewer FOREIGN KEY (reviewed_by) REFERENCES users(id) ON DELETE SET NULL,
  INDEX idx_prr_status_date (status, requested_at),
  INDEX idx_prr_user_status (user_id, status)
)");

try {
  $pdo->exec("ALTER TABLE users MODIFY role ENUM('admin', 'teacher', 'hop', 'accountant', 'ancillary', 'parent') NOT NULL DEFAULT 'teacher'");
} catch (PDOException $e) {
  // Keep bootstrap idempotent if already in expected shape.
}

$pdo->exec("CREATE TABLE IF NOT EXISTS app_settings (
  setting_key VARCHAR(120) NOT NULL PRIMARY KEY,
  setting_value TEXT NOT NULL,
  updated_by INT NULL,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)");

$defaultSchoolSettings = [
  'school_name' => 'MAVELA GOVERNMENT HIGH SCHOOL',
  'school_address' => 'P.O.Box 12 Tsholotsho',
  'school_contact' => 'Phone: +263 77 000 0000 | Email: admin@mavelahigh.org',
  'school_motto' => 'Imfundo Yinsika Yesizwe',
  'school_logo_path' => 'Uploads/Mavela_Logo.png',
  'school_theme_preset' => 'forest',
  'palette_bg_cream' => '#F7FBF7',
  'palette_bg_sand' => '#E5F0E6',
  'palette_ink' => '#173122',
  'palette_muted' => '#4F6656',
  'palette_brand_navy' => '#2E8B45',
  'palette_brand_navy_deep' => '#1D6A33',
  'palette_brand_gold' => '#1E1A1B',
  'palette_brand_gold_soft' => '#D8DDD8',
  'palette_brand_ice' => '#EEF7EF',
  'palette_patch_sky' => '#7CC9FF',
  'palette_patch_sky_soft' => '#DFF2FF',
  'palette_patch_yellow' => '#7DC48A',
  'palette_patch_yellow_soft' => '#F0F7F1'
];

$seedSettingStmt = $pdo->prepare("INSERT IGNORE INTO app_settings (setting_key, setting_value) VALUES (?, ?)");
foreach ($defaultSchoolSettings as $settingKey => $settingValue) {
  $seedSettingStmt->execute([$settingKey, $settingValue]);
}

// Demo accounts are created only on explicitly local/demo installations.
if (mavela_demo_mode()) {
  $adminEmail = 'admin@mavelahigh.org';
  $adminExistsStmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ? LIMIT 1");
  $adminExistsStmt->execute([$adminEmail]);
  if ((int)$adminExistsStmt->fetchColumn() === 0) {
    $seedAdmin = $pdo->prepare("INSERT INTO users (name, email, password_hash, role) VALUES (?, ?, ?, 'admin')");
    $seedAdmin->execute(['Mavela System Admin', $adminEmail, password_hash('MavelaDemo7', PASSWORD_DEFAULT)]);
  }

  $defaultAccountants = [
    ['Mavela Accounts Office Lead', 'accounts.lead@mavelahigh.org', 'AccountsDemo7'],
  ];
  $accountantExistsStmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1");
  $seedAccountant = $pdo->prepare("INSERT INTO users (name, email, password_hash, role) VALUES (?, ?, ?, 'accountant')");
  foreach ($defaultAccountants as $accountantSeed) {
    $accountantExistsStmt->execute([$accountantSeed[1]]);
    if ((int)$accountantExistsStmt->fetchColumn() === 0) {
      $seedAccountant->execute([$accountantSeed[0], $accountantSeed[1], password_hash($accountantSeed[2], PASSWORD_DEFAULT)]);
    }
  }
}

$configuredUserCount = (int)$pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
if ($configuredUserCount === 0) {
  header('Location: setup.php');
  exit;
}

if (isset($_SESSION['user_id'], $_SESSION['role'])) {
  if ($_SESSION['role'] === 'admin') {
    header('Location: admin.php');
    exit;
  }
  if ($_SESSION['role'] === 'teacher') {
    header('Location: teacher.php');
    exit;
  }
  if ($_SESSION['role'] === 'hop') {
    header('Location: hop.php');
    exit;
  }
  if ($_SESSION['role'] === 'accountant') {
    header('Location: accountant.php');
    exit;
  }
  if ($_SESSION['role'] === 'ancillary') {
    header('Location: ancillary.php');
    exit;
  }
  if ($_SESSION['role'] === 'learner') {
    header('Location: learner.php');
    exit;
  }
  if ($_SESSION['role'] === 'parent') {
    header('Location: parent.php');
    exit;
  }
}

// Ensure learners table exists for learner desk login.
$pdo->exec("CREATE TABLE IF NOT EXISTS learners (
  reg_number VARCHAR(30) NOT NULL PRIMARY KEY,
  id INT NOT NULL AUTO_INCREMENT UNIQUE,
  class_id INT NOT NULL,
  date_of_admission DATE NULL,
  surname VARCHAR(100) NULL,
  christian_names VARCHAR(150) NULL,
  full_name VARCHAR(150) NOT NULL,
  date_of_birth_info VARCHAR(40) NULL,
  birth_certificate_number VARCHAR(80) NULL,
  religious_denomination VARCHAR(120) NULL,
  gender ENUM('Male', 'Female', 'Other') NOT NULL DEFAULT 'Other',
  guardian_name VARCHAR(120) NULL,
  guardian_national_id VARCHAR(60) NULL,
  guardian_address VARCHAR(255) NULL,
  guardian_phone VARCHAR(40) NULL,
  contact_email VARCHAR(150) NULL,
  password_hash VARCHAR(255) NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

$indexLearnerColumnsToEnsure = [
  "contact_email VARCHAR(150) NULL",
  "password_hash VARCHAR(255) NULL"
];
foreach ($indexLearnerColumnsToEnsure as $columnSql) {
  try {
    $pdo->exec("ALTER TABLE learners ADD COLUMN " . $columnSql);
  } catch (PDOException $e) {
    // Ignore duplicate column errors for idempotent upgrades.
  }
}

$pdo->exec("CREATE TABLE IF NOT EXISTS parent_learner_links (
  id INT AUTO_INCREMENT PRIMARY KEY,
  parent_user_id INT NOT NULL,
  learner_id INT NOT NULL UNIQUE,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_pl_parent FOREIGN KEY (parent_user_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_pl_learner FOREIGN KEY (learner_id) REFERENCES learners(id) ON DELETE CASCADE
)");

try {
  $pdo->exec("ALTER TABLE parent_learner_links DROP INDEX parent_user_id");
} catch (PDOException $e) {
  // Ignore when index name differs or is already removed.
}

try {
  $pdo->exec("ALTER TABLE parent_learner_links ADD INDEX idx_pl_parent_user (parent_user_id)");
} catch (PDOException $e) {
  // Ignore duplicate index errors.
}

try {
  $pdo->exec("ALTER TABLE parent_learner_links ADD UNIQUE KEY uq_pl_parent_learner (parent_user_id, learner_id)");
} catch (PDOException $e) {
  // Ignore duplicate index errors.
}

ensure_workflow_tables($pdo);

function verify_password_compat(string $plainPassword, string $storedHash): bool {
  if ($storedHash === '') {
    return false;
  }

  if (password_verify($plainPassword, $storedHash)) {
    return true;
  }

  // Legacy compatibility for old dumps that stored plain/md5/sha1 passwords.
  if (hash_equals($storedHash, $plainPassword)) {
    return true;
  }
  if (hash_equals($storedHash, md5($plainPassword))) {
    return true;
  }
  if (hash_equals($storedHash, sha1($plainPassword))) {
    return true;
  }

  return false;
}

$error = '';
$success = '';
$resetRequestPendingPopup = false;
if (isset($_POST['login'])) {
  $email = trim($_POST['email'] ?? '');
  $password = $_POST['password'] ?? '';

  if ($email === '' || $password === '') {
    $error = 'Email and password are required.';
  } elseif (login_attempt_is_blocked($pdo, 'staff:' . $email)) {
    $error = 'Too many unsuccessful sign-in attempts. Please wait 15 minutes and try again.';
  } else {
    $stmt = $pdo->prepare("SELECT id, name, email, password_hash, role, must_change_password FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user && verify_password_compat((string)$password, (string)$user['password_hash'])) {
      clear_login_failures($pdo, 'staff:' . $email);
      if (!password_verify((string)$password, (string)$user['password_hash'])) {
        try {
          $rehashStmt = $pdo->prepare("UPDATE users SET password_hash = ? WHERE id = ?");
          $rehashStmt->execute([password_hash((string)$password, PASSWORD_DEFAULT), (int)$user['id']]);
        } catch (Throwable $e) {
          // Keep login flow successful even if hash upgrade fails.
        }
      }

      append_system_log($pdo, 'user_login', 'Successful login for ' . $email, (int)$user['id'], (string)$user['role'], 'user', (int)$user['id'], get_client_ip_address());
      login_user($user);
      if ($user['role'] === 'admin') {
        header('Location: admin.php');
        exit;
      }
      if ($user['role'] === 'accountant') {
        header('Location: accountant.php');
        exit;
      }
      if ($user['role'] === 'ancillary') {
        header('Location: ancillary.php');
        exit;
      }
      if ($user['role'] === 'hop') {
        header('Location: hop.php');
        exit;
      }
      if ($user['role'] === 'parent') {
        header('Location: parent.php');
        exit;
      }
      header('Location: teacher.php');
      exit;
    }

    record_login_failure($pdo, 'staff:' . $email);
    $error = 'Invalid login credentials.';
  }
}

if (isset($_POST['request_password_reset'])) {
  $resetEmail = trim((string)($_POST['reset_email'] ?? ''));
  $resetPassword = trim((string)($_POST['reset_new_password'] ?? ''));
  $resetPasswordConfirm = trim((string)($_POST['reset_confirm_password'] ?? ''));
  $resetNote = trim((string)($_POST['reset_note'] ?? ''));

  if ($resetEmail === '' || $resetPassword === '' || $resetPasswordConfirm === '') {
    $error = 'Reset request requires email, new password, and confirmation.';
  } elseif (!filter_var($resetEmail, FILTER_VALIDATE_EMAIL)) {
    $error = 'Please provide a valid email for password reset request.';
  } elseif (!mavela_password_is_strong($resetPassword)) {
    $error = 'Use at least 10 characters with uppercase, lowercase, and a number.';
  } elseif ($resetPassword !== $resetPasswordConfirm) {
    $error = 'New password and confirmation do not match.';
  } else {
    $resetUserStmt = $pdo->prepare("SELECT id, email, role FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1");
    $resetUserStmt->execute([$resetEmail]);
    $resetUser = $resetUserStmt->fetch();

    if (!$resetUser) {
      $error = 'No account found with that email address.';
    } else {
      $pendingCheckStmt = $pdo->prepare("SELECT id FROM password_reset_requests WHERE user_id = ? AND status = 'pending' LIMIT 1");
      $pendingCheckStmt->execute([(int)$resetUser['id']]);

      if ($pendingCheckStmt->fetch()) {
        $error = 'A password reset request is already pending admin approval for this account.';
      } else {
        $createResetStmt = $pdo->prepare("INSERT INTO password_reset_requests
          (user_id, email, requested_password_hash, status, requester_note)
          VALUES (?, ?, ?, 'pending', ?)");
        $createResetStmt->execute([
          (int)$resetUser['id'],
          (string)$resetUser['email'],
          password_hash($resetPassword, PASSWORD_DEFAULT),
          $resetNote === '' ? null : $resetNote
        ]);

        $success = 'Password reset request submitted. Awaiting admin approval.';
        $resetRequestPendingPopup = true;
      }
    }
  }
}

if (isset($_POST['learner_login'])) {
  $regNumber = strtoupper(trim($_POST['learner_reg_number'] ?? ''));
  $credential = trim((string)($_POST['learner_password'] ?? ''));

  if ($regNumber === '' || $credential === '') {
    $error = 'Learner Reg Number and password are required. If no password is set yet, use your surname once.';
  } elseif (login_attempt_is_blocked($pdo, 'learner:' . $regNumber)) {
    $error = 'Too many unsuccessful sign-in attempts. Please wait 15 minutes and try again.';
  } else {
    $stmt = $pdo->prepare("SELECT id, reg_number, surname, christian_names, full_name, password_hash FROM learners WHERE reg_number = ? LIMIT 1");
    $stmt->execute([$regNumber]);
    $learner = $stmt->fetch();

    if ($learner) {
      $storedLearnerHash = trim((string)($learner['password_hash'] ?? ''));
      $dbSurname = strtolower(trim((string)($learner['surname'] ?? '')));
      $isCredentialValid = false;

      if ($storedLearnerHash !== '') {
        $isCredentialValid = verify_password_compat($credential, $storedLearnerHash);
        if ($isCredentialValid && !password_verify($credential, $storedLearnerHash)) {
          try {
            $rehashLearnerStmt = $pdo->prepare("UPDATE learners SET password_hash = ? WHERE id = ?");
            $rehashLearnerStmt->execute([password_hash($credential, PASSWORD_DEFAULT), (int)$learner['id']]);
          } catch (Throwable $e) {
            // Keep learner login successful even if hash upgrade fails.
          }
        }
      } else {
        $isCredentialValid = $dbSurname !== '' && $dbSurname === strtolower($credential);
      }

      if ($isCredentialValid) {
        clear_login_failures($pdo, 'learner:' . $regNumber);
        login_user([
          'id' => $learner['id'],
          'name' => trim(($learner['christian_names'] ?? '') . ' ' . ($learner['surname'] ?? '')),
          'role' => 'learner'
        ]);
        $_SESSION['learner_reg_number'] = $learner['reg_number'];
        header('Location: learner.php');
        exit;
      }
    }

    record_login_failure($pdo, 'learner:' . $regNumber);
    $error = 'Invalid learner login details.';
  }
}

if (isset($_POST['parent_register'])) {
  $regNumber = strtoupper(trim((string)($_POST['parent_child_reg_number'] ?? '')));
  $childSurname = strtolower(trim((string)($_POST['parent_child_surname'] ?? '')));
  $parentFullName = trim((string)($_POST['parent_full_name'] ?? ''));
  $parentEmail = trim((string)($_POST['parent_email'] ?? ''));
  $parentPassword = trim((string)($_POST['parent_password'] ?? ''));

  if ($regNumber === '' || $childSurname === '' || $parentFullName === '' || $parentEmail === '' || $parentPassword === '') {
    $error = 'Parent registration requires child Reg Number, child surname, parent full name, email, and password.';
  } elseif (!filter_var($parentEmail, FILTER_VALIDATE_EMAIL)) {
    $error = 'Please provide a valid parent email address.';
  } elseif (!mavela_password_is_strong($parentPassword)) {
    $error = 'Parent password must have at least 10 characters, uppercase, lowercase, and a number.';
  } else {
    $learnerStmt = $pdo->prepare("SELECT id, surname, guardian_name
      FROM learners
      WHERE reg_number = ?
      LIMIT 1");
    $learnerStmt->execute([$regNumber]);
    $learner = $learnerStmt->fetch();

    $childMatches = false;
    $parentMatches = false;
    if ($learner) {
      $dbSurname = strtolower(trim((string)($learner['surname'] ?? '')));
      $childMatches = $dbSurname !== '' && $dbSurname === $childSurname;

      $dbGuardianName = strtolower(preg_replace('/\s+/', ' ', trim((string)($learner['guardian_name'] ?? ''))));
      $inputParentName = strtolower(preg_replace('/\s+/', ' ', $parentFullName));
      $parentMatches = $dbGuardianName !== '' && $dbGuardianName === $inputParentName;
    }

    if (!$learner || !$childMatches) {
      $error = 'Child verification failed. Check Reg Number and surname.';
    } elseif (!$parentMatches) {
      $error = 'Parent full name does not match the student database record.';
    } else {
      $existingUserStmt = $pdo->prepare("SELECT id, role FROM users WHERE email = ? LIMIT 1");
      $existingUserStmt->execute([$parentEmail]);
      $existingUser = $existingUserStmt->fetch();

      if ($existingUser) {
        $error = 'An account with this email already exists. Please sign in.';
      } else {
        try {
          $pdo->beginTransaction();

          $createParentStmt = $pdo->prepare("INSERT INTO users (name, email, password_hash, role)
            VALUES (?, ?, ?, 'parent')");
          $createParentStmt->execute([$parentFullName, $parentEmail, password_hash($parentPassword, PASSWORD_DEFAULT)]);
          $parentUserId = (int)$pdo->lastInsertId();

          $matchLearnersStmt = $pdo->prepare("SELECT id
            FROM learners
            WHERE LOWER(TRIM(guardian_name)) = LOWER(TRIM(?))");
          $matchLearnersStmt->execute([$parentFullName]);
          $matchedLearners = $matchLearnersStmt->fetchAll();

          $linkStmt = $pdo->prepare("INSERT INTO parent_learner_links (parent_user_id, learner_id)
            VALUES (?, ?)
            ON DUPLICATE KEY UPDATE parent_user_id = VALUES(parent_user_id)");

          $linkedCount = 0;
          foreach ($matchedLearners as $row) {
            $linkStmt->execute([$parentUserId, (int)$row['id']]);
            $linkedCount++;
          }

          if ($linkedCount === 0) {
            $linkStmt->execute([$parentUserId, (int)$learner['id']]);
            $linkedCount = 1;
          }

          $pdo->commit();
          $success = 'Parent account created successfully. Linked learner records: ' . $linkedCount . '. You can now sign in.';
        } catch (PDOException $e) {
          if ($pdo->inTransaction()) {
            $pdo->rollBack();
          }
          $error = 'Could not create parent account. Please try again.';
        }
      }
    }
  }
}

if (isset($_POST['submit_learner_application'])) {
  $preferredClassId = (int)($_POST['application_class_id'] ?? 0);
  $dateOfAdmission = trim((string)($_POST['application_date_of_admission'] ?? ''));
  $surname = trim((string)($_POST['application_surname'] ?? ''));
  $christianNames = trim((string)($_POST['application_christian_names'] ?? ''));
  $dateOfBirth = trim((string)($_POST['application_date_of_birth_info'] ?? ''));
  $birthCertificateNumber = trim((string)($_POST['application_birth_certificate_number'] ?? ''));
  $religion = trim((string)($_POST['application_religious_denomination'] ?? ''));
  $gender = trim((string)($_POST['application_gender'] ?? 'Other'));
  $guardianName = trim((string)($_POST['application_guardian_name'] ?? ''));
  $guardianNationalId = trim((string)($_POST['application_guardian_national_id'] ?? ''));
  $guardianAddress = trim((string)($_POST['application_guardian_address'] ?? ''));
  $guardianPhone = trim((string)($_POST['application_guardian_phone'] ?? ''));
  $parentEmail = trim((string)($_POST['application_parent_email'] ?? ''));
  $parentWhatsappPhone = trim((string)($_POST['application_parent_whatsapp_phone'] ?? ''));

  if ($preferredClassId <= 0) {
    $error = 'Please choose preferred class for learner application.';
  } elseif ($surname === '' || $christianNames === '') {
    $error = 'Learner surname and christian names are required.';
  } elseif ($guardianName === '') {
    $error = 'Parent/Guardian full name is required.';
  } elseif ($parentEmail !== '' && !filter_var($parentEmail, FILTER_VALIDATE_EMAIL)) {
    $error = 'Parent email format is invalid.';
  } elseif (!in_array($gender, ['Male', 'Female', 'Other'], true)) {
    $error = 'Invalid learner gender selected.';
  } else {
    $photoPath = null;
    if (isset($_FILES['application_student_photo']) && (int)($_FILES['application_student_photo']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
      $photoError = (int)($_FILES['application_student_photo']['error'] ?? UPLOAD_ERR_NO_FILE);
      if ($photoError !== UPLOAD_ERR_OK) {
        $error = 'Student photo upload failed.';
      } else {
        $originalName = (string)($_FILES['application_student_photo']['name'] ?? '');
        $tmpName = (string)($_FILES['application_student_photo']['tmp_name'] ?? '');
        $fileSize = (int)($_FILES['application_student_photo']['size'] ?? 0);
        $ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
        if (!in_array($ext, ['jpg', 'jpeg', 'png', 'webp'], true)) {
          $error = 'Student photo must be JPG, PNG, or WEBP.';
        } elseif ($fileSize <= 0 || $fileSize > 6 * 1024 * 1024) {
          $error = 'Student photo must be between 1 byte and 6 MB.';
        } else {
          $finfo = finfo_open(FILEINFO_MIME_TYPE);
          $detectedMime = $finfo ? (string)finfo_file($finfo, $tmpName) : '';
          if ($finfo) {
            finfo_close($finfo);
          }
          if (!in_array($detectedMime, ['image/jpeg', 'image/png', 'image/webp'], true)) {
            $error = 'The uploaded student photo is not a valid JPG, PNG, or WEBP image.';
          } else {
            $uploadDir = __DIR__ . '/Uploads/applications';
            if (!is_dir($uploadDir) && !mkdir($uploadDir, 0775, true)) {
              $error = 'Unable to create application upload folder.';
            } else {
              $safeBase = preg_replace('/[^A-Za-z0-9._-]/', '_', pathinfo($originalName, PATHINFO_FILENAME));
              $safeBase = trim((string)$safeBase, '._-');
              if ($safeBase === '') {
                $safeBase = 'applicant';
              }
              $fileName = 'application_' . date('Ymd_His') . '_' . bin2hex(random_bytes(3)) . '_' . $safeBase . '.' . $ext;
              $destPath = $uploadDir . '/' . $fileName;
              if (!move_uploaded_file($tmpName, $destPath)) {
                $error = 'Unable to save student photo.';
              } else {
                $photoPath = 'Uploads/applications/' . $fileName;
              }
            }
          }
        }
      }
    }

    if ($error === '') {
      $fullName = trim($christianNames . ' ' . $surname);
      $insertApplication = $pdo->prepare("INSERT INTO learner_applications
        (surname, christian_names, full_name, date_of_birth_info, birth_certificate_number, religious_denomination, gender,
         date_of_admission, guardian_name, guardian_national_id, guardian_address, guardian_phone,
         parent_email, parent_whatsapp_phone, preferred_class_id, student_photo_path)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
      $insertApplication->execute([
        $surname,
        $christianNames,
        $fullName,
        $dateOfBirth === '' ? null : $dateOfBirth,
        $birthCertificateNumber === '' ? null : $birthCertificateNumber,
        $religion === '' ? null : $religion,
        $gender,
        $dateOfAdmission === '' ? null : $dateOfAdmission,
        $guardianName,
        $guardianNationalId === '' ? null : $guardianNationalId,
        $guardianAddress === '' ? null : $guardianAddress,
        $guardianPhone === '' ? null : $guardianPhone,
        $parentEmail === '' ? null : $parentEmail,
        $parentWhatsappPhone === '' ? null : $parentWhatsappPhone,
        $preferredClassId,
        $photoPath
      ]);
      $success = 'Learner application submitted. Admin will review and contact parent/guardian.';
    }
  }
}

$applicationClasses = $pdo->query("SELECT id, name FROM classes ORDER BY id")->fetchAll();

$defaultSchoolName = 'MAVELA GOVERNMENT HIGH SCHOOL';
$defaultSchoolAddress = 'P.O.Box 12 Tsholotsho';
$defaultSchoolLogoPath = 'Uploads/Mavela_Logo.png';
$schoolName = trim(get_app_setting($pdo, 'school_name', $defaultSchoolName));
$schoolAddress = trim(get_app_setting($pdo, 'school_address', $defaultSchoolAddress));
$schoolLogoPath = trim(get_app_setting($pdo, 'school_logo_path', $defaultSchoolLogoPath));
$themePalette = get_school_theme_palette($pdo);
$paletteBgCream = (string)($themePalette['bg_cream'] ?? '#F7FBF7');
$paletteBgSand = (string)($themePalette['bg_sand'] ?? '#E5F0E6');
$paletteInk = (string)($themePalette['ink'] ?? '#173122');
$paletteMuted = (string)($themePalette['muted'] ?? '#4F6656');
$paletteBrandNavy = (string)($themePalette['brand_navy'] ?? '#2E8B45');
$paletteBrandNavyDeep = (string)($themePalette['brand_navy_deep'] ?? '#1D6A33');
$paletteBrandGold = (string)($themePalette['brand_gold'] ?? '#1E1A1B');
$paletteBrandGoldSoft = (string)($themePalette['brand_gold_soft'] ?? '#D8DDD8');
$paletteBrandIce = (string)($themePalette['brand_ice'] ?? '#EEF7EF');
$palettePatchSky = (string)($themePalette['patch_sky'] ?? '#7CC9FF');
$palettePatchSkySoft = (string)($themePalette['patch_sky_soft'] ?? '#D6EEFF');
$palettePatchYellow = (string)($themePalette['patch_yellow'] ?? '#FFD447');
$palettePatchYellowSoft = (string)($themePalette['patch_yellow_soft'] ?? '#FFF2BF');

if ($schoolName === '') {
  $schoolName = $defaultSchoolName;
}
if ($schoolAddress === '') {
  $schoolAddress = $defaultSchoolAddress;
}
if ($schoolLogoPath === '' || !is_file(__DIR__ . '/' . ltrim($schoolLogoPath, '/\\'))) {
  $schoolLogoPath = $defaultSchoolLogoPath;
}

$activeAuthView = 'staff';
if (isset($_POST['learner_login'])) {
  $activeAuthView = 'learner';
}
if (isset($_POST['parent_register']) || $success !== '') {
  $activeAuthView = 'parent';
}
if (isset($_POST['submit_learner_application'])) {
  $activeAuthView = 'application';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= h($schoolName) ?> Login</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&family=Plus+Jakarta+Sans:wght@500;600;700;800&display=swap" rel="stylesheet">
  <style>
    :root {
      --bg-cream: <?= h($paletteBgCream) ?>;
      --bg-sand: <?= h($paletteBgSand) ?>;
      --ink: <?= h($paletteInk) ?>;
      --muted: <?= h($paletteMuted) ?>;
      --brand-navy: <?= h($paletteBrandNavy) ?>;
      --brand-navy-deep: <?= h($paletteBrandNavyDeep) ?>;
      --brand-gold: <?= h($paletteBrandGold) ?>;
      --brand-gold-soft: <?= h($paletteBrandGoldSoft) ?>;
      --brand-ice: <?= h($paletteBrandIce) ?>;
      --patch-sky: <?= h($palettePatchSky) ?>;
      --patch-sky-soft: <?= h($palettePatchSkySoft) ?>;
      --patch-yellow: <?= h($palettePatchYellow) ?>;
      --patch-yellow-soft: <?= h($palettePatchYellowSoft) ?>;
      --line: <?= h($palettePatchSkySoft) ?>;
      --danger: #9f1239;
      --panel: rgba(255, 255, 255, 0.94);
      --shadow: 0 24px 70px rgba(5, 30, 63, 0.16);
    }

    * { box-sizing: border-box; }

    body {
      margin: 0;
      min-height: 100vh;
      font-family: 'Outfit', sans-serif;
      color: var(--ink);
      background:
        radial-gradient(circle at 12% 18%, color-mix(in srgb, var(--brand-navy) 18%, transparent) 0, transparent 32%),
        radial-gradient(circle at 88% 16%, color-mix(in srgb, var(--patch-yellow) 18%, transparent) 0, transparent 34%),
        linear-gradient(135deg, var(--bg-cream) 0%, var(--bg-sand) 100%);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 24px;
      overflow-x: hidden;
    }

    body::before {
      content: '';
      position: fixed;
      inset: 0;
      background: radial-gradient(circle at bottom left, rgba(255,255,255,0.28), transparent 35%);
      pointer-events: none;
    }

    .page-shell {
      width: min(1240px, 100%);
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 24px;
      align-items: stretch;
    }

    .hero-panel {
      background: linear-gradient(135deg, var(--brand-navy-deep) 0%, var(--brand-navy) 55%, var(--brand-gold-soft) 100%);
      color: #fff;
      border-radius: 30px;
      padding: 38px;
      box-shadow: var(--shadow);
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      text-align: center;
      position: relative;
      overflow: hidden;
      transform: translateY(0);
      transition: transform 180ms ease, box-shadow 180ms ease;
    }

    .hero-panel:hover {
      transform: translateY(-3px);
      box-shadow: 0 30px 80px rgba(5, 30, 63, 0.22);
    }

    .hero-panel::after {
      content: '';
      position: absolute;
      inset: auto -60px -60px auto;
      width: 240px;
      height: 240px;
      border-radius: 50%;
      background: rgba(255,255,255,0.16);
      filter: blur(2px);
    }

    .hero-pill {
      display: inline-flex;
      align-items: center;
      gap: 8px;
      width: fit-content;
      padding: 8px 12px;
      border-radius: 999px;
      background: rgba(255,255,255,0.18);
      color: #fefefe;
      font-size: 0.86rem;
      font-weight: 700;
      letter-spacing: 0.04em;
      text-transform: uppercase;
      backdrop-filter: blur(8px);
      margin: 0 auto;
    }

    .hero-panel h1 {
      margin: 14px 0 8px;
      font-family: 'Plus Jakarta Sans', sans-serif;
      font-size: clamp(1.5rem, 2.2vw, 2.1rem);
      line-height: 1.12;
    }

    .hero-panel p {
      margin: 0;
      font-size: 0.93rem;
      line-height: 1.55;
      color: rgba(255,255,255,0.88);
    }

    .hero-list {
      list-style: none;
      padding: 0;
      margin: 14px 0 0;
      display: grid;
      gap: 8px;
    }

    .hero-list li {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10px;
      background: rgba(255,255,255,0.15);
      padding: 9px 12px;
      border-radius: 12px;
      font-size: 0.9rem;
      font-weight: 600;
      backdrop-filter: blur(7px);
      text-align: center;
    }

    .hero-list li::before {
      content: '●';
      color: var(--patch-yellow);
      font-size: 0.9rem;
    }

    .hero-stats {
      display: grid;
      grid-template-columns: repeat(3, minmax(0, 1fr));
      gap: 10px;
      margin-top: 16px;
    }

    .hero-stat {
      background: rgba(255,255,255,0.12);
      border: 1px solid rgba(255,255,255,0.22);
      border-radius: 16px;
      padding: 12px;
      backdrop-filter: blur(8px);
      text-align: center;
    }

    .hero-stat strong {
      display: block;
      font-size: 1.1rem;
      margin-bottom: 3px;
    }

    .hero-stat span {
      font-size: 0.8rem;
      color: rgba(255,255,255,0.86);
      text-transform: uppercase;
      letter-spacing: 0.04em;
    }

    .auth-panel {
      background: var(--panel);
      border: 1px solid rgba(255,255,255,0.8);
      border-radius: 28px;
      box-shadow: var(--shadow);
      padding: 22px;
      backdrop-filter: blur(12px);
      animation: floatIn 320ms ease both;
      position: relative;
    }

    .auth-panel::before {
      content: '';
      position: absolute;
      inset: 0;
      border-radius: inherit;
      padding: 1px;
      background: linear-gradient(135deg, rgba(124, 201, 255, 0.35), rgba(46, 139, 69, 0.08));
      -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
      -webkit-mask-composite: xor;
      mask-composite: exclude;
      pointer-events: none;
    }

    @keyframes floatIn {
      from {
        opacity: 0;
        transform: translateY(10px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }

    .card {
      width: 100%;
      background: transparent;
      border: 0;
      border-radius: 0;
      box-shadow: none;
      overflow: visible;
    }

    .hero {
      padding: 18px 20px;
      background: linear-gradient(120deg, var(--brand-navy-deep), var(--brand-navy) 70%, var(--patch-sky));
      color: #fff;
      display: flex;
      gap: 12px;
      align-items: center;
      justify-content: center;
      text-align: center;
      border-radius: 18px;
      margin-bottom: 16px;
      box-shadow: 0 10px 24px rgba(18, 46, 86, 0.16);
    }

    .hero img {
      width: 68px;
      height: 68px;
      border-radius: 16px;
      background: rgba(255, 255, 255, 0.18);
      border: 1px solid rgba(255, 255, 255, 0.3);
      padding: 7px;
      object-fit: contain;
    }

    .hero h1 {
      margin: 0;
      font-family: 'Plus Jakarta Sans', sans-serif;
      font-size: 0.95rem;
      line-height: 1.3;
    }

    .hero p {
      margin: 5px 0 0;
      font-size: 0.9rem;
      opacity: 0.95;
      line-height: 1.45;
    }

    .content {
      padding: 6px 2px 2px;
      text-align: center;
    }

    .field {
      margin-bottom: 12px;
      display: grid;
      gap: 5px;
    }

    label {
      font-size: 0.82rem;
      text-transform: uppercase;
      letter-spacing: 0.06em;
      color: var(--muted);
      font-weight: 700;
      text-align: left;
    }

    input, select, textarea {
      border: 1px solid #d3ddda;
      border-radius: 12px;
      padding: 10px 12px;
      font-family: inherit;
      font-size: 0.96rem;
      width: 100%;
      color: var(--ink);
      background: #fff;
    }

    input:focus, select:focus, textarea:focus {
      outline: none;
      border-color: var(--brand-navy);
      box-shadow: 0 0 0 3px rgba(10, 59, 121, 0.16);
    }

    .btn {
      width: 100%;
      border: 0;
      border-radius: 12px;
      padding: 11px 14px;
      font-family: 'Plus Jakarta Sans', sans-serif;
      font-weight: 700;
      background: linear-gradient(115deg, var(--patch-yellow), var(--brand-navy));
      color: #fff;
      cursor: pointer;
      transition: background 160ms ease, color 160ms ease, transform 120ms ease;
      box-shadow: 0 8px 20px rgba(25, 57, 93, 0.16);
    }

    .btn:hover {
      background: linear-gradient(115deg, var(--patch-sky), var(--brand-navy));
      color: var(--brand-navy-deep);
      transform: translateY(-1px);
      box-shadow: 0 10px 24px rgba(25, 57, 93, 0.2);
    }

    .error {
      margin-bottom: 10px;
      padding: 9px 10px;
      border-radius: 9px;
      border: 1px solid #fda4af;
      background: #fff1f2;
      color: var(--danger);
      font-size: 0.9rem;
      font-weight: 600;
    }

    .hint {
      margin-top: 12px;
      font-size: 0.86rem;
      color: var(--muted);
      line-height: 1.45;
    }

    .hint strong {
      color: var(--brand-navy-deep);
    }

    .text-link {
      display: inline-block;
      margin-top: 10px;
      font-size: 0.86rem;
      color: var(--brand-navy);
      font-weight: 700;
      text-decoration: underline;
      cursor: pointer;
      border: 0;
      background: transparent;
      padding: 0;
      font-family: inherit;
    }

    .inline-box {
      margin-top: 12px;
      border: 1px dashed #c7d8c9;
      border-radius: 12px;
      padding: 10px;
      background: var(--patch-yellow-soft);
      display: none;
    }

    .inline-box.active {
      display: block;
    }

    .auth-tabs {
      display: grid;
      grid-template-columns: repeat(3, minmax(0, 1fr));
      gap: 6px;
      margin-bottom: 12px;
      align-items: center;
      text-align: center;
    }

    .auth-tab {
      border: 1px solid #d8e5db;
      background: var(--brand-ice);
      color: var(--brand-navy-deep);
      border-radius: 10px;
      padding: 8px 9px;
      font-family: 'Plus Jakarta Sans', sans-serif;
      font-weight: 700;
      font-size: 0.82rem;
      cursor: pointer;
      transition: transform 140ms ease, box-shadow 140ms ease;
    }

    .auth-tab:hover {
      transform: translateY(-1px);
      box-shadow: 0 6px 14px rgba(22, 48, 88, 0.1);
    }

    .auth-tab.active {
      background: linear-gradient(115deg, var(--brand-navy), var(--brand-navy-deep));
      color: #fff;
      border-color: var(--brand-navy);
    }

    .auth-tab--application {
      grid-column: 1 / -1;
      justify-self: center;
      width: min(320px, 100%);
    }

    .auth-pane {
      display: none;
    }

    .auth-pane.active {
      display: block;
    }

    .workspace-launch {
      margin: 2px 0 12px;
      padding: 11px 12px;
      border-radius: 12px;
      border: 1px solid #c9ddd0;
      background: linear-gradient(120deg, #f4fbf5, #eef8f2);
      text-align: left;
    }

    .workspace-launch strong {
      display: block;
      font-size: 0.88rem;
      color: var(--brand-navy-deep);
      margin-bottom: 3px;
    }

    .workspace-launch p {
      margin: 0;
      font-size: 0.82rem;
      color: var(--muted);
      line-height: 1.4;
    }

    .workspace-launch a {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      margin-top: 7px;
      min-height: 42px;
      padding: 0 16px;
      border-radius: 12px;
      font-size: 0.88rem;
      font-weight: 700;
      color: #fff;
      text-decoration: none;
      background: linear-gradient(135deg, #2f80ed, #1d62c9);
      box-shadow: 0 10px 22px rgba(29, 98, 201, 0.22);
      border: 1px solid #1d62c9;
    }

    .workspace-launch a:hover {
      background: linear-gradient(135deg, #3b8ef7, #1b57b2);
      border-color: #1b57b2;
    }

    .page-footer {
      width: min(1240px, 100%);
      text-align: center;
      margin-top: 18px;
      font-size: 0.82rem;
      color: var(--muted);
      opacity: 0.75;
      flex-shrink: 0;
    }

    @media (max-width: 920px) {
      .page-shell {
        grid-template-columns: 1fr;
      }

      .hero-panel {
        min-height: auto;
      }
    }

    @media (max-width: 520px) {
      body {
        padding: 14px;
      }

      .hero-panel,
      .auth-panel {
        border-radius: 20px;
        padding: 18px;
      }

      .hero-stats {
        grid-template-columns: 1fr;
      }

      .auth-tabs {
        grid-template-columns: 1fr;
      }

      input,
      select,
      textarea {
        font-size: 16px;
      }

      .auth-tab--application {
        justify-self: stretch;
        width: 100%;
      }
    }
  </style>
</head>
<body>
  <main class="page-shell">
    <section class="hero-panel">
      <div>
        <div class="hero-pill">Smart school portal</div>
        <h1>Your school, fully connected.</h1>
        <p>Secure access for staff, learners, and parents — all in one place.</p>
        <ul class="hero-list">
          <li>Staff &amp; learner sign-in</li>
          <li>Parent registration &amp; communication</li>
          <li>Online learner applications</li>
        </ul>
      </div>

      <div class="hero-stats">
        <div class="hero-stat">
          <strong>24/7</strong>
          <span>Digital access</span>
        </div>
        <div class="hero-stat">
          <strong>100%</strong>
          <span>Secure sign-in</span>
        </div>
        <div class="hero-stat">
          <strong>All roles</strong>
          <span>Unified portal</span>
        </div>
      </div>
    </section>

    <section class="auth-panel">
      <div class="card">
        <header class="hero">
          <img src="<?= h($schoolLogoPath) ?>" alt="<?= h($schoolName) ?> logo">
          <div>
            <h1><?= h($schoolName) ?></h1>
            <p><?= h($schoolAddress) ?> | Secure access for Admin, Teachers, Learners, and Parents</p>
          </div>
        </header>

        <section class="content">
          <?php if ($error !== ''): ?>
            <div class="error"><?= h($error) ?></div>
          <?php endif; ?>
          <?php if ($success !== ''): ?>
            <div class="error" style="border-color:#86efac;background:#ecfdf3;color:#166534;"><?= h($success) ?></div>
          <?php endif; ?>

          <div class="auth-tabs" id="authTabs">
            <button type="button" class="auth-tab <?= $activeAuthView === 'staff' ? 'active' : '' ?>" data-target="staffAuthPane">Sign In</button>
            <button type="button" class="auth-tab <?= $activeAuthView === 'learner' ? 'active' : '' ?>" data-target="learnerAuthPane">Learner Desk</button>
            <button type="button" class="auth-tab <?= $activeAuthView === 'parent' ? 'active' : '' ?>" data-target="parentAuthPane">Parent Sign Up</button>
            <button type="button" class="auth-tab auth-tab--application <?= $activeAuthView === 'application' ? 'active' : '' ?>" data-target="applicationAuthPane">New Learner Application</button>
          </div>

          <div class="workspace-launch">
            <strong>Need the Tuckshop &amp; Produce portal?</strong>
            <p>Use the independent business workspaces for snacks, fast food, and agricultural produce/project sales.</p>
            <a href="tuckshop_projects_login.php">Open Tuckshop &amp; Produce Workspaces</a>
          </div>

          <div id="staffAuthPane" class="auth-pane <?= $activeAuthView === 'staff' ? 'active' : '' ?>">
            <form method="POST" autocomplete="off">
              <div class="field">
                <label for="email">Email Address</label>
                <input id="email" type="email" name="email" required>
              </div>
              <div class="field">
                <label for="password">Password</label>
                <input id="password" type="password" name="password" required>
              </div>
              <button class="btn" type="submit" name="login">Sign In</button>
            </form>

            <button type="button" class="text-link" id="openResetRequestBtn">Forgot password? Request admin reset</button>
            <div class="inline-box" id="resetRequestBox">
              <form method="POST" autocomplete="off">
                <div class="field">
                  <label for="reset_email">Account Email</label>
                  <input id="reset_email" type="email" name="reset_email" required>
                </div>
                <div class="field">
                  <label for="reset_new_password">New Password (to be approved by Admin)</label>
                  <input id="reset_new_password" type="password" name="reset_new_password" minlength="10" autocomplete="new-password" required>
                </div>
                <div class="field">
                  <label for="reset_confirm_password">Confirm New Password</label>
                  <input id="reset_confirm_password" type="password" name="reset_confirm_password" minlength="10" autocomplete="new-password" required>
                </div>
                <div class="field">
                  <label for="reset_note">Reason / Note (Optional)</label>
                  <input id="reset_note" type="text" name="reset_note" placeholder="e.g. Phone lost, forgot old password">
                </div>
                <button class="btn" type="submit" name="request_password_reset">Submit Reset Request</button>
                <p class="hint" style="margin:8px 0 0;">Your request stays pending until admin verifies by physical phone call or in-person appearance.</p>
              </form>
            </div>
          </div>

          <div id="learnerAuthPane" class="auth-pane <?= $activeAuthView === 'learner' ? 'active' : '' ?>">
            <form method="POST" autocomplete="off">
              <div class="field">
                <label for="learner_reg_number">Learner Reg Number</label>
                <input id="learner_reg_number" type="text" name="learner_reg_number" placeholder="e.g. MAV26001" required>
              </div>
              <div class="field">
                <label for="learner_password">Password</label>
                <input id="learner_password" type="password" name="learner_password" required>
              </div>
              <p class="hint" style="margin:-2px 0 10px;">If your learner password has not been set yet, enter your surname once, then change it inside Learner Desk.</p>
              <button class="btn" type="submit" name="learner_login">Open Learner Desk</button>
            </form>
          </div>

          <div id="parentAuthPane" class="auth-pane <?= $activeAuthView === 'parent' ? 'active' : '' ?>">
            <form method="POST" autocomplete="off">
              <div class="field">
                <label for="parent_child_reg_number">Child Reg Number</label>
                <input id="parent_child_reg_number" type="text" name="parent_child_reg_number" placeholder="e.g. MAV26001" required>
              </div>
              <div class="field">
                <label for="parent_child_surname">Child Surname</label>
                <input id="parent_child_surname" type="text" name="parent_child_surname" required>
              </div>
              <div class="field">
                <label for="parent_full_name">Parent Full Name (as in school records)</label>
                <input id="parent_full_name" type="text" name="parent_full_name" required>
              </div>
              <div class="field">
                <label for="parent_email">Parent Email</label>
                <input id="parent_email" type="email" name="parent_email" required>
              </div>
              <div class="field">
                <label for="parent_password">Create Password</label>
                <input id="parent_password" type="password" name="parent_password" minlength="10" autocomplete="new-password" required>
              </div>
              <button class="btn" type="submit" name="parent_register">Create Parent Account</button>
            </form>
          </div>

          <div id="applicationAuthPane" class="auth-pane <?= $activeAuthView === 'application' ? 'active' : '' ?>">
            <form method="POST" autocomplete="off" enctype="multipart/form-data">
              <div class="field">
                <label for="application_class_id">Preferred Class</label>
                <select id="application_class_id" name="application_class_id" required>
                  <option value="">Choose class</option>
                  <?php foreach ($applicationClasses as $classRow): ?>
                    <option value="<?= h($classRow['id']) ?>"><?= h($classRow['name']) ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div class="field">
                <label for="application_date_of_admission">Date of Admission</label>
                <input id="application_date_of_admission" type="date" name="application_date_of_admission">
              </div>
              <div class="field">
                <label for="application_surname">Learner Surname</label>
                <input id="application_surname" type="text" name="application_surname" required>
              </div>
              <div class="field">
                <label for="application_christian_names">Learner Christian Names</label>
                <input id="application_christian_names" type="text" name="application_christian_names" required>
              </div>
              <div class="field">
                <label for="application_date_of_birth_info">Date of Birth</label>
                <input id="application_date_of_birth_info" type="text" name="application_date_of_birth_info" placeholder="e.g. 2016-02-14">
              </div>
              <div class="field">
                <label for="application_birth_certificate_number">Birth Certificate Number</label>
                <input id="application_birth_certificate_number" type="text" name="application_birth_certificate_number" placeholder="Optional">
              </div>
              <div class="field">
                <label for="application_religious_denomination">Religious Denomination</label>
                <input id="application_religious_denomination" type="text" name="application_religious_denomination">
              </div>
              <div class="field">
                <label for="application_gender">Gender</label>
                <select id="application_gender" name="application_gender" required>
                  <option value="Male">Male</option>
                  <option value="Female">Female</option>
                  <option value="Other" selected>Other</option>
                </select>
              </div>
              <div class="field">
                <label for="application_guardian_name">Parent/Guardian Full Name</label>
                <input id="application_guardian_name" type="text" name="application_guardian_name" required>
              </div>
              <div class="field">
                <label for="application_guardian_national_id">Guardian National ID</label>
                <input id="application_guardian_national_id" type="text" name="application_guardian_national_id">
              </div>
              <div class="field">
                <label for="application_guardian_address">Guardian Address</label>
                <input id="application_guardian_address" type="text" name="application_guardian_address">
              </div>
              <div class="field">
                <label for="application_guardian_phone">Guardian Phone</label>
                <input id="application_guardian_phone" type="text" name="application_guardian_phone">
              </div>
              <div class="field">
                <label for="application_parent_email">Parent Email</label>
                <input id="application_parent_email" type="email" name="application_parent_email">
              </div>
              <div class="field">
                <label for="application_parent_whatsapp_phone">Parent WhatsApp Phone</label>
                <input id="application_parent_whatsapp_phone" type="text" name="application_parent_whatsapp_phone" placeholder="e.g. +26377xxxxxxx">
              </div>
              <div class="field">
                <label for="application_student_photo">Student Photo (Optional)</label>
                <input id="application_student_photo" type="file" name="application_student_photo" accept=".jpg,.jpeg,.png,.webp">
              </div>
              <button class="btn" type="submit" name="submit_learner_application">Submit Application</button>
            </form>
          </div>
        </section>
      </div>
    </section>
  </main>

  <footer class="page-footer">
    Developed by Ngwenya Jonas &copy; 2026
  </footer>

  <script>
    const authTabs = Array.from(document.querySelectorAll('#authTabs .auth-tab'));
    const authPanes = Array.from(document.querySelectorAll('.auth-pane'));

    function openAuthPane(targetId) {
      authPanes.forEach(pane => pane.classList.toggle('active', pane.id === targetId));
      authTabs.forEach(tab => tab.classList.toggle('active', tab.dataset.target === targetId));
    }

    authTabs.forEach(tab => {
      tab.addEventListener('click', function () {
        const target = this.dataset.target || '';
        if (target !== '') {
          openAuthPane(target);
        }
      });
    });

    const openResetRequestBtn = document.getElementById('openResetRequestBtn');
    const resetRequestBox = document.getElementById('resetRequestBox');
    if (openResetRequestBtn && resetRequestBox) {
      openResetRequestBtn.addEventListener('click', function () {
        resetRequestBox.classList.toggle('active');
      });
    }

    <?php if ($resetRequestPendingPopup): ?>
      window.alert('Password reset request submitted and pending admin approval.');
    <?php endif; ?>
  </script>
  <?php output_auto_capitalize_script(); ?>
  <?php output_select_search_script(); ?>
</body>
</html>
