<?php

$pageTitle = "Register Corps Member";

require_once '../includes/auth.php';

require_login();

$user = current_user();


/*
|--------------------------------------------------------------------------
| OPTIONAL ROLE PROTECTION
|--------------------------------------------------------------------------
|
| Uncomment this when you are ready to restrict this page.
|--------------------------------------------------------------------------
*/

// $allowedRoles = ['Administrator', 'Camp Officer'];
//
// if (!in_array($user['role'], $allowedRoles)) {
//     header("Location: index.php");
//     exit;
// }


/*
|--------------------------------------------------------------------------
| INITIAL VARIABLES
|--------------------------------------------------------------------------
*/

$successMessage = '';
$errorMessage = '';

/*
|--------------------------------------------------------------------------
| INITIALIZE PASSPORT UPLOAD VARIABLES
|--------------------------------------------------------------------------
|
| These are initialized here so that they are always available inside
| the catch block if anything fails during registration.
|--------------------------------------------------------------------------
*/

$passportPath = null;
$uploadDestination = null;


/*
|--------------------------------------------------------------------------
| GET STATES
|--------------------------------------------------------------------------
*/

$statesStmt = $db->query("
    SELECT
        id,
        state_name,
        state_code
    FROM states
    ORDER BY state_name ASC
");

$states = $statesStmt->fetchAll(PDO::FETCH_ASSOC);


/*
|--------------------------------------------------------------------------
| GET PLATOONS
|--------------------------------------------------------------------------
*/

$platoonsStmt = $db->query("
    SELECT
        id,
        platoon_name,
        platoon_code
    FROM platoons
    WHERE status = 'Active'
    ORDER BY platoon_name ASC
");

$platoons = $platoonsStmt->fetchAll(PDO::FETCH_ASSOC);


/*
|--------------------------------------------------------------------------
| GET HOSTELS
|--------------------------------------------------------------------------
|
| Hostel assignment is optional during registration.
|--------------------------------------------------------------------------
*/

$hostelsStmt = $db->query("
    SELECT
        id,
        hostel_name,
        hostel_code,
        gender,
        status
    FROM hostels
    WHERE status != 'Maintenance'
    ORDER BY hostel_name ASC
");

$hostels = $hostelsStmt->fetchAll(PDO::FETCH_ASSOC);


/*
|--------------------------------------------------------------------------
| PROCESS REGISTRATION FORM
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    /*
    |--------------------------------------------------------------------------
    | RESET PASSPORT VARIABLES FOR THIS REQUEST
    |--------------------------------------------------------------------------
    */

    $passportPath = null;
    $uploadDestination = null;


    /*
    |--------------------------------------------------------------------------
    | PERSONAL INFORMATION
    |--------------------------------------------------------------------------
    */

    $firstname = trim($_POST['firstname'] ?? '');
    $lastname = trim($_POST['lastname'] ?? '');
    $othername = trim($_POST['othername'] ?? '');

    $gender = trim($_POST['gender'] ?? '');
    $dateOfBirth = trim($_POST['date_of_birth'] ?? '');
    $maritalStatus = trim($_POST['marital_status'] ?? 'Single');

    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');

    $homeAddress = trim($_POST['home_address'] ?? '');


    /*
    |--------------------------------------------------------------------------
    | NYSC INFORMATION
    |--------------------------------------------------------------------------
    */

    $stateCode = trim($_POST['state_code'] ?? '');
    $callUpNumber = trim($_POST['call_up_number'] ?? '');

    $stateId = !empty($_POST['state_id'])
        ? (int) $_POST['state_id']
        : null;

    $lgaId = !empty($_POST['lga_id'])
        ? (int) $_POST['lga_id']
        : null;

    $batch = trim($_POST['batch'] ?? '');
    $stream = trim($_POST['stream'] ?? '');

    $yearOfService = !empty($_POST['year_of_service'])
        ? (int) $_POST['year_of_service']
        : null;

    $registrationDate = !empty($_POST['registration_date'])
        ? $_POST['registration_date']
        : date('Y-m-d');

    $corpsStatus = trim($_POST['corps_status'] ?? 'Registered');


    /*
    |--------------------------------------------------------------------------
    | ACADEMIC INFORMATION
    |--------------------------------------------------------------------------
    */

    $institution = trim($_POST['institution'] ?? '');
    $courseOfStudy = trim($_POST['course_of_study'] ?? '');
    $qualification = trim($_POST['qualification'] ?? '');

    $graduationYear = !empty($_POST['graduation_year'])
        ? (int) $_POST['graduation_year']
        : null;


    /*
    |--------------------------------------------------------------------------
    | NEXT OF KIN
    |--------------------------------------------------------------------------
    */

    $nextOfKin = trim($_POST['next_of_kin'] ?? '');
    $nextOfKinPhone = trim($_POST['next_of_kin_phone'] ?? '');


    /*
    |--------------------------------------------------------------------------
    | CAMP ASSIGNMENT
    |--------------------------------------------------------------------------
    */

    $platoonId = !empty($_POST['platoon_id'])
        ? (int) $_POST['platoon_id']
        : null;

    $hostelId = !empty($_POST['hostel_id'])
        ? (int) $_POST['hostel_id']
        : null;


    /*
    |--------------------------------------------------------------------------
    | ACCOUNT INFORMATION
    |--------------------------------------------------------------------------
    */

    $password = $_POST['password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';


    /*
    |--------------------------------------------------------------------------
    | VALIDATION
    |--------------------------------------------------------------------------
    */

    if (
        empty($firstname) ||
        empty($lastname) ||
        empty($email) ||
        empty($phone) ||
        empty($stateCode) ||
        empty($password)
    ) {

        $errorMessage = "Please fill in all required fields.";

    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

        $errorMessage = "Please enter a valid email address.";

    } elseif ($password !== $confirmPassword) {

        $errorMessage = "Password and confirm password do not match.";

    } elseif (strlen($password) < 6) {

        $errorMessage = "Password must be at least 6 characters.";

    } else {

        try {

            /*
            |--------------------------------------------------------------------------
            | CHECK DUPLICATE USER EMAIL
            |--------------------------------------------------------------------------
            */

            $checkEmailStmt = $db->prepare("
                SELECT id
                FROM users
                WHERE email = ?
                LIMIT 1
            ");

            $checkEmailStmt->execute([$email]);

            if ($checkEmailStmt->fetch()) {

                throw new Exception(
                    "A user account with this email address already exists."
                );
            }


            /*
            |--------------------------------------------------------------------------
            | CHECK DUPLICATE USER PHONE
            |--------------------------------------------------------------------------
            */

            $checkPhoneStmt = $db->prepare("
                SELECT id
                FROM users
                WHERE phone = ?
                LIMIT 1
            ");

            $checkPhoneStmt->execute([$phone]);

            if ($checkPhoneStmt->fetch()) {

                throw new Exception(
                    "A user account with this phone number already exists."
                );
            }


            /*
            |--------------------------------------------------------------------------
            | CHECK DUPLICATE STATE CODE
            |--------------------------------------------------------------------------
            */

            $checkStateCodeStmt = $db->prepare("
                SELECT id
                FROM corps_members
                WHERE state_code = ?
                LIMIT 1
            ");

            $checkStateCodeStmt->execute([$stateCode]);

            if ($checkStateCodeStmt->fetch()) {

                throw new Exception(
                    "A Corps Member with this State Code already exists."
                );
            }


            /*
            |--------------------------------------------------------------------------
            | CHECK DUPLICATE CALL-UP NUMBER
            |--------------------------------------------------------------------------
            */

            if (!empty($callUpNumber)) {

                $checkCallUpStmt = $db->prepare("
                    SELECT id
                    FROM corps_members
                    WHERE call_up_number = ?
                    LIMIT 1
                ");

                $checkCallUpStmt->execute([$callUpNumber]);

                if ($checkCallUpStmt->fetch()) {

                    throw new Exception(
                        "A Corps Member with this Call-Up Number already exists."
                    );
                }
            }


            /*
            |--------------------------------------------------------------------------
            | GET CORPS MEMBER ROLE
            |--------------------------------------------------------------------------
            */

            $roleStmt = $db->prepare("
                SELECT id
                FROM roles
                WHERE role_name = ?
                LIMIT 1
            ");

            $roleStmt->execute(['Corps Member']);

            $corpsMemberRole = $roleStmt->fetch(PDO::FETCH_ASSOC);

            if (!$corpsMemberRole) {

                throw new Exception(
                    "Corps Member role was not found in the roles table."
                );
            }

            $roleId = $corpsMemberRole['id'];


            /*
            |--------------------------------------------------------------------------
            | HANDLE PASSPORT UPLOAD
            |--------------------------------------------------------------------------
            */

            if (
                isset($_FILES['passport']) &&
                $_FILES['passport']['error'] !== UPLOAD_ERR_NO_FILE
            ) {

                /*
                |--------------------------------------------------------------------------
                | CHECK PHP FILE UPLOAD ERROR
                |--------------------------------------------------------------------------
                */

                if ($_FILES['passport']['error'] !== UPLOAD_ERR_OK) {

                    $uploadErrors = [

                        UPLOAD_ERR_INI_SIZE =>
                            'The uploaded passport exceeds the maximum file size allowed by PHP.',

                        UPLOAD_ERR_FORM_SIZE =>
                            'The uploaded passport exceeds the maximum file size allowed by the form.',

                        UPLOAD_ERR_PARTIAL =>
                            'The passport image was only partially uploaded.',

                        UPLOAD_ERR_NO_FILE =>
                            'No passport image was uploaded.',

                        UPLOAD_ERR_NO_TMP_DIR =>
                            'The PHP temporary upload directory is missing.',

                        UPLOAD_ERR_CANT_WRITE =>
                            'PHP could not write the passport image to disk.',

                        UPLOAD_ERR_EXTENSION =>
                            'A PHP extension stopped the passport upload.'

                    ];

                    $uploadErrorCode =
                        $_FILES['passport']['error'];

                    throw new Exception(
                        $uploadErrors[$uploadErrorCode]
                        ?? 'An unknown passport upload error occurred. Error code: '
                        . $uploadErrorCode
                    );
                }


                /*
                |--------------------------------------------------------------------------
                | GET TEMPORARY UPLOADED FILE
                |--------------------------------------------------------------------------
                */

                $temporaryFile =
                    $_FILES['passport']['tmp_name'];

                if (empty($temporaryFile)) {

                    throw new Exception(
                        "The passport temporary file path is empty."
                    );
                }


                /*
                |--------------------------------------------------------------------------
                | VERIFY THAT PHP RECEIVED A REAL HTTP UPLOAD
                |--------------------------------------------------------------------------
                */

                if (!is_uploaded_file($temporaryFile)) {

                    throw new Exception(
                        "The passport file was not received as a valid PHP file upload."
                    );
                }


                /*
                |--------------------------------------------------------------------------
                | VALIDATE FILE SIZE
                |--------------------------------------------------------------------------
                |
                | Maximum allowed size = 2MB
                |--------------------------------------------------------------------------
                */

                $maximumFileSize =
                    2 * 1024 * 1024;

                if (
                    $_FILES['passport']['size']
                    > $maximumFileSize
                ) {

                    throw new Exception(
                        "Passport image must not exceed 2MB."
                    );
                }


                /*
                |--------------------------------------------------------------------------
                | VALIDATE ACTUAL FILE MIME TYPE
                |--------------------------------------------------------------------------
                |
                | This is safer than checking only the filename extension.
                |--------------------------------------------------------------------------
                */

                $allowedMimeTypes = [

                    'image/jpeg' => 'jpg',

                    'image/png' => 'png'

                ];


                /*
                |--------------------------------------------------------------------------
                | DETECT MIME TYPE
                |--------------------------------------------------------------------------
                */

                if (!class_exists('finfo')) {

                    throw new Exception(
                        "PHP Fileinfo extension is not enabled. Please enable the fileinfo extension in php.ini."
                    );
                }

                $fileInfo =
                    new finfo(FILEINFO_MIME_TYPE);

                $mimeType =
                    $fileInfo->file($temporaryFile);


                /*
                |--------------------------------------------------------------------------
                | CHECK ALLOWED IMAGE TYPE
                |--------------------------------------------------------------------------
                */

                if (
                    !isset(
                        $allowedMimeTypes[$mimeType]
                    )
                ) {

                    throw new Exception(
                        "Invalid passport image. Only JPG, JPEG and PNG images are allowed."
                    );
                }


                /*
                |--------------------------------------------------------------------------
                | GET SAFE FILE EXTENSION
                |--------------------------------------------------------------------------
                */

                $fileExtension =
                    $allowedMimeTypes[$mimeType];


                /*
                |--------------------------------------------------------------------------
                | SET PROJECT ROOT DIRECTORY
                |--------------------------------------------------------------------------
                |
                | This file is located inside:
                |
                | nysc_management_system/dashboard/
                |
                | dirname(__DIR__) returns:
                |
                | C:\xampp\htdocs\nysc_management_system
                |--------------------------------------------------------------------------
                */

                $projectRoot =
                    dirname(__DIR__);


                /*
                |--------------------------------------------------------------------------
                | SET PASSPORT UPLOAD DIRECTORY
                |--------------------------------------------------------------------------
                |
                | Final directory:
                |
                | C:\xampp\htdocs\nysc_management_system\uploads\passports\
                |--------------------------------------------------------------------------
                */

                $uploadDirectory =
                    $projectRoot .
                    DIRECTORY_SEPARATOR .
                    'uploads' .
                    DIRECTORY_SEPARATOR .
                    'passports' .
                    DIRECTORY_SEPARATOR;


                /*
                |--------------------------------------------------------------------------
                | CREATE UPLOAD DIRECTORY IF IT DOES NOT EXIST
                |--------------------------------------------------------------------------
                */

                if (!is_dir($uploadDirectory)) {

                    $directoryCreated =
                        mkdir(
                            $uploadDirectory,
                            0775,
                            true
                        );

                    if (!$directoryCreated) {

                        throw new Exception(
                            "Unable to create passport upload directory: "
                            . $uploadDirectory
                        );
                    }
                }


                /*
                |--------------------------------------------------------------------------
                | VERIFY DIRECTORY EXISTS
                |--------------------------------------------------------------------------
                */

                if (!is_dir($uploadDirectory)) {

                    throw new Exception(
                        "Passport upload directory does not exist: "
                        . $uploadDirectory
                    );
                }


                /*
                |--------------------------------------------------------------------------
                | VERIFY DIRECTORY IS WRITABLE
                |--------------------------------------------------------------------------
                */

                if (!is_writable($uploadDirectory)) {

                    throw new Exception(
                        "Passport upload directory is not writable: "
                        . $uploadDirectory
                    );
                }


                /*
                |--------------------------------------------------------------------------
                | GENERATE UNIQUE FILE NAME
                |--------------------------------------------------------------------------
                |
                | Example:
                |
                | passport_20260720_183000_a1b2c3d4e5.jpg
                |--------------------------------------------------------------------------
                */

                $newFileName =
                    'passport_' .
                    date('Ymd_His') .
                    '_' .
                    bin2hex(
                        random_bytes(8)
                    ) .
                    '.' .
                    $fileExtension;


                /*
                |--------------------------------------------------------------------------
                | CREATE FULL PHYSICAL UPLOAD DESTINATION
                |--------------------------------------------------------------------------
                |
                | Example:
                |
                | C:\xampp\htdocs\nysc_management_system\
                | uploads\passports\passport_xxxxx.jpg
                |--------------------------------------------------------------------------
                */

                $uploadDestination =
                    $uploadDirectory .
                    $newFileName;


                /*
                |--------------------------------------------------------------------------
                | MOVE UPLOADED FILE
                |--------------------------------------------------------------------------
                */

                $fileMoved =
                    move_uploaded_file(
                        $temporaryFile,
                        $uploadDestination
                    );


                /*
                |--------------------------------------------------------------------------
                | CHECK IF FILE MOVE FAILED
                |--------------------------------------------------------------------------
                */

                if (!$fileMoved) {

                    $lastError =
                        error_get_last();

                    $errorDetails = '';

                    if ($lastError !== null) {

                        $errorDetails =
                            ' PHP Error: ' .
                            (
                                $lastError['message']
                                ?? 'Unknown error'
                            );
                    }

                    throw new Exception(
                        "Unable to save the passport image to: "
                        . $uploadDestination
                        . "."
                        . $errorDetails
                    );
                }


                /*
                |--------------------------------------------------------------------------
                | VERIFY FILE EXISTS AFTER MOVING
                |--------------------------------------------------------------------------
                */

                if (!file_exists($uploadDestination)) {

                    throw new Exception(
                        "Passport upload appeared successful, but the saved file could not be found."
                    );
                }


                /*
                |--------------------------------------------------------------------------
                | SAVE RELATIVE FILE PATH
                |--------------------------------------------------------------------------
                |
                | IMPORTANT:
                |
                | Physical path used by PHP:
                |
                | C:\xampp\htdocs\nysc_management_system\
                | uploads\passports\passport_xxxxx.jpg
                |
                | Path saved in database:
                |
                | uploads/passports/passport_xxxxx.jpg
                |--------------------------------------------------------------------------
                */

                $passportPath =
                    'uploads/passports/' .
                    $newFileName;
            }


            /*
            |--------------------------------------------------------------------------
            | HASH PASSWORD
            |--------------------------------------------------------------------------
            */

            $hashedPassword =
                password_hash(
                    $password,
                    PASSWORD_DEFAULT
                );


            /*
            |--------------------------------------------------------------------------
            | START DATABASE TRANSACTION
            |--------------------------------------------------------------------------
            */

            $db->beginTransaction();


            /*
            |--------------------------------------------------------------------------
            | CREATE USER ACCOUNT
            |--------------------------------------------------------------------------
            */

            $userStmt = $db->prepare("
                INSERT INTO users
                (
                    role_id,
                    firstname,
                    lastname,
                    othername,
                    email,
                    phone,
                    password,
                    avatar,
                    gender,
                    status
                )
                VALUES
                (
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    'active'
                )
            ");


            /*
            |--------------------------------------------------------------------------
            | EXECUTE USER INSERT
            |--------------------------------------------------------------------------
            */

            $userStmt->execute([

                $roleId,

                $firstname,

                $lastname,

                !empty($othername)
                    ? $othername
                    : null,

                $email,

                $phone,

                $hashedPassword,

                $passportPath,

                !empty($gender)
                    ? $gender
                    : null

            ]);


            /*
            |--------------------------------------------------------------------------
            | GET NEW USER ID
            |--------------------------------------------------------------------------
            */

            $newUserId =
                $db->lastInsertId();


            /*
            |--------------------------------------------------------------------------
            | CREATE CORPS MEMBER PROFILE
            |--------------------------------------------------------------------------
            */

            $corpsStmt = $db->prepare("
                INSERT INTO corps_members
                (
                    user_id,
                    state_id,
                    lga_id,
                    platoon_id,
                    hostel_id,
                    state_code,
                    call_up_number,
                    firstname,
                    lastname,
                    othername,
                    gender,
                    date_of_birth,
                    phone,
                    email,
                    institution,
                    course_of_study,
                    qualification,
                    graduation_year,
                    marital_status,
                    passport,
                    home_address,
                    next_of_kin,
                    next_of_kin_phone,
                    batch,
                    stream,
                    year_of_service,
                    registration_date,
                    status
                )
                VALUES
                (
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?
                )
            ");


            /*
            |--------------------------------------------------------------------------
            | EXECUTE CORPS MEMBER INSERT
            |--------------------------------------------------------------------------
            */

            $corpsStmt->execute([

                $newUserId,

                $stateId,

                $lgaId,

                $platoonId,

                $hostelId,

                $stateCode,

                !empty($callUpNumber)
                    ? $callUpNumber
                    : null,

                $firstname,

                $lastname,

                !empty($othername)
                    ? $othername
                    : null,

                !empty($gender)
                    ? $gender
                    : null,

                !empty($dateOfBirth)
                    ? $dateOfBirth
                    : null,

                $phone,

                $email,

                !empty($institution)
                    ? $institution
                    : null,

                !empty($courseOfStudy)
                    ? $courseOfStudy
                    : null,

                !empty($qualification)
                    ? $qualification
                    : null,

                $graduationYear,

                $maritalStatus,

                $passportPath,

                !empty($homeAddress)
                    ? $homeAddress
                    : null,

                !empty($nextOfKin)
                    ? $nextOfKin
                    : null,

                !empty($nextOfKinPhone)
                    ? $nextOfKinPhone
                    : null,

                !empty($batch)
                    ? $batch
                    : null,

                !empty($stream)
                    ? $stream
                    : null,

                $yearOfService,

                $registrationDate,

                $corpsStatus

            ]);


            /*
            |--------------------------------------------------------------------------
            | COMMIT DATABASE TRANSACTION
            |--------------------------------------------------------------------------
            */

            $db->commit();


            /*
            |--------------------------------------------------------------------------
            | SUCCESS MESSAGE
            |--------------------------------------------------------------------------
            */

            $_SESSION['success_message'] =
                "Corps Member registered successfully. The login account has also been created.";


            /*
            |--------------------------------------------------------------------------
            | REDIRECT TO ALL CORPS MEMBERS
            |--------------------------------------------------------------------------
            */

            header(
                "Location: register_corps_member.php"
            );

            exit;


        } catch (Throwable $e) {


            /*
            |--------------------------------------------------------------------------
            | ROLLBACK DATABASE TRANSACTION
            |--------------------------------------------------------------------------
            */

            if ($db->inTransaction()) {

                $db->rollBack();
            }


            /*
            |--------------------------------------------------------------------------
            | DELETE PASSPORT IF DATABASE REGISTRATION FAILED
            |--------------------------------------------------------------------------
            |
            | For example:
            |
            | If the passport was uploaded successfully but creating the user
            | or Corps Member record failed, delete the uploaded image.
            |--------------------------------------------------------------------------
            */

            if (
                !empty($uploadDestination) &&
                file_exists($uploadDestination)
            ) {

                unlink(
                    $uploadDestination
                );
            }


            /*
            |--------------------------------------------------------------------------
            | DISPLAY ERROR
            |--------------------------------------------------------------------------
            */

            $errorMessage =
                "Unable to register Corps Member: " .
                $e->getMessage();
        }
    }
}


/*
|--------------------------------------------------------------------------
| LOAD HEADER AND SIDEBAR
|--------------------------------------------------------------------------
*/

require_once '../includes/header.php';

require_once '../includes/sidebar.php';

?>

<div class="overlay bg-black bg-opacity-50 w-100 h-100 position-fixed z-9 visibility-hidden opacity-0 duration-300">
</div>


<main class="dashboard-main">

    <?php require_once '../includes/topbar.php'; ?>


    <div class="dashboard-main-body">


        <!-- ================================================================
        BREADCRUMB
        ================================================================= -->

        <div class="breadcrumb d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">

            <div>

                <h6 class="fw-semibold mb-0">
                    <?= htmlspecialchars($pageTitle) ?>
                </h6>

                <p class="text-neutral-600 mt-4 mb-0">

                    <?= APP_SHORT_NAME ?>

                    >

                    Corps Members

                    >

                    <?= htmlspecialchars($pageTitle) ?>

                </p>

            </div>

        </div>



        <!-- ================================================================
        SUCCESS MESSAGE
        ================================================================= -->

        <?php if (!empty($successMessage)): ?>

        <div class="alert alert-success alert-dismissible fade show mb-24">

            <i class="ri-checkbox-circle-line me-2"></i>

            <?= htmlspecialchars($successMessage) ?>

            <button type="button" class="btn-close" data-bs-dismiss="alert">
            </button>

        </div>

        <?php endif; ?>



        <!-- ================================================================
        ERROR MESSAGE
        ================================================================= -->

        <?php if (!empty($errorMessage)): ?>

        <div class="alert alert-danger alert-dismissible fade show mb-24">

            <i class="ri-error-warning-line me-2"></i>

            <?= htmlspecialchars($errorMessage) ?>

            <button type="button" class="btn-close" data-bs-dismiss="alert">
            </button>

        </div>

        <?php endif; ?>



        <!-- ================================================================
        REGISTRATION FORM
        ================================================================= -->

        <form method="POST" enctype="multipart/form-data" id="corpsMemberRegistrationForm">


            <!-- ============================================================
            PERSONAL INFORMATION
            ============================================================= -->

            <div class="card mb-24">

                <div class="card-header border-bottom border-neutral-200">

                    <h6 class="text-lg fw-semibold mb-0">

                        Personal Information

                    </h6>

                </div>


                <div class="card-body">

                    <div class="row gy-20">


                        <!-- PASSPORT -->

                        <div class="col-12">

                            <label class="form-label fw-semibold text-primary-light text-sm mb-8">

                                Passport Photograph

                            </label>

                            <div class="d-flex align-items-center gap-16">

                                <img id="passportPreview" src="../assets/images/user-grid/user-grid-img13.png"
                                    alt="Passport" class="w-100-px h-100-px rounded-circle object-fit-cover border">

                                <div>

                                    <input type="file" name="passport" id="passport" class="form-control"
                                        accept=".jpg,.jpeg,.png">

                                    <small class="text-secondary-light">

                                        JPG, JPEG or PNG. Maximum size 2MB.

                                    </small>

                                </div>

                            </div>

                        </div>


                        <!-- FIRST NAME -->

                        <div class="col-md-4">

                            <label class="form-label">

                                First Name
                                <span class="text-danger">*</span>

                            </label>

                            <input type="text" name="firstname" class="form-control"
                                value="<?= htmlspecialchars($_POST['firstname'] ?? '') ?>" required>

                        </div>


                        <!-- LAST NAME -->

                        <div class="col-md-4">

                            <label class="form-label">

                                Last Name
                                <span class="text-danger">*</span>

                            </label>

                            <input type="text" name="lastname" class="form-control"
                                value="<?= htmlspecialchars($_POST['lastname'] ?? '') ?>" required>

                        </div>


                        <!-- OTHER NAME -->

                        <div class="col-md-4">

                            <label class="form-label">

                                Other Name

                            </label>

                            <input type="text" name="othername" class="form-control"
                                value="<?= htmlspecialchars($_POST['othername'] ?? '') ?>">

                        </div>


                        <!-- GENDER -->

                        <div class="col-md-4">

                            <label class="form-label">

                                Gender

                            </label>

                            <select name="gender" class="form-control form-select">

                                <option value="">
                                    Select Gender
                                </option>

                                <option value="Male" <?= ($_POST['gender'] ?? '') === 'Male' ? 'selected' : '' ?>>

                                    Male

                                </option>

                                <option value="Female" <?= ($_POST['gender'] ?? '') === 'Female' ? 'selected' : '' ?>>

                                    Female

                                </option>

                            </select>

                        </div>


                        <!-- DATE OF BIRTH -->

                        <div class="col-md-4">

                            <label class="form-label">

                                Date of Birth

                            </label>

                            <input type="date" name="date_of_birth" class="form-control"
                                value="<?= htmlspecialchars($_POST['date_of_birth'] ?? '') ?>">

                        </div>


                        <!-- MARITAL STATUS -->

                        <div class="col-md-4">

                            <label class="form-label">

                                Marital Status

                            </label>

                            <select name="marital_status" class="form-control form-select">

                                <?php

                                $maritalStatuses = [
                                    'Single',
                                    'Married',
                                    'Divorced',
                                    'Widowed'
                                ];

                                foreach ($maritalStatuses as $status):

                                ?>

                                <option value="<?= $status ?>"
                                    <?= ($_POST['marital_status'] ?? 'Single') === $status ? 'selected' : '' ?>>

                                    <?= $status ?>

                                </option>

                                <?php endforeach; ?>

                            </select>

                        </div>


                        <!-- PHONE -->

                        <div class="col-md-6">

                            <label class="form-label">

                                Phone Number
                                <span class="text-danger">*</span>

                            </label>

                            <input type="text" name="phone" class="form-control" maxlength="15"
                                value="<?= htmlspecialchars($_POST['phone'] ?? '') ?>" required>

                        </div>


                        <!-- EMAIL -->

                        <div class="col-md-6">

                            <label class="form-label">

                                Email Address
                                <span class="text-danger">*</span>

                            </label>

                            <input type="email" name="email" class="form-control"
                                value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" required>

                        </div>


                        <!-- HOME ADDRESS -->

                        <div class="col-12">

                            <label class="form-label">

                                Home Address

                            </label>

                            <textarea name="home_address" class="form-control"
                                rows="3"><?= htmlspecialchars($_POST['home_address'] ?? '') ?></textarea>

                        </div>


                    </div>

                </div>

            </div>



            <!-- ============================================================
            NYSC INFORMATION
            ============================================================= -->

            <div class="card mb-24">

                <div class="card-header border-bottom border-neutral-200">

                    <h6 class="text-lg fw-semibold mb-0">

                        NYSC Information

                    </h6>

                </div>


                <div class="card-body">

                    <div class="row gy-20">


                        <!-- STATE CODE -->

                        <div class="col-md-6">

                            <label class="form-label">

                                State Code
                                <span class="text-danger">*</span>

                            </label>

                            <input type="text" name="state_code" class="form-control" placeholder="Example: LA/26A/1234"
                                value="<?= htmlspecialchars($_POST['state_code'] ?? '') ?>" required>

                        </div>


                        <!-- CALL UP NUMBER -->

                        <div class="col-md-6">

                            <label class="form-label">

                                Call-Up Number

                            </label>

                            <input type="text" name="call_up_number" class="form-control"
                                placeholder="Example: NYSC/ABC/2026/123456"
                                value="<?= htmlspecialchars($_POST['call_up_number'] ?? '') ?>">

                        </div>


                        <!-- STATE -->

                        <div class="col-md-6">

                            <label class="form-label">

                                State

                            </label>

                            <select name="state_id" id="state_id" class="form-control form-select">

                                <option value="">

                                    Select State

                                </option>

                                <?php foreach ($states as $state): ?>

                                <option value="<?= $state['id'] ?>"
                                    <?= ($_POST['state_id'] ?? '') == $state['id'] ? 'selected' : '' ?>>

                                    <?= htmlspecialchars($state['state_name']) ?>

                                </option>

                                <?php endforeach; ?>

                            </select>

                        </div>


                        <!-- LGA -->

                        <div class="col-md-6">

                            <label class="form-label">

                                Local Government Area

                            </label>

                            <select name="lga_id" id="lga_id" class="form-control form-select">

                                <option value="">

                                    Select State First

                                </option>

                            </select>

                        </div>


                        <!-- BATCH -->

                        <div class="col-md-4">

                            <label class="form-label">

                                Batch

                            </label>

                            <select name="batch" class="form-control form-select">

                                <option value="">
                                    Select Batch
                                </option>

                                <option value="Batch A" <?= ($_POST['batch'] ?? '') === 'Batch A' ? 'selected' : '' ?>>

                                    Batch A

                                </option>

                                <option value="Batch B" <?= ($_POST['batch'] ?? '') === 'Batch B' ? 'selected' : '' ?>>

                                    Batch B

                                </option>

                                <option value="Batch C" <?= ($_POST['batch'] ?? '') === 'Batch C' ? 'selected' : '' ?>>

                                    Batch C

                                </option>

                            </select>

                        </div>


                        <!-- STREAM -->

                        <div class="col-md-4">

                            <label class="form-label">

                                Stream

                            </label>

                            <select name="stream" class="form-control form-select">

                                <option value="">
                                    Select Stream
                                </option>

                                <option value="Stream I"
                                    <?= ($_POST['stream'] ?? '') === 'Stream I' ? 'selected' : '' ?>>

                                    Stream I

                                </option>

                                <option value="Stream II"
                                    <?= ($_POST['stream'] ?? '') === 'Stream II' ? 'selected' : '' ?>>

                                    Stream II

                                </option>

                            </select>

                        </div>


                        <!-- YEAR OF SERVICE -->

                        <div class="col-md-4">

                            <label class="form-label">

                                Year of Service

                            </label>

                            <input type="number" name="year_of_service" class="form-control" min="2000" max="2100"
                                value="<?= htmlspecialchars($_POST['year_of_service'] ?? date('Y')) ?>">

                        </div>


                        <!-- REGISTRATION DATE -->

                        <div class="col-md-6">

                            <label class="form-label">

                                Registration Date

                            </label>

                            <input type="date" name="registration_date" class="form-control"
                                value="<?= htmlspecialchars($_POST['registration_date'] ?? date('Y-m-d')) ?>">

                        </div>


                        <!-- STATUS -->

                        <div class="col-md-6">

                            <label class="form-label">

                                Service Status

                            </label>

                            <select name="corps_status" class="form-control form-select">

                                <?php

                                $corpsStatuses = [
                                    'Registered',
                                    'In Camp',
                                    'Serving',
                                    'Completed',
                                    'Relocated',
                                    'Suspended'
                                ];

                                foreach ($corpsStatuses as $status):

                                ?>

                                <option value="<?= $status ?>"
                                    <?= ($_POST['corps_status'] ?? 'Registered') === $status ? 'selected' : '' ?>>

                                    <?= $status ?>

                                </option>

                                <?php endforeach; ?>

                            </select>

                        </div>


                    </div>

                </div>

            </div>



            <!-- ============================================================
            ACADEMIC INFORMATION
            ============================================================= -->

            <div class="card mb-24">

                <div class="card-header border-bottom border-neutral-200">

                    <h6 class="text-lg fw-semibold mb-0">

                        Academic Information

                    </h6>

                </div>


                <div class="card-body">

                    <div class="row gy-20">


                        <div class="col-md-6">

                            <label class="form-label">

                                Institution

                            </label>

                            <input type="text" name="institution" class="form-control"
                                value="<?= htmlspecialchars($_POST['institution'] ?? '') ?>">

                        </div>


                        <div class="col-md-6">

                            <label class="form-label">

                                Course of Study

                            </label>

                            <input type="text" name="course_of_study" class="form-control"
                                value="<?= htmlspecialchars($_POST['course_of_study'] ?? '') ?>">

                        </div>


                        <div class="col-md-6">

                            <label class="form-label">

                                Qualification

                            </label>

                            <select name="qualification" class="form-control form-select">

                                <option value="">
                                    Select Qualification
                                </option>

                                <?php

                                $qualifications = [
                                    'B.Sc',
                                    'B.A',
                                    'B.Ed',
                                    'B.Eng',
                                    'B.Tech',
                                    'HND',
                                    'LL.B',
                                    'MBBS',
                                    'Other'
                                ];

                                foreach ($qualifications as $qualification):

                                ?>

                                <option value="<?= $qualification ?>"
                                    <?= ($_POST['qualification'] ?? '') === $qualification ? 'selected' : '' ?>>

                                    <?= $qualification ?>

                                </option>

                                <?php endforeach; ?>

                            </select>

                        </div>


                        <div class="col-md-6">

                            <label class="form-label">

                                Graduation Year

                            </label>

                            <input type="number" name="graduation_year" class="form-control" min="1980"
                                max="<?= date('Y') ?>" value="<?= htmlspecialchars($_POST['graduation_year'] ?? '') ?>">

                        </div>


                    </div>

                </div>

            </div>



            <!-- ============================================================
            NEXT OF KIN
            ============================================================= -->

            <div class="card mb-24">

                <div class="card-header border-bottom border-neutral-200">

                    <h6 class="text-lg fw-semibold mb-0">

                        Next of Kin Information

                    </h6>

                </div>


                <div class="card-body">

                    <div class="row gy-20">


                        <div class="col-md-6">

                            <label class="form-label">

                                Next of Kin Full Name

                            </label>

                            <input type="text" name="next_of_kin" class="form-control"
                                value="<?= htmlspecialchars($_POST['next_of_kin'] ?? '') ?>">

                        </div>


                        <div class="col-md-6">

                            <label class="form-label">

                                Next of Kin Phone Number

                            </label>

                            <input type="text" name="next_of_kin_phone" class="form-control"
                                value="<?= htmlspecialchars($_POST['next_of_kin_phone'] ?? '') ?>">

                        </div>


                    </div>

                </div>

            </div>



            <!-- ============================================================
            CAMP ASSIGNMENT
            ============================================================= -->

            <div class="card mb-24">

                <div class="card-header border-bottom border-neutral-200">

                    <h6 class="text-lg fw-semibold mb-0">

                        Camp Assignment

                    </h6>

                    <p class="text-secondary-light text-sm mb-0 mt-4">

                        These fields are optional. The Corps Member can be assigned later through Camp Management.

                    </p>

                </div>


                <div class="card-body">

                    <div class="row gy-20">


                        <!-- PLATOON -->

                        <div class="col-md-6">

                            <label class="form-label">

                                Platoon

                            </label>

                            <select name="platoon_id" class="form-control form-select">

                                <option value="">

                                    Not Assigned

                                </option>

                                <?php foreach ($platoons as $platoon): ?>

                                <option value="<?= $platoon['id'] ?>"
                                    <?= ($_POST['platoon_id'] ?? '') == $platoon['id'] ? 'selected' : '' ?>>

                                    <?= htmlspecialchars($platoon['platoon_name']) ?>

                                    -

                                    <?= htmlspecialchars($platoon['platoon_code']) ?>

                                </option>

                                <?php endforeach; ?>

                            </select>

                        </div>


                        <!-- HOSTEL -->

                        <div class="col-md-6">

                            <label class="form-label">

                                Hostel

                            </label>

                            <select name="hostel_id" class="form-control form-select">

                                <option value="">

                                    Not Assigned

                                </option>

                                <?php foreach ($hostels as $hostel): ?>

                                <option value="<?= $hostel['id'] ?>"
                                    <?= ($_POST['hostel_id'] ?? '') == $hostel['id'] ? 'selected' : '' ?>>

                                    <?= htmlspecialchars($hostel['hostel_name']) ?>

                                    (<?= htmlspecialchars($hostel['gender']) ?>)

                                </option>

                                <?php endforeach; ?>

                            </select>

                        </div>


                    </div>

                </div>

            </div>



            <!-- ============================================================
            LOGIN ACCOUNT INFORMATION
            ============================================================= -->

            <div class="card mb-24">

                <div class="card-header border-bottom border-neutral-200">

                    <h6 class="text-lg fw-semibold mb-0">

                        Login Account Information

                    </h6>

                    <p class="text-secondary-light text-sm mb-0 mt-4">

                        The Corps Member will use the email address entered above and this password to log in.

                    </p>

                </div>


                <div class="card-body">

                    <div class="row gy-20">


                        <div class="col-md-6">

                            <label class="form-label">

                                Password
                                <span class="text-danger">*</span>

                            </label>

                            <input type="password" name="password" id="password" class="form-control" minlength="6"
                                required>

                        </div>


                        <div class="col-md-6">

                            <label class="form-label">

                                Confirm Password
                                <span class="text-danger">*</span>

                            </label>

                            <input type="password" name="confirm_password" id="confirm_password" class="form-control"
                                minlength="6" required>

                        </div>


                    </div>

                </div>

            </div>



            <!-- ============================================================
            FORM BUTTONS
            ============================================================= -->

            <div class="card">

                <div class="card-body">

                    <div class="d-flex align-items-center justify-content-end gap-3">


                        <button type="reset" class="btn btn-outline-danger-600">

                            <i class="ri-refresh-line me-1"></i>

                            Reset

                        </button>


                        <button type="submit" class="btn btn-primary-600">

                            <i class="ri-user-add-line me-1"></i>

                            Register Corps Member

                        </button>


                    </div>

                </div>

            </div>


        </form>


    </div>


</main>



<script>
/*
|--------------------------------------------------------------------------
| PASSPORT IMAGE PREVIEW
|--------------------------------------------------------------------------
*/

const passportInput =
    document.getElementById(
        'passport'
    );

if (passportInput) {

    passportInput.addEventListener(
        'change',
        function(event) {

            const file =
                event.target.files[0];

            if (!file) {
                return;
            }

            const reader =
                new FileReader();

            reader.onload =
                function(e) {

                    document
                        .getElementById(
                            'passportPreview'
                        )
                        .src =
                        e.target.result;

                };

            reader.readAsDataURL(
                file
            );

        }
    );

}


/*
|--------------------------------------------------------------------------
| STATE -> LGA DYNAMIC DROPDOWN
|--------------------------------------------------------------------------
*/

const stateSelect =
    document.getElementById(
        'state_id'
    );

const lgaSelect =
    document.getElementById(
        'lga_id'
    );


if (
    stateSelect &&
    lgaSelect
) {

    stateSelect.addEventListener(
        'change',
        function() {

            const stateId =
                this.value;


            /*
            |--------------------------------------------------------------------------
            | RESET LGA
            |--------------------------------------------------------------------------
            */

            lgaSelect.innerHTML =
                '<option value="">Loading...</option>';


            if (!stateId) {

                lgaSelect.innerHTML =
                    '<option value="">Select State First</option>';

                return;

            }


            /*
            |--------------------------------------------------------------------------
            | FETCH LGAs
            |--------------------------------------------------------------------------
            */

            fetch(
                    '../ajax/get-lgas.php?state_id=' +
                    encodeURIComponent(
                        stateId
                    )
                )

                .then(
                    response => {

                        if (!response.ok) {

                            throw new Error(
                                'Unable to load LGAs.'
                            );

                        }

                        return response.json();

                    }
                )

                .then(
                    data => {

                        lgaSelect.innerHTML =
                            '<option value="">Select LGA</option>';


                        data.forEach(
                            function(lga) {

                                const option =
                                    document.createElement(
                                        'option'
                                    );

                                option.value =
                                    lga.id;

                                option.textContent =
                                    lga.lga_name;

                                lgaSelect.appendChild(
                                    option
                                );

                            }
                        );

                    }
                )

                .catch(
                    error => {

                        console.error(
                            error
                        );

                        lgaSelect.innerHTML =
                            '<option value="">Unable to load LGAs</option>';

                    }
                );

        }
    );

}
</script>


<?php

require_once '../includes/footer.php';

?>