<?php

error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

require_once(__DIR__ . "/../../public/connection.php");


/* =========================================================
   VARIABLES
   ========================================================= */

$edit = false;
$slide = null;

$message = '';
$message_type = '';


/* =========================================================
   UPLOAD DIRECTORY
   ========================================================= */

$upload_dir = __DIR__ . "/../../uploads/login_slides/";
$upload_url = "/uploads/login_slides/";


/* =========================================================
   CREATE UPLOAD DIRECTORY
   ========================================================= */

if (!is_dir($upload_dir)) {

    if (!mkdir($upload_dir, 0755, true)) {

        die(
            "<div style='padding:20px;color:red;'>
                <strong>ERROR:</strong> Unable to create upload directory:<br>
                " . htmlspecialchars($upload_dir) . "
            </div>"
        );
    }
}


/* =========================================================
   ADD SLIDE
   ========================================================= */

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

    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');

    $status = isset($_POST['status'])
        ? intval($_POST['status'])
        : 1;

    $sort_order = isset($_POST['sort_order'])
        ? intval($_POST['sort_order'])
        : 0;

    $image = '';


    /* =====================================================
       CHECK IMAGE
       ===================================================== */

    if (
        !isset($_FILES['image']) ||
        $_FILES['image']['error'] !== UPLOAD_ERR_OK
    ) {

        $message = 'Please select a slide image.';
        $message_type = 'danger';

    } else {

        $tmp_file = $_FILES['image']['tmp_name'];
        $original_name = $_FILES['image']['name'];


        /* =================================================
           CHECK THAT IT IS REALLY AN IMAGE
           ================================================= */

        $image_info = @getimagesize($tmp_file);


        if ($image_info === false) {

            $message = 'The uploaded file is not a valid image.';
            $message_type = 'danger';

        } else {

            /*
             * Detect actual image type using getimagesize()
             */

            $image_type = $image_info[2];


            $allowed_types = array(
                IMAGETYPE_JPEG,
                IMAGETYPE_PNG,
                IMAGETYPE_WEBP
            );


            if (!in_array($image_type, $allowed_types, true)) {

                $message =
                    'Invalid image type. Please upload JPG, PNG or WEBP.';

                $message_type = 'danger';

            } else {


                /* =========================================
                   GET SAFE EXTENSION
                   ========================================= */

                switch ($image_type) {

                    case IMAGETYPE_JPEG:
                        $extension = 'jpg';
                        break;

                    case IMAGETYPE_PNG:
                        $extension = 'png';
                        break;

                    case IMAGETYPE_WEBP:
                        $extension = 'webp';
                        break;

                    default:
                        $extension = '';
                }


                if ($extension === '') {

                    $message = 'Unable to determine image extension.';
                    $message_type = 'danger';

                } else {


                    /* =====================================
                       GENERATE UNIQUE FILE NAME
                       ===================================== */

                    try {

                        $random_part = bin2hex(random_bytes(5));

                    } catch (Exception $e) {

                        $random_part = uniqid();
                    }


                    $file_name =
                        'slide_' .
                        time() .
                        '_' .
                        $random_part .
                        '.' .
                        $extension;


                    $target_file =
                        $upload_dir . $file_name;


                    /* =====================================
                       MOVE IMAGE
                       ===================================== */

                    if (
                        move_uploaded_file(
                            $tmp_file,
                            $target_file
                        )
                    ) {

                        /*
                         * Database path
                         */

                        $image =
                            'uploads/login_slides/' .
                            $file_name;


                        /* =================================
                           INSERT DATABASE RECORD
                           ================================= */

                        $stmt = $connection->prepare("
                            INSERT INTO login_slides
                            (
                                image,
                                title,
                                description,
                                status,
                                sort_order
                            )
                            VALUES (?, ?, ?, ?, ?)
                        ");


                        $stmt->bind_param(
                            "sssii",
                            $image,
                            $title,
                            $description,
                            $status,
                            $sort_order
                        );


                        if ($stmt->execute()) {

                            $message =
                                'Login slide added successfully.';

                            $message_type = 'success';

                        } else {

                            /*
                             * If database insertion fails,
                             * remove uploaded image.
                             */

                            if (file_exists($target_file)) {
                                unlink($target_file);
                            }

                            $message =
                                'Database error: ' .
                                $stmt->error;

                            $message_type = 'danger';
                        }


                        $stmt->close();

                    } else {

                        $message =
                            'Image upload failed.<br>' .
                            'Check folder permissions:<br>' .
                            htmlspecialchars($upload_dir);

                        $message_type = 'danger';
                    }
                }
            }
        }
    }
}


/* =========================================================
   DELETE SLIDE
   ========================================================= */

if (isset($_GET['delete'])) {

    $id = intval($_GET['delete']);


    /* Get image */

    $stmt = $connection->prepare("
        SELECT image
        FROM login_slides
        WHERE id = ?
    ");

    $stmt->bind_param("i", $id);

    $stmt->execute();

    $result = $stmt->get_result();

    $delete_slide = $result->fetch_assoc();

    $stmt->close();


    /* Delete physical image */

    if (
        $delete_slide &&
        !empty($delete_slide['image'])
    ) {

        $file_path =
            __DIR__ .
            "/../../" .
            ltrim(
                $delete_slide['image'],
                "/"
            );


        if (file_exists($file_path)) {

            unlink($file_path);
        }
    }


    /* Delete database record */

    $stmt = $connection->prepare("
        DELETE FROM login_slides
        WHERE id = ?
    ");

    $stmt->bind_param("i", $id);

    $stmt->execute();

    $stmt->close();


    $message = 'Login slide deleted successfully.';
    $message_type = 'danger';
}


/* =========================================================
   TOGGLE STATUS
   ========================================================= */

if (isset($_GET['toggle'])) {

    $id = intval($_GET['toggle']);


    $stmt = $connection->prepare("
        UPDATE login_slides
        SET status = IF(status = 1, 0, 1)
        WHERE id = ?
    ");


    $stmt->bind_param("i", $id);

    $stmt->execute();

    $stmt->close();


    $message = 'Slide status updated successfully.';
    $message_type = 'info';
}


/* =========================================================
   EDIT SLIDE
   ========================================================= */

if (isset($_GET['edit'])) {

    $id = intval($_GET['edit']);


    $stmt = $connection->prepare("
        SELECT *
        FROM login_slides
        WHERE id = ?
    ");


    $stmt->bind_param("i", $id);

    $stmt->execute();

    $result = $stmt->get_result();

    $slide = $result->fetch_assoc();

    $stmt->close();


    if ($slide) {

        $edit = true;

    } else {

        $edit = false;
        $slide = null;

        $message = 'Login slide not found.';
        $message_type = 'danger';
    }
}


/* =========================================================
   UPDATE SLIDE
   ========================================================= */

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

    $id = intval($_POST['slide_id'] ?? 0);

    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');

    $status = isset($_POST['status'])
        ? intval($_POST['status'])
        : 1;

    $sort_order = isset($_POST['sort_order'])
        ? intval($_POST['sort_order'])
        : 0;

    $old_image = $_POST['old_image'] ?? '';

    $image = $old_image;


    /* =====================================================
       CHECK IF NEW IMAGE WAS UPLOADED
       ===================================================== */

    if (
        isset($_FILES['image']) &&
        $_FILES['image']['error'] === UPLOAD_ERR_OK
    ) {

        $tmp_file = $_FILES['image']['tmp_name'];


        /* ================================================
           VALIDATE IMAGE
           ================================================ */

        $image_info = @getimagesize($tmp_file);


        if ($image_info === false) {

            $message = 'The uploaded file is not a valid image.';
            $message_type = 'danger';

        } else {

            $image_type = $image_info[2];


            $allowed_types = array(
                IMAGETYPE_JPEG,
                IMAGETYPE_PNG,
                IMAGETYPE_WEBP
            );


            if (!in_array($image_type, $allowed_types, true)) {

                $message =
                    'Invalid image type. Please upload JPG, PNG or WEBP.';

                $message_type = 'danger';

            } else {


                /* =========================================
                   EXTENSION
                   ========================================= */

                switch ($image_type) {

                    case IMAGETYPE_JPEG:
                        $extension = 'jpg';
                        break;

                    case IMAGETYPE_PNG:
                        $extension = 'png';
                        break;

                    case IMAGETYPE_WEBP:
                        $extension = 'webp';
                        break;

                    default:
                        $extension = '';
                }


                if ($extension !== '') {


                    /* =====================================
                       UNIQUE NAME
                       ===================================== */

                    try {

                        $random_part = bin2hex(random_bytes(5));

                    } catch (Exception $e) {

                        $random_part = uniqid();
                    }


                    $file_name =
                        'slide_' .
                        time() .
                        '_' .
                        $random_part .
                        '.' .
                        $extension;


                    $target_file =
                        $upload_dir . $file_name;


                    /* =====================================
                       MOVE NEW IMAGE
                       ===================================== */

                    if (
                        move_uploaded_file(
                            $tmp_file,
                            $target_file
                        )
                    ) {


                        /* =================================
                           DELETE OLD IMAGE
                           ================================= */

                        if (!empty($old_image)) {

                            $old_file =
                                __DIR__ .
                                "/../../" .
                                ltrim(
                                    $old_image,
                                    "/"
                                );


                            if (
                                file_exists($old_file)
                            ) {

                                unlink($old_file);
                            }
                        }


                        /* =================================
                           NEW DATABASE IMAGE PATH
                           ================================= */

                        $image =
                            'uploads/login_slides/' .
                            $file_name;
                    }
                }
            }
        }
    }


    /* =====================================================
       UPDATE DATABASE
       ===================================================== */

    $stmt = $connection->prepare("
        UPDATE login_slides
        SET
            image = ?,
            title = ?,
            description = ?,
            status = ?,
            sort_order = ?
        WHERE id = ?
    ");


    $stmt->bind_param(
        "sssiii",
        $image,
        $title,
        $description,
        $status,
        $sort_order,
        $id
    );


    if ($stmt->execute()) {

        $message =
            'Login slide updated successfully.';

        $message_type = 'success';

    } else {

        $message =
            'Failed to update slide: ' .
            $stmt->error;

        $message_type = 'danger';
    }


    $stmt->close();


    /*
     * Return to normal add mode
     */

    $edit = false;
    $slide = null;
}


/* =========================================================
   FETCH ALL SLIDES
   ========================================================= */

$result = $connection->query("
    SELECT *
    FROM login_slides
    ORDER BY sort_order ASC, id DESC
");

?>

<!-- =======================================================
     PAGE TITLE
     ======================================================= -->

<div class="page-title mb-3">

    <h1>
        <i class="fa-solid fa-images"></i>
        Login Slides
    </h1>

</div>


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

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

    <div class="alert alert-<?= htmlspecialchars($message_type) ?>">

        <?= $message ?>

    </div>

<?php endif; ?>


<!-- =======================================================
     ADD / EDIT CARD
     ======================================================= -->

<div class="card shadow-sm">

    <div class="card-body">

        <h4 class="mb-4">

            <?= $edit
                ? 'Edit Login Slide'
                : 'Add Login Slide'
            ?>

        </h4>


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


            <!-- SLIDE ID -->

            <input
                type="hidden"
                name="slide_id"
                value="<?= $edit
                    ? intval($slide['id'])
                    : ''
                ?>"
            >


            <!-- OLD IMAGE -->

            <input
                type="hidden"
                name="old_image"
                value="<?= $edit
                    ? htmlspecialchars($slide['image'])
                    : ''
                ?>"
            >


            <!-- TITLE -->

            <div class="mb-3">

                <label class="form-label">
                    Slide Title
                </label>

                <input
                    type="text"
                    name="title"
                    class="form-control"
                    placeholder="Example: New Academic Session Begins"
                    value="<?= $edit
                        ? htmlspecialchars($slide['title'])
                        : ''
                    ?>"
                >

            </div>


            <!-- DESCRIPTION -->

            <div class="mb-3">

                <label class="form-label">
                    Slide Description
                </label>

                <textarea
                    name="description"
                    class="form-control"
                    rows="3"
                    placeholder="Short description displayed on the slide"
                ><?= $edit
                    ? htmlspecialchars($slide['description'])
                    : ''
                ?></textarea>

            </div>


            <!-- IMAGE -->

            <div class="mb-3">

                <label class="form-label">
                    Slide Image
                </label>

                <input
                    type="file"
                    name="image"
                    class="form-control"
                    accept=".jpg,.jpeg,.png,.webp"
                    <?= $edit ? '' : 'required' ?>
                >

                <small class="text-muted">
                    JPG, JPEG, PNG or WEBP only.
                </small>

            </div>


            <!-- CURRENT IMAGE -->

            <?php if (
                $edit &&
                !empty($slide['image'])
            ): ?>

                <div class="mb-3">

                    <label class="form-label">
                        Current Image
                    </label>

                    <br>

                    <img
                        src="/<?= htmlspecialchars($slide['image']) ?>"
                        style="
                            width:300px;
                            height:160px;
                            object-fit:cover;
                            border-radius:10px;
                            border:1px solid #ddd;
                        "
                        alt="Current Slide"
                    >

                </div>

            <?php endif; ?>


            <div class="row">


                <!-- STATUS -->

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

                    <label class="form-label">
                        Status
                    </label>

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

                        <option
                            value="1"
                            <?= (
                                $edit &&
                                intval($slide['status']) === 1
                            ) || !$edit
                                ? 'selected'
                                : ''
                            ?>
                        >
                            Active
                        </option>

                        <option
                            value="0"
                            <?= (
                                $edit &&
                                intval($slide['status']) === 0
                            )
                                ? 'selected'
                                : ''
                            ?>
                        >
                            Inactive
                        </option>

                    </select>

                </div>


                <!-- DISPLAY ORDER -->

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

                    <label class="form-label">
                        Display Order
                    </label>

                    <input
                        type="number"
                        name="sort_order"
                        class="form-control"
                        min="0"
                        value="<?= $edit
                            ? intval($slide['sort_order'])
                            : 0
                        ?>"
                    >

                    <small class="text-muted">
                        Lower numbers appear first.
                    </small>

                </div>

            </div>


            <!-- BUTTON -->

            <button
                type="submit"
                name="<?= $edit
                    ? 'update_slide'
                    : 'add_slide'
                ?>"
                class="btn btn-primary"
            >

                <i class="fa-solid fa-save"></i>

                <?= $edit
                    ? 'Update Slide'
                    : 'Add Slide'
                ?>

            </button>


            <?php if ($edit): ?>

                <a
                    href="?page=admin_event"
                    class="btn btn-secondary"
                >
                    Cancel
                </a>

            <?php endif; ?>


        </form>

    </div>

</div>


<hr class="my-4">


<!-- =======================================================
     ALL SLIDES
     ======================================================= -->

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

    <h4 class="mb-0">
        All Login Slides
    </h4>

</div>


<div class="row">

<?php if ($result && $result->num_rows > 0): ?>

    <?php while ($row = $result->fetch_assoc()): ?>

        <div class="col-lg-4 col-md-6 mb-4">

            <div class="card shadow-sm h-100">


                <!-- IMAGE -->

                <?php if (!empty($row['image'])): ?>

                    <img
                        src="/<?= htmlspecialchars($row['image']) ?>"
                        style="
                            width:100%;
                            height:190px;
                            object-fit:cover;
                            border-radius:8px 8px 0 0;
                        "
                        alt="Login Slide"
                    >

                <?php else: ?>

                    <div
                        style="
                            height:190px;
                            display:flex;
                            align-items:center;
                            justify-content:center;
                            background:#f1f1f1;
                            color:#888;
                        "
                    >
                        No Image
                    </div>

                <?php endif; ?>


                <div class="card-body">


                    <!-- TITLE -->

                    <h5 class="card-title">

                        <?= !empty($row['title'])
                            ? htmlspecialchars($row['title'])
                            : 'Untitled Slide'
                        ?>

                    </h5>


                    <!-- DESCRIPTION -->

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

                        <p class="card-text text-muted">

                            <?= nl2br(
                                htmlspecialchars(
                                    $row['description']
                                )
                            ) ?>

                        </p>

                    <?php endif; ?>


                    <!-- STATUS -->

                    <div class="mb-3">

                        <?php if (intval($row['status']) === 1): ?>

                            <span class="badge bg-success">
                                Active
                            </span>

                        <?php else: ?>

                            <span class="badge bg-secondary">
                                Inactive
                            </span>

                        <?php endif; ?>


                        <span class="badge bg-info">
                            Order:
                            <?= intval($row['sort_order']) ?>
                        </span>

                    </div>


                    <!-- ACTIONS -->

                    <div class="d-flex gap-2 flex-wrap">


                        <!-- EDIT -->

                        <a
                            href="?edit=<?= intval($row['id']) ?>"
                            class="btn btn-warning btn-sm"
                        >

                            <i class="fa-solid fa-pen"></i>
                            Edit

                        </a>


                        <!-- TOGGLE -->

                        <a
                            href="?toggle=<?= intval($row['id']) ?>"
                            class="btn btn-info btn-sm"
                            onclick="return confirm('Change this slide status?');"
                        >

                            <?php if (
                                intval($row['status']) === 1
                            ): ?>

                                <i class="fa-solid fa-eye-slash"></i>
                                Disable

                            <?php else: ?>

                                <i class="fa-solid fa-eye"></i>
                                Activate

                            <?php endif; ?>

                        </a>


                        <!-- DELETE -->

                        <a
                            href="?delete=<?= intval($row['id']) ?>"
                            class="btn btn-danger btn-sm"
                            onclick="return confirm('Delete this login slide? The image will also be deleted.');"
                        >

                            <i class="fa-solid fa-trash"></i>
                            Delete

                        </a>


                    </div>

                </div>

            </div>

        </div>

    <?php endwhile; ?>

<?php else: ?>

    <div class="col-12">

        <div class="alert alert-info">

            <i class="fa-solid fa-circle-info"></i>

            No login slides have been added yet.

        </div>

    </div>

<?php endif; ?>

</div>