<?php

$pageTitle = "Edit Corps Member";

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

require_login();

$user = current_user();


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

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

$uploadDestination = null;


/*
|--------------------------------------------------------------------------
| GET CORPS MEMBER ID
|--------------------------------------------------------------------------
*/

$corpsMemberId = isset($_GET['id'])
    ? (int) $_GET['id']
    : 0;


if ($corpsMemberId <= 0) {

    $_SESSION['error_message'] =
        "Invalid Corps Member selected.";

    header(
        "Location: all-corps-members.php"
    );

    exit;
}


/*
|--------------------------------------------------------------------------
| FUNCTION: GET CORPS MEMBER
|--------------------------------------------------------------------------
*/

function getCorpsMember(
    PDO $db,
    int $corpsMemberId
) {

    $stmt = $db->prepare("
        SELECT
            cm.*,
            u.status AS account_status,
            u.avatar AS user_avatar

        FROM corps_members cm

        LEFT JOIN users u
            ON cm.user_id = u.id

        WHERE cm.id = ?

        LIMIT 1
    ");

    $stmt->execute([
        $corpsMemberId
    ]);

    return $stmt->fetch(PDO::FETCH_ASSOC);
}


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

$corpsMember = getCorpsMember(
    $db,
    $corpsMemberId
);


if (!$corpsMember) {

    $_SESSION['error_message'] =
        "Corps Member not found.";

    header(
        "Location: all-corps-members.php"
    );

    exit;
}


/*
|--------------------------------------------------------------------------
| 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
|--------------------------------------------------------------------------
*/

$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
);


/*
|--------------------------------------------------------------------------
| GET CURRENT LGAs
|--------------------------------------------------------------------------
|
| This allows the current LGA to be displayed immediately when the
| edit page loads.
|--------------------------------------------------------------------------
*/

$currentLgas = [];

if (!empty($corpsMember['state_id'])) {

    $lgaStmt = $db->prepare("
        SELECT
            id,
            lga_name

        FROM local_governments

        WHERE state_id = ?

        ORDER BY lga_name ASC
    ");

    $lgaStmt->execute([
        $corpsMember['state_id']
    ]);

    $currentLgas = $lgaStmt->fetchAll(
        PDO::FETCH_ASSOC
    );
}


/*
|--------------------------------------------------------------------------
| PROCESS UPDATE FORM
|--------------------------------------------------------------------------
*/

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


    /*
    |--------------------------------------------------------------------------
    | 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']
            : null;

    $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 STATUS
    |--------------------------------------------------------------------------
    */

    $accountStatus = trim(
        $_POST['account_status'] ?? 'active'
    );


    /*
    |--------------------------------------------------------------------------
    | VALIDATE CORPS MEMBER STATUS
    |--------------------------------------------------------------------------
    */

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


    if (
        !in_array(
            $corpsStatus,
            $allowedCorpsStatuses,
            true
        )
    ) {

        $corpsStatus = 'Registered';
    }


    /*
    |--------------------------------------------------------------------------
    | VALIDATE USER ACCOUNT STATUS
    |--------------------------------------------------------------------------
    */

    $allowedAccountStatuses = [
        'active',
        'inactive',
        'suspended'
    ];


    if (
        !in_array(
            $accountStatus,
            $allowedAccountStatuses,
            true
        )
    ) {

        $accountStatus = 'active';
    }


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

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

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

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

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

    } else {

        try {


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

            $checkEmailStmt = $db->prepare("
                SELECT id

                FROM users

                WHERE email = ?

                AND id != ?

                LIMIT 1
            ");

            $checkEmailStmt->execute([
                $email,
                $corpsMember['user_id']
            ]);


            if ($checkEmailStmt->fetch()) {

                throw new Exception(
                    "Another user account already uses this email address."
                );
            }


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

            $checkPhoneStmt = $db->prepare("
                SELECT id

                FROM users

                WHERE phone = ?

                AND id != ?

                LIMIT 1
            ");

            $checkPhoneStmt->execute([
                $phone,
                $corpsMember['user_id']
            ]);


            if ($checkPhoneStmt->fetch()) {

                throw new Exception(
                    "Another user account already uses this phone number."
                );
            }


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

            $checkStateCodeStmt = $db->prepare("
                SELECT id

                FROM corps_members

                WHERE state_code = ?

                AND id != ?

                LIMIT 1
            ");

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


            if ($checkStateCodeStmt->fetch()) {

                throw new Exception(
                    "Another Corps Member already uses this State Code."
                );
            }


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

            if (!empty($callUpNumber)) {

                $checkCallUpStmt = $db->prepare("
                    SELECT id

                    FROM corps_members

                    WHERE call_up_number = ?

                    AND id != ?

                    LIMIT 1
                ");

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


                if ($checkCallUpStmt->fetch()) {

                    throw new Exception(
                        "Another Corps Member already uses this Call-Up Number."
                    );
                }
            }


            /*
            |--------------------------------------------------------------------------
            | CURRENT PASSPORT
            |--------------------------------------------------------------------------
            */

            $passportPath =
                $corpsMember['passport'];


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

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


                /*
                |--------------------------------------------------------------------------
                | CHECK UPLOAD ERROR
                |--------------------------------------------------------------------------
                */

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

                    throw new Exception(
                        "An error occurred while uploading the passport."
                    );
                }


                /*
                |--------------------------------------------------------------------------
                | ALLOWED EXTENSIONS
                |--------------------------------------------------------------------------
                */

                $allowedExtensions = [
                    'jpg',
                    'jpeg',
                    'png'
                ];


                $originalFileName =
                    $_FILES['passport']['name'];


                $fileExtension = strtolower(
                    pathinfo(
                        $originalFileName,
                        PATHINFO_EXTENSION
                    )
                );


                if (
                    !in_array(
                        $fileExtension,
                        $allowedExtensions,
                        true
                    )
                ) {

                    throw new Exception(
                        "Passport must be a JPG, JPEG or PNG image."
                    );
                }


                /*
                |--------------------------------------------------------------------------
                | MAXIMUM FILE SIZE: 2MB
                |--------------------------------------------------------------------------
                */

                if (
                    $_FILES['passport']['size']
                    > 2 * 1024 * 1024
                ) {

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


                /*
                |--------------------------------------------------------------------------
                | UPLOAD DIRECTORY
                |--------------------------------------------------------------------------
                |
                | dashboard/ is inside the project directory.
                |
                | dirname(__DIR__) returns:
                |
                | nysc_management_system/
                |
                | Therefore the upload path becomes:
                |
                | nysc_management_system/uploads/passports/
                |--------------------------------------------------------------------------
                */

                $uploadDirectory =
                    dirname(__DIR__)
                    . '/uploads/passports/';


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

                if (!is_dir($uploadDirectory)) {

                    if (
                        !mkdir(
                            $uploadDirectory,
                            0775,
                            true
                        )
                    ) {

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


                /*
                |--------------------------------------------------------------------------
                | CHECK DIRECTORY PERMISSION
                |--------------------------------------------------------------------------
                */

                if (!is_writable($uploadDirectory)) {

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


                /*
                |--------------------------------------------------------------------------
                | GENERATE UNIQUE FILE NAME
                |--------------------------------------------------------------------------
                */

                $newFileName =
                    'passport_'
                    . time()
                    . '_'
                    . bin2hex(
                        random_bytes(5)
                    )
                    . '.'
                    . $fileExtension;


                /*
                |--------------------------------------------------------------------------
                | FULL DESTINATION
                |--------------------------------------------------------------------------
                */

                $uploadDestination =
                    $uploadDirectory
                    . $newFileName;


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

                if (
                    !move_uploaded_file(
                        $_FILES['passport']['tmp_name'],
                        $uploadDestination
                    )
                ) {

                    throw new Exception(
                        "Unable to save the passport image."
                    );
                }


                /*
                |--------------------------------------------------------------------------
                | DATABASE RELATIVE PATH
                |--------------------------------------------------------------------------
                */

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


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

            $db->beginTransaction();


            /*
            |--------------------------------------------------------------------------
            | UPDATE USER ACCOUNT
            |--------------------------------------------------------------------------
            */

            $updateUserStmt = $db->prepare("
                UPDATE users

                SET
                    firstname = ?,
                    lastname = ?,
                    othername = ?,
                    email = ?,
                    phone = ?,
                    avatar = ?,
                    gender = ?,
                    status = ?

                WHERE id = ?
            ");


            $updateUserStmt->execute([

                $firstname,

                $lastname,

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

                $email,

                $phone,

                $passportPath,

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

                $accountStatus,

                $corpsMember['user_id']

            ]);


            /*
            |--------------------------------------------------------------------------
            | UPDATE CORPS MEMBER PROFILE
            |--------------------------------------------------------------------------
            */

            $updateCorpsStmt = $db->prepare("
                UPDATE corps_members

                SET
                    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 = ?

                WHERE id = ?
            ");


            $updateCorpsStmt->execute([

                $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,

                $corpsMemberId

            ]);


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

            $db->commit();


            /*
            |--------------------------------------------------------------------------
            | DELETE OLD PASSPORT IF A NEW ONE WAS UPLOADED
            |--------------------------------------------------------------------------
            */

            if (
                !empty($uploadDestination) &&
                !empty($corpsMember['passport']) &&
                $corpsMember['passport'] !== $passportPath
            ) {

                $oldPassportFile =
                    dirname(__DIR__)
                    . '/'
                    . ltrim(
                        $corpsMember['passport'],
                        '/'
                    );


                if (
                    file_exists($oldPassportFile) &&
                    is_file($oldPassportFile)
                ) {

                    @unlink(
                        $oldPassportFile
                    );
                }
            }


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

            $_SESSION['success_message'] =
                "Corps Member updated successfully.";


            /*
            |--------------------------------------------------------------------------
            | REDIRECT TO PROFILE
            |--------------------------------------------------------------------------
            */

            header(
                "Location: view-corps-member.php?id="
                . $corpsMemberId
            );

            exit;


        } catch (Throwable $e) {


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

            if ($db->inTransaction()) {

                $db->rollBack();
            }


            /*
            |--------------------------------------------------------------------------
            | DELETE NEW PASSPORT IF DATABASE UPDATE FAILED
            |--------------------------------------------------------------------------
            */

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

                @unlink(
                    $uploadDestination
                );
            }


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


    /*
    |--------------------------------------------------------------------------
    | REFRESH CORPS MEMBER AFTER FAILED POST
    |--------------------------------------------------------------------------
    |
    | The values entered by the user will still be displayed using $_POST.
    |--------------------------------------------------------------------------
    */

    $corpsMember = getCorpsMember(
        $db,
        $corpsMemberId
    );
}


/*
|--------------------------------------------------------------------------
| HELPER FUNCTION FOR FORM VALUES
|--------------------------------------------------------------------------
|
| If POST data exists, display it.
| Otherwise display the existing database value.
|--------------------------------------------------------------------------
*/

function oldValue(
    string $field,
    $databaseValue = ''
) {

    return $_POST[$field]
        ?? $databaseValue
        ?? '';
}


/*
|--------------------------------------------------------------------------
| CURRENT PASSPORT URL
|--------------------------------------------------------------------------
*/

if (!empty($corpsMember['passport'])) {

    $passportUrl =
        '../'
        . ltrim(
            $corpsMember['passport'],
            '/'
        );

} else {

    $passportUrl =
        '../assets/images/user-grid/user-grid-img13.png';
}


/*
|--------------------------------------------------------------------------
| 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">

                    <?= htmlspecialchars(APP_SHORT_NAME) ?>

                    >

                    Corps Members

                    >

                    <?= htmlspecialchars($pageTitle) ?>

                </p>

            </div>


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

                <a href="view_corps_member.php?id=<?= (int) $corpsMemberId ?>" class="btn btn-outline-primary">

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

                    View Profile

                </a>


                <a href="corps_members.php" class="btn btn-outline-secondary">

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

                    Back

                </a>

            </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; ?>



        <!-- ================================================================
        EDIT FORM
        ================================================================= -->

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


            <!-- ============================================================
            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="<?= htmlspecialchars($passportUrl) ?>" 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">

                                        Leave empty to keep the current passport.
                                        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(
                                    oldValue(
                                        'firstname',
                                        $corpsMember['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(
                                    oldValue(
                                        'lastname',
                                        $corpsMember['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(
                                    oldValue(
                                        'othername',
                                        $corpsMember['othername']
                                    )
                                ) ?>">

                        </div>



                        <!-- GENDER -->

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

                            <label class="form-label">

                                Gender

                            </label>


                            <?php

                            $selectedGender = oldValue(
                                'gender',
                                $corpsMember['gender']
                            );

                            ?>


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


                                <option value="">

                                    Select Gender

                                </option>


                                <option value="Male" <?= $selectedGender === 'Male'
                                        ? 'selected'
                                        : '' ?>>

                                    Male

                                </option>


                                <option value="Female" <?= $selectedGender === '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(
                                    oldValue(
                                        'date_of_birth',
                                        $corpsMember['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'
                                ];


                                $selectedMaritalStatus =
                                    oldValue(
                                        'marital_status',
                                        $corpsMember['marital_status']
                                    );


                                foreach (
                                    $maritalStatuses as $status
                                ):

                                ?>


                                <option value="<?= htmlspecialchars($status) ?>" <?= $selectedMaritalStatus === $status
                                            ? 'selected'
                                            : '' ?>>

                                    <?= htmlspecialchars($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(
                                    oldValue(
                                        'phone',
                                        $corpsMember['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(
                                    oldValue(
                                        'email',
                                        $corpsMember['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(
                                    oldValue(
                                        'home_address',
                                        $corpsMember['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(
                                    oldValue(
                                        'state_code',
                                        $corpsMember['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(
                                    oldValue(
                                        'call_up_number',
                                        $corpsMember['call_up_number']
                                    )
                                ) ?>">

                        </div>



                        <!-- STATE -->

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

                            <label class="form-label">

                                State

                            </label>


                            <?php

                            $selectedStateId =
                                oldValue(
                                    'state_id',
                                    $corpsMember['state_id']
                                );

                            ?>


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


                                <option value="">

                                    Select State

                                </option>


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


                                <option value="<?= (int) $state['id'] ?>" <?= $selectedStateId == $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>


                            <?php

                            $selectedLgaId =
                                oldValue(
                                    'lga_id',
                                    $corpsMember['lga_id']
                                );

                            ?>


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


                                <option value="">

                                    Select LGA

                                </option>


                                <?php foreach ($currentLgas as $lga): ?>


                                <option value="<?= (int) $lga['id'] ?>" <?= $selectedLgaId == $lga['id']
                                            ? 'selected'
                                            : '' ?>>

                                    <?= htmlspecialchars(
                                            $lga['lga_name']
                                        ) ?>

                                </option>


                                <?php endforeach; ?>


                            </select>

                        </div>



                        <!-- BATCH -->

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

                            <label class="form-label">

                                Batch

                            </label>


                            <?php

                            $selectedBatch =
                                oldValue(
                                    'batch',
                                    $corpsMember['batch']
                                );

                            ?>


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


                                <option value="">

                                    Select Batch

                                </option>


                                <option value="Batch A" <?= $selectedBatch === 'Batch A'
                                        ? 'selected'
                                        : '' ?>>

                                    Batch A

                                </option>


                                <option value="Batch B" <?= $selectedBatch === 'Batch B'
                                        ? 'selected'
                                        : '' ?>>

                                    Batch B

                                </option>


                                <option value="Batch C" <?= $selectedBatch === 'Batch C'
                                        ? 'selected'
                                        : '' ?>>

                                    Batch C

                                </option>


                            </select>

                        </div>



                        <!-- STREAM -->

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

                            <label class="form-label">

                                Stream

                            </label>


                            <?php

                            $selectedStream =
                                oldValue(
                                    'stream',
                                    $corpsMember['stream']
                                );

                            ?>


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


                                <option value="">

                                    Select Stream

                                </option>


                                <option value="Stream I" <?= $selectedStream === 'Stream I'
                                        ? 'selected'
                                        : '' ?>>

                                    Stream I

                                </option>


                                <option value="Stream II" <?= $selectedStream === '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(
                                    oldValue(
                                        'year_of_service',
                                        $corpsMember['year_of_service']
                                    )
                                ) ?>">

                        </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(
                                    oldValue(
                                        'registration_date',
                                        $corpsMember['registration_date']
                                    )
                                ) ?>">

                        </div>



                        <!-- SERVICE STATUS -->

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

                            <label class="form-label">

                                Service Status

                            </label>


                            <?php

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


                            $selectedCorpsStatus =
                                oldValue(
                                    'corps_status',
                                    $corpsMember['status']
                                );

                            ?>


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


                                <?php foreach (
                                    $corpsStatuses as $status
                                ): ?>


                                <option value="<?= htmlspecialchars($status) ?>" <?= $selectedCorpsStatus === $status
                                            ? 'selected'
                                            : '' ?>>

                                    <?= htmlspecialchars($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">


                        <!-- INSTITUTION -->

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

                            <label class="form-label">

                                Institution

                            </label>


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

                        </div>



                        <!-- COURSE -->

                        <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(
                                    oldValue(
                                        'course_of_study',
                                        $corpsMember['course_of_study']
                                    )
                                ) ?>">

                        </div>



                        <!-- QUALIFICATION -->

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

                            <label class="form-label">

                                Qualification

                            </label>


                            <?php

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


                            $selectedQualification =
                                oldValue(
                                    'qualification',
                                    $corpsMember['qualification']
                                );

                            ?>


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


                                <option value="">

                                    Select Qualification

                                </option>


                                <?php foreach (
                                    $qualifications as $qualification
                                ): ?>


                                <option value="<?= htmlspecialchars($qualification) ?>" <?= $selectedQualification === $qualification
                                            ? 'selected'
                                            : '' ?>>

                                    <?= htmlspecialchars($qualification) ?>

                                </option>


                                <?php endforeach; ?>


                            </select>

                        </div>



                        <!-- GRADUATION YEAR -->

                        <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(
                                    oldValue(
                                        'graduation_year',
                                        $corpsMember['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(
                                    oldValue(
                                        'next_of_kin',
                                        $corpsMember['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(
                                    oldValue(
                                        'next_of_kin_phone',
                                        $corpsMember['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">

                        Update the Corps Member's platoon and hostel assignment.

                    </p>

                </div>


                <div class="card-body">

                    <div class="row gy-20">


                        <!-- PLATOON -->

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

                            <label class="form-label">

                                Platoon

                            </label>


                            <?php

                            $selectedPlatoonId =
                                oldValue(
                                    'platoon_id',
                                    $corpsMember['platoon_id']
                                );

                            ?>


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


                                <option value="">

                                    Not Assigned

                                </option>


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


                                <option value="<?= (int) $platoon['id'] ?>" <?= $selectedPlatoonId == $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>


                            <?php

                            $selectedHostelId =
                                oldValue(
                                    'hostel_id',
                                    $corpsMember['hostel_id']
                                );

                            ?>


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


                                <option value="">

                                    Not Assigned

                                </option>


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


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

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

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

                                </option>


                                <?php endforeach; ?>


                            </select>

                        </div>


                    </div>

                </div>

            </div>



            <!-- ============================================================
            LOGIN ACCOUNT MANAGEMENT
            ============================================================= -->

            <div class="card mb-24">

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

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

                        Login Account Management

                    </h6>


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

                        Manage whether this Corps Member can access their account.

                    </p>

                </div>


                <div class="card-body">

                    <div class="row gy-20">


                        <!-- ACCOUNT STATUS -->

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

                            <label class="form-label">

                                Account Status

                            </label>


                            <?php

                            $selectedAccountStatus =
                                oldValue(
                                    'account_status',
                                    $corpsMember['account_status']
                                );

                            ?>


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


                                <option value="active" <?= $selectedAccountStatus === 'active'
                                        ? 'selected'
                                        : '' ?>>

                                    Active

                                </option>


                                <option value="inactive" <?= $selectedAccountStatus === 'inactive'
                                        ? 'selected'
                                        : '' ?>>

                                    Inactive

                                </option>


                                <option value="suspended" <?= $selectedAccountStatus === 'suspended'
                                        ? 'selected'
                                        : '' ?>>

                                    Suspended

                                </option>


                            </select>


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

                                Active users can access their account.
                                Inactive or suspended users should be blocked
                                from logging into the system.

                            </small>

                        </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">


                        <!-- CANCEL -->

                        <a href="view-corps-member.php?id=<?= (int) $corpsMemberId ?>"
                            class="btn btn-outline-danger-600">

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

                            Cancel

                        </a>


                        <!-- UPDATE -->

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

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

                            Update 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';

?>