<?php

$pageTitle = "Register";

require_once "../includes/auth.php";

if (is_logged_in()) {
        redirect("../dashboard/index.php");
    }

    $error = "";

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

        $fname = sanitize($_POST["firstname"]);
        $lname = sanitize($_POST["lastname"]);
        $email = sanitize($_POST["email"]);
        $phone = sanitize($_POST["phonenumber"]);
        $statecode = sanitize($_POST["statecode"]);
        $gender = sanitize($_POST["gender"]);
        $batch = sanitize($_POST["batch"]);
        $pword = sanitize($_POST["password"]);
        $cpword = sanitize($_POST["confirm_password"]);

        if(empty($fname) || empty($lname) || empty($email) || empty($phone) || empty($statecode) || empty($gender) || empty($batch) || empty($pword) || empty($cpword)) {
            $error = "All fields are required.";
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = "Invalid email format.";
        }

        if(strlen($pword) < 6) {
            $error = "Password must be at least 6 characters long.";
        }

        if ($pword !== $cpword) {
            $error = "Passwords do not match.";
        }

        if (empty($error)) {
            $stmt = $db->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$email]);

            if($stmt->fetch()){
                $error = "Email already exists.";
            } 

            $stmt = $db->prepare("SELECT id FROM users WHERE phone = ?");
            $stmt->execute([$phone]);

            if($stmt->fetch()){
                $error = "Phone number already exists.";
            }

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

            $stmt->execute([$statecode]);
            if ($stmt->fetch()) {
                $error = "State code already exists.";
            }
        }

        if (empty($error)) {
            
            try {
                $db->beginTransaction();

                $hashedPassword = password_hash($pword, PASSWORD_DEFAULT);

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

                $userStmt->execute([
                    4,
                    $fname,
                    $lname,
                    $email,
                    $phone,
                    $hashedPassword,
                    ucfirst($gender),
                    'active'
                ]);

                $userId = $db->lastInsertId();

                $memberStmt = $db->prepare("INSERT INTO corps_members (
                    user_id, 
                    firstname,
                    lastname,
                    email,
                    phone,
                    gender,
                    state_code,
                    batch,
                    registration_date,
                    status
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURDATE(), ?)");

                $memberStmt->execute([
                    $userId,
                    $fname,
                    $lname,
                    $email,
                    $phone,
                    ucfirst($gender),
                    strtoupper($statecode),
                    strtoupper($batch),
                    'Registered'
                ]);

                $db->commit();
                set_flash("Account created successfully! You can now log in.", "success");

                redirect("../auth/login.php");
                    
            } catch (Exception $e) {
                $db->rollBack();
                $error = $e->getMessage();
            }
        }
    }

    require_once "../includes/auth-header.php";
?>

<div class="overlay bg-black bg-opacity-50 w-100 h-100 position-fixed z-9 visibility-hidden opacity-0 duration-300">
</div>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="d-lg-flex bg-white">
    <div class="w-50 d-lg-flex d-none overflow-hidden">
        <img src="../assets/images/thumbs/nysc.jpg" alt="Login Image" class="w-100 h-100 object-fit-cover">
    </div>
    <div class="lg-w-50 px-24 py-32 d-flex justify-content-center align-items-center">
        <div class="max-w-540-px mx-auto">
            <div class="text-center mb-40">
                <img src="../assets/images/thumbs/nysc-logo.webp" width="90" class="mb-3">
                <h5 class="fw-bold text-success">
                    Centralized NYSC
                </h5>
                <p class="text-secondary-light">
                    Management Information System
                </p>
            </div>
            <div class="mt-32 mb-32">
                <h1 class="h6 fw-bold text-primary-light mb-8">
                    Create Corps Member Account 🚀
                </h1>
                <p class="text-sm text-secondary-light mb-0">
                    Complete the registration form to access the CNMIS portal
                </p>
            </div>
            <?php if ($flash = get_flash()) : ?>
            <div class="alert alert-success">
                <?= htmlspecialchars($flash['message']) ?>
            </div>
            <?php endif; ?>
            <?php if ($error): ?>
            <div class="alert alert-danger">
                <?= htmlspecialchars($error) ?>
            </div>
            <?php endif; ?>
            <form action="register.php" method="POST" class="mt-24">
                <div class="row gy-3">
                    <div class="col-lg-12">
                        <div class="shadow-1 radius-12 bg-base h-100 overflow-hidden">
                            <div class="card-body p-20">
                                <div class="row gy-3">
                                    <div class="col-xxl-6 col-xl-4 col-sm-6">
                                        <div class="">
                                            <label for="firstname"
                                                class="text-sm fw-semibold text-primary-light d-inline-block mb-8">First
                                                Name
                                                <span class="text-danger-600">*</span> </label>
                                            <input type="text" name="firstname" class="form-control" id="firstname"
                                                placeholder="Enter your First Name">
                                        </div>
                                    </div>
                                    <div class="col-xxl-6 col-xl-4 col-sm-6">
                                        <div class="">
                                            <label for="lastname"
                                                class="text-sm fw-semibold text-primary-light d-inline-block mb-8">Last
                                                Name
                                                <span class="text-danger-600">*</span> </label>
                                            <input type="text" name="lastname" class="form-control" id="lastname"
                                                placeholder="Enter your Last Name">
                                        </div>
                                    </div>
                                    <div class="col-xxl-6 col-xl-4 col-sm-6">
                                        <div class="">
                                            <label for="email"
                                                class="text-sm fw-semibold text-primary-light d-inline-block mb-8">Email
                                                <span class="text-danger-600">*</span> </label>
                                            <input type="text" name="email" class="form-control" id="email"
                                                placeholder="Your Email">
                                        </div>
                                    </div>
                                    <div class=" col-xxl-6 col-xl-4 col-sm-6">
                                        <div class="">
                                            <label for="gender"
                                                class="text-sm fw-semibold text-primary-light d-inline-block mb-8">Gender</label>
                                            <select id="gender" name="gender" class="form-control form-select">
                                                <option value="male" selected>Male</option>
                                                <option value="female">Female</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class=" col-xxl-6 col-xl-4 col-sm-6">
                                        <div class="">
                                            <label for="batch"
                                                class="text-sm fw-semibold text-primary-light d-inline-block mb-8">Batch</label>
                                            <select id="batch" name="batch" class="form-control form-select">
                                                <option value="male" selected>Batch A</option>
                                                <option value="female">Batch B</option>
                                                <option value="female">Batch C</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-xxl-6 col-xl-4 col-sm-6">
                                        <div class="">
                                            <label for="statecode"
                                                class="text-sm fw-semibold text-primary-light d-inline-block mb-8">State
                                                Code
                                                <span class="text-danger-600">*</span> </label>
                                            <input type="text" name="statecode" class="form-control" id="statecode"
                                                placeholder="Enter State Code">
                                        </div>
                                    </div>
                                    <div class="col-xxl-6 col-xl-4 col-sm-6">
                                        <div class="">
                                            <label for="phonenumber"
                                                class="text-sm fw-semibold text-primary-light d-inline-block mb-8">Phone
                                                Number
                                                <span class="text-danger-600">*</span> </label>
                                            <input type="text" name="phonenumber" class="form-control" id="phonenumber"
                                                placeholder="Enter Phone Number">
                                        </div>
                                    </div>
                                    <div class="col-xxl-6 col-xl-4 col-sm-6">
                                        <div class="">
                                            <label for="your-password"
                                                class="text-sm fw-semibold text-primary-light d-inline-block mb-8">Password
                                                <span class="text-danger-600">*</span>
                                            </label>
                                            <div class="position-relative">
                                                <input type="password" name="password" id="your-password"
                                                    class="form-control" placeholder="Enter your password">
                                                <span
                                                    class="toggle-password ri-eye-line cursor-pointer position-absolute end-0 top-50 translate-middle-y me-16 text-secondary-light"
                                                    data-toggle="#your-password"></span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-xxl-6 col-xl-4 col-sm-6">
                                        <div class="">
                                            <label for="your-password"
                                                class="text-sm fw-semibold text-primary-light d-inline-block mb-8">Confirm
                                                Password
                                                <span class="text-danger-600">*</span>
                                            </label>
                                            <div class="position-relative">
                                                <input type="password" name="confirm_password" id="confirm-password"
                                                    class="form-control" placeholder="Confirm your password">
                                                <span
                                                    class="toggle-password ri-eye-line cursor-pointer position-absolute end-0 top-50 translate-middle-y me-16 text-secondary-light"
                                                    data-toggle="#confirm-password"></span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-12">
                        <div class="">
                            <button type="submit"
                                class="loginBtn btn btn-primary-600 text-sm btn-sm px-12 py-16 w-100 radius-8"> Create
                                Account
                            </button>
                        </div>
                    </div>
                </div>
            </form>
            <div class="mt-32 text-center text-sm">
                Already have an account?
                <a href="../auth/login.php" class="text-primary-600 fw-semibold text-decoration-underline">
                    Login
                </a>
            </div>
        </div>
    </div>
</div>
<?php
 require_once "../includes/auth-footer.php";
?>