<?php
session_start();
require_once("public/connection.php");

// Fetch school info
$school_name = " ";
$school_logo = " ";
$school_favicon = " ";

$stmt = $conn->query("SELECT * FROM administratives LIMIT 1");

if ($stmt && $stmt->num_rows > 0) {

    $adminData = $stmt->fetch_assoc();

    $school_name = $adminData['school_name'];
    $school_logo = $adminData['school_logo'];
    $school_favicon = $adminData['school_favicon'];
}


/* =========================================================
   LOGIN SLIDES
   ========================================================= */

$slides = $conn->query("
    SELECT *
    FROM login_slides
    WHERE status = 1
    ORDER BY sort_order ASC, id DESC
");


/* =========================================================
   YOUR EXISTING AUTHENTICATION LOGIC
   DO NOT CHANGE
   ========================================================= */

if (isset($_POST['login_btn'])) {

    $identity = trim($_POST['login_id']);
    $password = $_POST['login_password'];


    /* =========================
       STAFF LOGIN
    ========================= */

    $stmt = $conn->prepare("
        SELECT *
        FROM staff
        WHERE username = ?
    ");

    $stmt->bind_param("s", $identity);
    $stmt->execute();

    $staff = $stmt
        ->get_result()
        ->fetch_assoc();


    if (
        $staff &&
        password_verify(
            $password,
            $staff['password']
        )
    ) {

        $_SESSION['staff_id'] = $staff['id'];
        $_SESSION['role'] = 'staff';

        header("Location: admin/dashboard.php");
        exit;
    }


    /* =========================
       STUDENT LOGIN
    ========================= */

    $stmt = $conn->prepare("
        SELECT *
        FROM students
        WHERE reg_number = ?
    ");

    $stmt->bind_param("s", $identity);
    $stmt->execute();

    $student = $stmt
        ->get_result()
        ->fetch_assoc();


    if (
        $student &&
        password_verify(
            $password,
            $student['gen_password']
        )
    ) {

        if ($student['status'] !== 'active') {

            $_SESSION['login_msg'] = "Account disabled";
            $_SESSION['alert_type'] = "error";

            header("Location: index.php");
            exit;
        }


        if ((int)$student['flagged'] === 1) {

            $_SESSION['login_msg'] =
                "You are disqualified for malpractice";

            $_SESSION['alert_type'] = "error";

            header("Location: index.php");
            exit;
        }


        session_regenerate_id(true);

        $_SESSION['student_id'] = $student['id'];
        $_SESSION['role'] = 'student';

        header("Location: student/dashboard.php");
        exit;
    }


    /* =========================
       APPLICANT LOGIN
       ========================= */

    $stmt = $conn->prepare("
        SELECT a.*, ac.exam_id
        FROM applications a
        JOIN exam_access_codes ac
            ON ac.student_id = a.id
        WHERE a.ref = ?
          AND ac.access_code = ?
          AND ac.student_type = 'applicant'
          AND ac.expires_at > NOW()
        LIMIT 1
    ");

    $stmt->bind_param(
        "ss",
        $identity,
        $password
    );

    $stmt->execute();

    $applicant = $stmt
        ->get_result()
        ->fetch_assoc();


    if ($applicant) {

        if ((int)$applicant['flagged'] === 1) {

            $_SESSION['login_msg'] =
                "You are disqualified for malpractice";

            $_SESSION['alert_type'] = "error";

            header("Location: index.php");
            exit;
        }


        session_regenerate_id(true);


        $_SESSION['applicant'] = [

            'id' =>
                (int)$applicant['id'],

            'ref' =>
                $applicant['ref'],

            'name' =>
                $applicant['fname'] .
                ' ' .
                $applicant['lname'],

            'exam_id' =>
                (int)$applicant['exam_id']
        ];


        $_SESSION['role'] = 'applicant';


        header("Location: student/dashboard.php");
        exit;
    }


    /* =========================
       INVALID LOGIN
    ========================= */

    $_SESSION['login_msg'] =
        "Invalid credentials";

    $_SESSION['alert_type'] =
        "error";

    header("Location: index.php");
    exit;
}

?>

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="utf-8">

<meta
    http-equiv="X-UA-Compatible"
    content="IE=edge"
>

<meta
    name="viewport"
    content="width=device-width, initial-scale=1"
>


<!-- =========================================================
     EXISTING STYLES
     ========================================================= -->

<link
    rel="stylesheet"
    href="assets/css/font-awesome-4.7.0/css/font-awesome.css"
>

<link
    rel="stylesheet"
    type="text/css"
    href="assets/css/login.css"
>

<link
    rel="icon"
    href="../<?php echo htmlspecialchars($school_favicon); ?>"
    type="image/png"
>

<link
    href="assets/SweetAlerts/sweetalert.css"
    rel="stylesheet"
>

<link
    rel="stylesheet"
    type="text/css"
    href="assets/loader/waitMe.css"
>


<title>
    <?php echo htmlspecialchars($school_name); ?>
    - CBT PORTAL
</title>


<style>

/* =========================================================
   GLOBAL
   ========================================================= */

* {
    box-sizing: border-box;
}

html,
body {
    margin: 0;
    padding: 0;
    width: 100%;
    min-height: 100%;
}

body {

    background: #f5f7fb;

    font-family:
        "Segoe UI",
        Arial,
        sans-serif;
}


/* =========================================================
   MAIN WRAPPER
   ========================================================= */

.portal-shell {

    min-height: 100vh;

    width: 100%;
}


/* =========================================================
   LEFT IMAGE PANEL
   ========================================================= */

.brand-panel {

    position: relative;

    min-height: 100vh;

    overflow: hidden;

    background: #111;
}


.brand-slider {

    position: absolute;

    inset: 0;
}


.brand-slide {

    position: absolute;

    inset: 0;

    background-size: cover;

    background-position: center;

    opacity: 0;

    transform: scale(1.04);

    transition:
        opacity 1s ease-in-out,
        transform 6s ease;
}


.brand-slide.active {

    opacity: 1;

    transform: scale(1);
}


/* =========================================================
   IMAGE OVERLAY
   ========================================================= */

.brand-overlay {

    position: absolute;

    inset: 0;

    background:
        linear-gradient(
            180deg,
            rgba(0,0,0,0.15) 0%,
            rgba(0,0,0,0.45) 55%,
            rgba(0,0,0,0.80) 100%
        );

    z-index: 2;
}


/* =========================================================
   LEFT CONTENT
   ========================================================= */

.brand-content {

    position: relative;

    z-index: 3;

    min-height: 100vh;

    display: flex;

    align-items: center;

    justify-content: center;

    padding: 50px;

    text-align: center;
}


.brand-content-inner {

    width: 100%;

    max-width: 520px;

    color: #fff;
}


/* SCHOOL LOGO */

.hero-logo {

    width: 135px;

    height: 135px;

    object-fit: contain;

    background: rgba(255,255,255,0.96);

    padding: 10px;

    border-radius: 50%;

    box-shadow:
        0 15px 45px rgba(0,0,0,0.30);

    margin-bottom: 28px;
}


/* SCHOOL NAME */

.brand-content h1 {

    font-size: 38px;

    line-height: 1.2;

    font-weight: 700;

    margin: 0 0 15px;
}


/* SLIDE TEXT */

.slide-title {

    font-size: 25px;

    font-weight: 700;

    margin: 0 0 12px;

    color: #fff;
}


.brand-content p {

    font-size: 16px;

    line-height: 1.7;

    color: rgba(255,255,255,0.92);

    margin: 0 auto;

    max-width: 450px;
}


/* =========================================================
   SLIDER DOTS
   ========================================================= */

.brand-dots {

    position: absolute;

    z-index: 5;

    bottom: 35px;

    left: 0;

    right: 0;

    display: flex;

    justify-content: center;

    gap: 8px;
}


.brand-dot {

    width: 9px;

    height: 9px;

    border-radius: 50%;

    background: rgba(255,255,255,0.45);

    transition: all .3s ease;
}


.brand-dot.active {

    width: 28px;

    border-radius: 10px;

    background: #fff;
}


/* =========================================================
   RIGHT LOGIN PANEL
   ========================================================= */

.login-panel {

    min-height: 100vh;

    display: flex;

    align-items: center;

    background: #ffffff;

    padding: 50px 30px;
}


.login-container {

    width: 100%;

    max-width: 570px;

    margin: auto;
}


/* =========================================================
   LOGIN CARD
   ========================================================= */

.login-card {

    background: #fff;

    padding: 45px;

    border-radius: 18px;

    box-shadow:
        0 15px 50px rgba(0,0,0,0.08);

    border: 1px solid #edf0f5;
}


/* =========================================================
   MOBILE LOGO
   ========================================================= */

.login-card-logo {

    display: none;

    text-align: center;

    margin-bottom: 20px;
}


.login-card-logo img {

    width: 90px;

    height: 90px;

    object-fit: contain;
}


/* =========================================================
   LOGIN HEADING
   ========================================================= */

.login-head {

    text-align: left;

    font-size: 28px;

    font-weight: 700;

    color: #20242b;

    margin: 0 0 8px;
}


.login-subtitle {

    color: #7a808a;

    font-size: 14px;

    margin-bottom: 30px;
}


/* =========================================================
   FORM LABELS
   ========================================================= */

.login-form .form-label {

    font-size: 13px;

    font-weight: 600;

    color: #363b44;

    margin-bottom: 8px;

    text-transform: uppercase;
}


/* =========================================================
   INPUTS
   ========================================================= */

.login-form .form-control {

    height: 52px;

    border: 1px solid #dfe3e8;

    border-radius: 9px;

    padding: 0 15px;

    font-size: 14px;

    color: #252a31;

    background: #fff;

    box-shadow: none;

    transition: all .25s ease;
}


.login-form .form-control:focus {

    border-color: #198754;

    box-shadow:
        0 0 0 3px rgba(25,135,84,0.10);
}


.login-form .form-control::placeholder {

    color: #a0a5ad;
}


/* =========================================================
   LINKS
   ========================================================= */

.semibold-text {

    font-size: 13px;

    font-weight: 600;
}


.semibold-text a {

    color: #198754;

    text-decoration: none;

    transition: color .2s ease;
}


.semibold-text a:hover {

    color: #146c43;
}


/* =========================================================
   LOGIN BUTTON
   ========================================================= */

.app_btn {

    width: 100%;

    min-height: 52px;

    border: none !important;

    border-radius: 9px !important;

    background:
        linear-gradient(
            135deg,
            #198754,
            #20a464
        ) !important;

    color: #fff !important;

    font-size: 14px;

    font-weight: 700;

    letter-spacing: .3px;

    transition:
        transform .2s ease,
        box-shadow .2s ease;
}


.app_btn:hover {

    transform: translateY(-1px);

    box-shadow:
        0 8px 20px
        rgba(25,135,84,0.25);
}


/* =========================================================
   FOOTER
   ========================================================= */

.login-footer {

    text-align: center;

    margin-top: 22px;

    font-size: 12px;

    color: #888;
}


.login-footer a {

    color: #198754;

    text-decoration: none;

    font-weight: 600;
}


/* =========================================================
   TABLET
   ========================================================= */

@media (max-width: 991px) {

    .brand-panel {

        min-height: 430px;
    }


    .brand-content {

        min-height: 430px;
    }


    .brand-content h1 {

        font-size: 30px;
    }


    .hero-logo {

        width: 105px;

        height: 105px;
    }


    .login-panel {

        min-height: auto;

        padding: 45px 25px;
    }

}


/* =========================================================
   MOBILE
   ========================================================= */

@media (max-width: 575px) {

    .brand-panel {

        min-height: 330px;
    }


    .brand-content {

        min-height: 330px;

        padding: 30px 20px;
    }


    .brand-content h1 {

        font-size: 24px;
    }


    .slide-title {

        font-size: 19px;
    }


    .brand-content p {

        font-size: 13px;
    }


    .hero-logo {

        width: 85px;

        height: 85px;

        margin-bottom: 18px;
    }


    .brand-dots {

        bottom: 18px;
    }


    .login-panel {

        padding: 25px 15px;
    }


    .login-card {

        padding: 28px 20px;

        border-radius: 14px;

        box-shadow: none;

        border: none;
    }


    .login-head {

        font-size: 23px;
    }


    .login-card-logo {

        display: block;
    }

}


/* =========================================================
   VERY SMALL DEVICES
   ========================================================= */

@media (max-width: 380px) {

    .brand-panel {

        min-height: 290px;
    }


    .brand-content {

        min-height: 290px;
    }


    .brand-content h1 {

        font-size: 21px;
    }


    .login-card {

        padding: 25px 16px;
    }

}

</style>

</head>


<body>


<div class="portal-shell">


    <div class="row g-0 min-vh-100">


        <!-- =====================================================
             LEFT SIDE - LOGIN SLIDES
             ===================================================== -->

        <div class="col-lg-5 brand-panel">


            <div class="brand-slider">


                <?php

                /*
                 * Build the active slides.
                 *
                 * Images are stored as:
                 *
                 * uploads/login_slides/filename.jpg
                 *
                 * Since CBT index.php is inside /cbt/,
                 * we use /uploads/... from website root.
                 */

                $sliderData = [];


                if (
                    $slides &&
                    $slides->num_rows > 0
                ) {

                    while (
                        $slide = $slides->fetch_assoc()
                    ) {

                        if (!empty($slide['image'])) {

                            $sliderData[] = [

                                'image' =>
                                    '/' .
                                    ltrim(
                                        $slide['image'],
                                        '/'
                                    ),

                                'title' =>
                                    $slide['title'] ?? '',

                                'description' =>
                                    $slide['description'] ?? ''
                            ];
                        }
                    }
                }


                /*
                 * Fallback if no slides exist.
                 */

                if (empty($sliderData)) {

                    $sliderData[] = [

                        'image' =>
                            'assets/images/login-bg.jpg',

                        'title' =>
                            'Welcome to our CBT Portal',

                        'description' =>
                            'Sign in to access your examination portal.'
                    ];
                }

                ?>


                <?php foreach (
                    $sliderData
                    as $index => $slide
                ): ?>


                    <div
                        class="brand-slide <?php
                            echo $index === 0
                                ? 'active'
                                : '';
                        ?>"
                        style="background-image:url('<?php
                            echo htmlspecialchars(
                                $slide['image'],
                                ENT_QUOTES,
                                'UTF-8'
                            );
                        ?>');"
                    ></div>


                <?php endforeach; ?>


            </div>


            <!-- =================================================
                 DARK OVERLAY
                 ================================================= -->

            <div class="brand-overlay"></div>


            <!-- =================================================
                 SCHOOL / SLIDE CONTENT
                 ================================================= -->

            <div class="brand-content">


                <div class="brand-content-inner">


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

                        <img
                            src="../<?php
                                echo htmlspecialchars(
                                    $school_logo
                                );
                            ?>"
                            alt="<?php
                                echo htmlspecialchars(
                                    $school_name
                                );
                            ?>"
                            class="hero-logo"
                        >

                    <?php endif; ?>


                    <h1>
                        <?php
                            echo htmlspecialchars(
                                $school_name
                            );
                        ?>
                    </h1>


                    <?php foreach (
                        $sliderData
                        as $index => $slide
                    ): ?>

                        <div
                            class="slide-text"
                            data-slide="<?php
                                echo $index;
                            ?>"
                            style="<?php
                                echo $index === 0
                                    ? ''
                                    : 'display:none;';
                            ?>"
                        >

                            <?php if (
                                !empty(
                                    $slide['title']
                                )
                            ): ?>

                                <div class="slide-title">

                                    <?php
                                        echo htmlspecialchars(
                                            $slide['title']
                                        );
                                    ?>

                                </div>

                            <?php endif; ?>


                            <?php if (
                                !empty(
                                    $slide['description']
                                )
                            ): ?>

                                <p>

                                    <?php
                                        echo nl2br(
                                            htmlspecialchars(
                                                $slide['description']
                                            )
                                        );
                                    ?>

                                </p>

                            <?php endif; ?>

                        </div>

                    <?php endforeach; ?>


                </div>

            </div>


            <!-- =================================================
                 SLIDER DOTS
                 ================================================= -->

            <?php if (
                count($sliderData) > 1
            ): ?>

                <div class="brand-dots">


                    <?php foreach (
                        $sliderData
                        as $index => $slide
                    ): ?>

                        <span
                            class="brand-dot <?php
                                echo $index === 0
                                    ? 'active'
                                    : '';
                            ?>"
                            data-slide="<?php
                                echo $index;
                            ?>"
                        ></span>

                    <?php endforeach; ?>


                </div>

            <?php endif; ?>


        </div>


        <!-- =====================================================
             RIGHT SIDE - LOGIN
             ===================================================== -->

        <div class="col-lg-7 login-panel">


            <div class="login-container">


                <div class="login-card">


                    <div class="login-box">


                        <!-- =========================================
                             LOGIN FORM
                             ========================================= -->

                        <form
                            class="login-form app_frm"
                            action=""
                            method="POST"
                            autocomplete="off"
                        >


                            <!-- MOBILE LOGO -->

                            <div class="login-card-logo">

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

                                    <img
                                        src="../<?php
                                            echo htmlspecialchars(
                                                $school_logo
                                            );
                                        ?>"
                                        alt="<?php
                                            echo htmlspecialchars(
                                                $school_name
                                            );
                                        ?>"
                                    >

                                <?php endif; ?>

                            </div>


                            <!-- HEADING -->

                            <h4 class="login-head">

                                Welcome Back

                            </h4>


                            <p class="login-subtitle">

                                Sign in to access your
                                CBT and entrance examination portal.

                            </p>


                            <!-- LOGIN ID -->

                            <div class="mb-3">

                                <label class="form-label">

                                    USERNAME / REG NO / APPLICATION NO

                                </label>


                                <input
                                    class="form-control"
                                    type="text"
                                    name="login_id"
                                    placeholder="Enter your ID"
                                    required
                                    autocomplete="off"
                                >

                            </div>


                            <!-- PASSWORD -->

                            <div class="mb-3">

                                <label class="form-label">

                                    PASSWORD / ACCESS CODE

                                </label>


                                <input
                                    class="form-control"
                                    type="password"
                                    name="login_password"
                                    placeholder="Enter your password or access code"
                                    required
                                    autocomplete="off"
                                >

                            </div>


                            <!-- LINKS -->

                            <div
                                class="mb-3 d-flex justify-content-between"
                            >

                                <p class="semibold-text mb-2">

                                    <a
                                        href="/login.php"
                                        target="_blank"
                                    >

                                        SCHOOL PORTAL

                                    </a>

                                </p>


                                <p class="semibold-text mb-2">

                                    <a
                                        href="javascript:void(0);"
                                        data-toggle="flip"
                                    >

                                        Forgot Password?

                                    </a>

                                </p>

                            </div>


                            <!-- LOGIN BUTTON -->

                            <div
                                class="mb-3 btn-container d-grid"
                            >

                                <button
                                    type="submit"
                                    name="login_btn"
                                    class="btn btn-success btn-block app_btn"
                                >

                                    <i
                                        class="fa fa-sign-in me-2"
                                    ></i>

                                    SIGN IN

                                </button>

                            </div>


                        </form>


                    </div>

                </div>


                <!-- =================================================
                     FOOTER
                     ================================================= -->

                <div class="login-footer">

                    Developed by

                    <a
                        href="https://wa.me/2348165684612"
                        target="_blank"
                    >

                        Syntax Digital Tech Ltd

                    </a>

                    <br>

                    08165684612

                </div>


            </div>

        </div>


    </div>

</div>


<!-- =========================================================
     EXISTING SCRIPTS
     ========================================================= -->

<script
    src="assets/js/jquery-3.7.0.min.js"
></script>

<script
    src="assets/js/bootstrap.min.js"
></script>

<script
    src="assets/js/login.js"
></script>

<script
    src="assets/loader/waitMe.js"
></script>

<script
    src="assets/js/forms.js"
></script>

<script
    src="assets/SweetAlerts/sweetalert.js"
></script>


<!-- =========================================================
     FORGOT PASSWORD FLIP
     ========================================================= -->

<script>

$('.login-content [data-toggle="flip"]').click(function() {

    $('.login-box').toggleClass('flipped');

    return false;

});

</script>


<!-- =========================================================
     SWEET ALERT
     ========================================================= -->

<?php
require_once("public/alert.php");
?>


<!-- =========================================================
     LOGIN SLIDER
     ========================================================= -->

<script>

document.addEventListener(
    "DOMContentLoaded",
    function() {

        const slides =
            document.querySelectorAll(
                ".brand-slide"
            );

        const dots =
            document.querySelectorAll(
                ".brand-dot"
            );

        const texts =
            document.querySelectorAll(
                ".slide-text"
            );


        /*
         * Nothing to slide.
         */

        if (slides.length <= 1) {

            return;

        }


        let current = 0;


        function showSlide(index) {


            /* =========================
               IMAGES
               ========================= */

            slides.forEach(
                function(slide, i) {

                    slide.classList.toggle(
                        "active",
                        i === index
                    );

                }
            );


            /* =========================
               DOTS
               ========================= */

            dots.forEach(
                function(dot, i) {

                    dot.classList.toggle(
                        "active",
                        i === index
                    );

                }
            );


            /* =========================
               TEXT
               ========================= */

            texts.forEach(
                function(text, i) {

                    text.style.display =
                        i === index
                            ? "block"
                            : "none";

                }
            );

        }


        /*
         * Automatic slideshow.
         */

        setInterval(
            function() {

                current =
                    (current + 1) %
                    slides.length;

                showSlide(current);

            },
            4000
        );


        /*
         * Allow user to click dots.
         */

        dots.forEach(
            function(dot, index) {

                dot.addEventListener(
                    "click",
                    function() {

                        current = index;

                        showSlide(current);

                    }
                );

            }
        );

    }
);

</script>


</body>
</html>