<?php
/**
 * Pure Chemical Admin
 * Admin Users Management
 *
 * Existing table:
 * admins
 *
 * Columns:
 * id
 * name
 * email
 * password_hash
 * status
 * created_at
 * updated_at
 */

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/includes/db.php';

if (file_exists(__DIR__ . '/includes/auth.php')) {
    require_once __DIR__ . '/includes/auth.php';
}

if (function_exists('requireAdmin')) {
    requireAdmin();
}


/* =========================================================
   HELPERS
========================================================= */

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars(
            (string)$value,
            ENT_QUOTES,
            'UTF-8'
        );
    }
}


if (!function_exists('csrf_token')) {
    function csrf_token()
    {
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(
                random_bytes(32)
            );
        }

        return $_SESSION['csrf_token'];
    }
}


if (!function_exists('csrf_field')) {
    function csrf_field()
    {
        return '<input type="hidden" name="csrf_token" value="' .
            e(csrf_token()) .
            '">';
    }
}


if (!function_exists('csrf_verify')) {
    function csrf_verify()
    {
        $token = $_POST['csrf_token'] ?? '';

        if (
            empty($_SESSION['csrf_token']) ||
            empty($token) ||
            !hash_equals(
                $_SESSION['csrf_token'],
                $token
            )
        ) {
            throw new Exception(
                'Invalid security token. Please refresh the page and try again.'
            );
        }
    }
}


function redirectWithMessage($type, $message)
{
    $url = strtok(
        $_SERVER['REQUEST_URI'],
        '?'
    );

    header(
        'Location: ' .
        $url .
        '?' .
        http_build_query([
            'msg_type' => $type,
            'msg' => $message
        ])
    );

    exit;
}


/* =========================================================
   CURRENT ADMIN ID
========================================================= */

$currentAdminId = 0;

if (!empty($_SESSION['ADMIN_ID'])) {
    $currentAdminId = (int)$_SESSION['ADMIN_ID'];
} elseif (!empty($_SESSION['admin_id'])) {
    $currentAdminId = (int)$_SESSION['admin_id'];
} elseif (!empty($_SESSION['id'])) {
    $currentAdminId = (int)$_SESSION['id'];
}


/* =========================================================
   POST ACTIONS
========================================================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    try {

        csrf_verify();

        $action = $_POST['action'] ?? '';


        /* =================================================
           SAVE ADMIN
        ================================================= */

        if ($action === 'save') {

            $id = isset($_POST['id'])
                ? (int)$_POST['id']
                : 0;

            $name = trim(
                $_POST['name'] ?? ''
            );

            $email = trim(
                strtolower(
                    $_POST['email'] ?? ''
                )
            );

            $password = $_POST['password'] ?? '';

            $status = isset($_POST['status'])
                ? 1
                : 0;


            /* ---------------------------------------------
               VALIDATION
            --------------------------------------------- */

            if ($name === '') {
                throw new Exception(
                    'Admin name is required.'
                );
            }

            if (mb_strlen($name) > 100) {
                throw new Exception(
                    'Admin name cannot exceed 100 characters.'
                );
            }


            if ($email === '') {
                throw new Exception(
                    'Email address is required.'
                );
            }


            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                throw new Exception(
                    'Please enter a valid email address.'
                );
            }


            if (mb_strlen($email) > 150) {
                throw new Exception(
                    'Email address cannot exceed 150 characters.'
                );
            }


            /* ---------------------------------------------
               DUPLICATE EMAIL
            --------------------------------------------- */

            $duplicateStmt = $pdo->prepare("
                SELECT id
                FROM admins
                WHERE LOWER(email) = LOWER(:email)
                AND id != :id
                LIMIT 1
            ");

            $duplicateStmt->execute([
                ':email' => $email,
                ':id' => $id
            ]);

            if ($duplicateStmt->fetch()) {
                throw new Exception(
                    'This email address is already registered.'
                );
            }


            /* =================================================
               UPDATE EXISTING ADMIN
            ================================================= */

            if ($id > 0) {

                $adminStmt = $pdo->prepare("
                    SELECT
                        id,
                        name,
                        email,
                        password_hash,
                        status
                    FROM admins
                    WHERE id = :id
                    LIMIT 1
                ");

                $adminStmt->execute([
                    ':id' => $id
                ]);

                $existingAdmin =
                    $adminStmt->fetch();


                if (!$existingAdmin) {
                    throw new Exception(
                        'Admin account not found.'
                    );
                }


                /*
                 * Prevent currently logged-in admin
                 * from disabling their own account.
                 */

                if (
                    $id === $currentAdminId &&
                    $status === 0
                ) {
                    throw new Exception(
                        'You cannot deactivate your own admin account.'
                    );
                }


                /* -----------------------------------------
                   PASSWORD INCLUDED
                ----------------------------------------- */

                if ($password !== '') {

                    if (strlen($password) < 8) {
                        throw new Exception(
                            'Password must be at least 8 characters long.'
                        );
                    }

                    if (strlen($password) > 72) {
                        throw new Exception(
                            'Password cannot exceed 72 characters.'
                        );
                    }


                    $passwordHash = password_hash(
                        $password,
                        PASSWORD_DEFAULT
                    );


                    $updateStmt = $pdo->prepare("
                        UPDATE admins
                        SET
                            name = :name,
                            email = :email,
                            password_hash = :password_hash,
                            status = :status
                        WHERE id = :id
                    ");

                    $updateStmt->execute([
                        ':name' => $name,
                        ':email' => $email,
                        ':password_hash' => $passwordHash,
                        ':status' => $status,
                        ':id' => $id
                    ]);

                } else {

                    /* -------------------------------------
                       UPDATE WITHOUT PASSWORD
                    ------------------------------------- */

                    $updateStmt = $pdo->prepare("
                        UPDATE admins
                        SET
                            name = :name,
                            email = :email,
                            status = :status
                        WHERE id = :id
                    ");

                    $updateStmt->execute([
                        ':name' => $name,
                        ':email' => $email,
                        ':status' => $status,
                        ':id' => $id
                    ]);
                }


                /*
                 * If the logged-in admin changed their own
                 * name/email, keep session display updated.
                 */

                if ($id === $currentAdminId) {

                    $_SESSION['ADMIN_NAME'] = $name;
                    $_SESSION['ADMIN_EMAIL'] = $email;

                }


                redirectWithMessage(
                    'success',
                    'Admin account updated successfully.'
                );
            }


            /* =================================================
               CREATE NEW ADMIN
            ================================================= */

            if ($password === '') {
                throw new Exception(
                    'Password is required when creating a new admin.'
                );
            }


            if (strlen($password) < 8) {
                throw new Exception(
                    'Password must be at least 8 characters long.'
                );
            }


            if (strlen($password) > 72) {
                throw new Exception(
                    'Password cannot exceed 72 characters.'
                );
            }


            $passwordHash = password_hash(
                $password,
                PASSWORD_DEFAULT
            );


            $insertStmt = $pdo->prepare("
                INSERT INTO admins
                (
                    name,
                    email,
                    password_hash,
                    status
                )
                VALUES
                (
                    :name,
                    :email,
                    :password_hash,
                    :status
                )
            ");

            $insertStmt->execute([
                ':name' => $name,
                ':email' => $email,
                ':password_hash' => $passwordHash,
                ':status' => $status
            ]);


            redirectWithMessage(
                'success',
                'New admin account created successfully.'
            );
        }


        /* =================================================
           DELETE ADMIN
        ================================================= */

        if ($action === 'delete') {

            $id = (int)(
                $_POST['id'] ?? 0
            );


            if ($id <= 0) {
                throw new Exception(
                    'Invalid admin ID.'
                );
            }


            /*
             * Never allow current logged-in admin
             * to delete themselves.
             */

            if ($id === $currentAdminId) {
                throw new Exception(
                    'You cannot delete your own admin account.'
                );
            }


            /* ---------------------------------------------
               Check admin exists
            --------------------------------------------- */

            $checkStmt = $pdo->prepare("
                SELECT id
                FROM admins
                WHERE id = :id
                LIMIT 1
            ");

            $checkStmt->execute([
                ':id' => $id
            ]);


            if (!$checkStmt->fetch()) {
                throw new Exception(
                    'Admin account not found.'
                );
            }


            /* ---------------------------------------------
               Delete
            --------------------------------------------- */

            $deleteStmt = $pdo->prepare("
                DELETE FROM admins
                WHERE id = :id
                LIMIT 1
            ");

            $deleteStmt->execute([
                ':id' => $id
            ]);


            redirectWithMessage(
                'success',
                'Admin account deleted successfully.'
            );
        }


        /* =================================================
           TOGGLE STATUS
        ================================================= */

        if ($action === 'toggle_status') {

            $id = (int)(
                $_POST['id'] ?? 0
            );


            if ($id <= 0) {
                throw new Exception(
                    'Invalid admin ID.'
                );
            }


            /*
             * Current logged-in admin cannot
             * disable their own account.
             */

            if ($id === $currentAdminId) {
                throw new Exception(
                    'You cannot deactivate your own admin account.'
                );
            }


            $toggleStmt = $pdo->prepare("
                UPDATE admins
                SET status =
                    CASE
                        WHEN status = 1 THEN 0
                        ELSE 1
                    END
                WHERE id = :id
                LIMIT 1
            ");

            $toggleStmt->execute([
                ':id' => $id
            ]);


            redirectWithMessage(
                'success',
                'Admin status updated successfully.'
            );
        }


        throw new Exception(
            'Invalid request action.'
        );

    } catch (Throwable $e) {

        redirectWithMessage(
            'error',
            $e->getMessage()
        );
    }
}


/* =========================================================
   MESSAGES
========================================================= */

$message = $_GET['msg'] ?? '';
$messageType = $_GET['msg_type'] ?? '';


/* =========================================================
   FILTERS
========================================================= */

$search = trim(
    $_GET['search'] ?? ''
);

$statusFilter = $_GET['status'] ?? '';


/* =========================================================
   DASHBOARD COUNTS
========================================================= */

$totalAdmins = (int)$pdo
    ->query("
        SELECT COUNT(*)
        FROM admins
    ")
    ->fetchColumn();


$activeAdmins = (int)$pdo
    ->query("
        SELECT COUNT(*)
        FROM admins
        WHERE status = 1
    ")
    ->fetchColumn();


$inactiveAdmins = (int)$pdo
    ->query("
        SELECT COUNT(*)
        FROM admins
        WHERE status = 0
    ")
    ->fetchColumn();


$recentAdmins = (int)$pdo
    ->query("
        SELECT COUNT(*)
        FROM admins
        WHERE created_at >= DATE_SUB(
            NOW(),
            INTERVAL 30 DAY
        )
    ")
    ->fetchColumn();


/* =========================================================
   ADMIN LIST
========================================================= */

$sql = "
    SELECT
        id,
        name,
        email,
        status,
        created_at,
        updated_at
    FROM admins
    WHERE 1 = 1
";

$params = [];


if ($search !== '') {

    $sql .= "
        AND (
            name LIKE :search
            OR email LIKE :search
        )
    ";

    $params[':search'] =
        '%' . $search . '%';
}


if (
    $statusFilter !== '' &&
    in_array(
        $statusFilter,
        ['0', '1'],
        true
    )
) {

    $sql .= "
        AND status = :status
    ";

    $params[':status'] =
        (int)$statusFilter;
}


$sql .= "
    ORDER BY
        status DESC,
        id DESC
";


$listStmt = $pdo->prepare($sql);

$listStmt->execute($params);

$admins = $listStmt->fetchAll();


/* =========================================================
   EDIT ADMIN
========================================================= */

$editId = isset($_GET['edit'])
    ? (int)$_GET['edit']
    : 0;

$editAdmin = null;


if ($editId > 0) {

    $editStmt = $pdo->prepare("
        SELECT
            id,
            name,
            email,
            status
        FROM admins
        WHERE id = :id
        LIMIT 1
    ");

    $editStmt->execute([
        ':id' => $editId
    ]);

    $editAdmin =
        $editStmt->fetch();


    if (!$editAdmin) {
        $editId = 0;
    }
}

?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>
        Admin Users | Pure Chemical
    </title>

    <meta
        name="description"
        content="Manage Pure Chemical administrator accounts"
    >

    <link
        rel="preconnect"
        href="https://fonts.googleapis.com"
    >

    <link
        rel="preconnect"
        href="https://fonts.gstatic.com"
        crossorigin
    >

    <link
        href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap"
        rel="stylesheet"
    >

    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
    >


    <style>

        :root {
            --primary: #0f766e;
            --primary-dark: #115e59;
            --primary-soft: #ecfdf5;

            --dark: #0f172a;
            --muted: #64748b;

            --border: #e2e8f0;

            --bg: #f8fafc;

            --white: #ffffff;

            --success: #15803d;
            --success-bg: #f0fdf4;

            --danger: #dc2626;
            --danger-bg: #fef2f2;

            --warning: #d97706;
            --warning-bg: #fffbeb;

            --shadow-sm:
                0 1px 2px rgba(15, 23, 42, .04);

            --shadow-md:
                0 10px 30px rgba(15, 23, 42, .07);

            --shadow-lg:
                0 20px 55px rgba(15, 23, 42, .14);

            --radius: 18px;
        }


        * {
            box-sizing: border-box;
        }


        html {
            scroll-behavior: smooth;
        }


        body {
            margin: 0;

            background:
                radial-gradient(
                    circle at top right,
                    rgba(20, 184, 166, .07),
                    transparent 30%
                ),
                var(--bg);

            color: var(--dark);

            font-family:
                'Inter',
                sans-serif;
        }


        button,
        input,
        select {
            font: inherit;
        }


        a {
            color: inherit;
            text-decoration: none;
        }


        /* =================================================
           PAGE WRAPPER
        ================================================= */

        .page-wrapper {
            min-height: 100vh;

            margin-left: 280px;
        }


        .page-content {
            width: 100%;
            max-width: 1700px;

            margin: 0 auto;

            padding: 28px;
        }


        /* =================================================
           TOPBAR
        ================================================= */

        .topbar {
            position: sticky;

            top: 0;

            z-index: 50;

            min-height: 76px;

            padding:
                14px
                28px;

            display: flex;

            align-items: center;

            justify-content: space-between;

            gap: 20px;

            background:
                rgba(255, 255, 255, .9);

            border-bottom:
                1px solid
                rgba(226, 232, 240, .8);

            backdrop-filter:
                blur(18px);

            -webkit-backdrop-filter:
                blur(18px);
        }


        .topbar-left {
            display: flex;

            align-items: center;

            gap: 13px;
        }


        .topbar-icon {
            width: 44px;
            height: 44px;

            flex: 0 0 44px;

            border-radius: 14px;

            display: flex;

            align-items: center;
            justify-content: center;

            color: #fff;

            background:
                linear-gradient(
                    135deg,
                    var(--primary),
                    #14b8a6
                );

            box-shadow:
                0 8px 20px
                rgba(15, 118, 110, .22);
        }


        .topbar-title {
            margin: 0;

            font-size: 18px;

            font-weight: 800;

            letter-spacing: -.02em;
        }


        .topbar-subtitle {
            margin: 3px 0 0;

            color: var(--muted);

            font-size: 12px;

            font-weight: 500;
        }


        .admin-chip {
            display: flex;

            align-items: center;

            gap: 10px;

            padding:
                7px
                12px
                7px
                8px;

            background: #fff;

            border:
                1px solid
                var(--border);

            border-radius: 14px;
        }


        .admin-avatar {
            width: 34px;
            height: 34px;

            display: flex;

            align-items: center;
            justify-content: center;

            border-radius: 10px;

            background:
                var(--primary-soft);

            color:
                var(--primary);

            font-size: 13px;

            font-weight: 800;
        }


        .admin-name {
            font-size: 12px;

            font-weight: 700;
        }


        /* =================================================
           HEADER
        ================================================= */

        .page-header {
            display: flex;

            align-items: flex-end;

            justify-content: space-between;

            gap: 20px;

            margin-bottom: 24px;
        }


        .eyebrow {
            display: inline-flex;

            align-items: center;

            gap: 7px;

            margin-bottom: 8px;

            color: var(--primary);

            font-size: 11px;

            font-weight: 800;

            letter-spacing: .12em;

            text-transform: uppercase;
        }


        .page-title {
            margin: 0;

            font-size:
                clamp(26px, 3vw, 35px);

            line-height: 1.1;

            font-weight: 800;

            letter-spacing: -.045em;
        }


        .page-description {
            max-width: 700px;

            margin: 9px 0 0;

            color: var(--muted);

            font-size: 14px;

            line-height: 1.65;
        }


        /* =================================================
           BUTTONS
        ================================================= */

        .btn {
            min-height: 44px;

            padding:
                0 16px;

            border: 0;

            border-radius: 13px;

            display: inline-flex;

            align-items: center;
            justify-content: center;

            gap: 8px;

            cursor: pointer;

            font-size: 13px;

            font-weight: 700;

            transition:
                transform .2s ease,
                box-shadow .2s ease,
                background .2s ease;
        }


        .btn:hover {
            transform:
                translateY(-1px);
        }


        .btn-primary {
            color: #fff;

            background:
                linear-gradient(
                    135deg,
                    var(--primary),
                    #0d9488
                );

            box-shadow:
                0 8px 20px
                rgba(15, 118, 110, .2);
        }


        .btn-secondary {
            color: var(--dark);

            background: #fff;

            border:
                1px solid
                var(--border);
        }


        .btn-danger {
            color: #fff;

            background:
                var(--danger);
        }


        /* =================================================
           CARDS
        ================================================= */

        .stats-grid {
            display: grid;

            grid-template-columns:
                repeat(4, minmax(0, 1fr));

            gap: 16px;

            margin-bottom: 22px;
        }


        .stat-card {
            position: relative;

            overflow: hidden;

            padding: 20px;

            background: #fff;

            border:
                1px solid
                var(--border);

            border-radius: var(--radius);

            box-shadow:
                var(--shadow-sm);

            transition:
                transform .2s ease,
                box-shadow .2s ease;
        }


        .stat-card:hover {
            transform:
                translateY(-2px);

            box-shadow:
                var(--shadow-md);
        }


        .stat-card::after {
            content: "";

            position: absolute;

            width: 95px;
            height: 95px;

            right: -38px;
            top: -38px;

            border-radius: 50%;

            background:
                rgba(20, 184, 166, .08);
        }


        .stat-icon {
            width: 42px;
            height: 42px;

            margin-bottom: 15px;

            display: flex;

            align-items: center;
            justify-content: center;

            border-radius: 13px;

            color:
                var(--primary);

            background:
                var(--primary-soft);
        }


        .stat-number {
            font-size: 27px;

            font-weight: 800;

            letter-spacing: -.04em;
        }


        .stat-label {
            margin-top: 5px;

            color: var(--muted);

            font-size: 12px;

            font-weight: 600;
        }


        /* =================================================
           ALERT
        ================================================= */

        .alert {
            display: flex;

            align-items: center;

            gap: 11px;

            margin-bottom: 20px;

            padding:
                14px
                16px;

            border-radius: 14px;

            font-size: 13px;

            font-weight: 600;
        }


        .alert-success {
            color: #166534;

            background:
                var(--success-bg);

            border:
                1px solid
                #bbf7d0;
        }


        .alert-error {
            color: #991b1b;

            background:
                var(--danger-bg);

            border:
                1px solid
                #fecaca;
        }


        /* =================================================
           PANEL
        ================================================= */

        .panel {
            overflow: hidden;

            background: #fff;

            border:
                1px solid
                var(--border);

            border-radius:
                var(--radius);

            box-shadow:
                var(--shadow-sm);
        }


        /* =================================================
           FILTER
        ================================================= */

        .filter-panel {
            margin-bottom: 20px;

            padding: 18px;
        }


        .filter-form {
            display: grid;

            grid-template-columns:
                minmax(250px, 1.6fr)
                minmax(170px, .8fr)
                auto;

            gap: 12px;

            align-items: end;
        }


        .field {
            display: flex;

            flex-direction: column;

            gap: 7px;
        }


        .field label {
            color: #475569;

            font-size: 11px;

            font-weight: 800;

            letter-spacing: .07em;

            text-transform: uppercase;
        }


        .input,
        .select {
            width: 100%;

            height: 44px;

            padding:
                0
                13px;

            outline: none;

            border:
                1px solid
                var(--border);

            border-radius: 12px;

            background: #fff;

            color: var(--dark);

            transition:
                border-color .2s ease,
                box-shadow .2s ease;
        }


        .input:focus,
        .select:focus {
            border-color:
                rgba(15, 118, 110, .55);

            box-shadow:
                0 0 0 4px
                rgba(15, 118, 110, .08);
        }


        .filter-actions {
            display: flex;

            gap: 8px;
        }


        /* =================================================
           TABLE HEADER
        ================================================= */

        .table-header {
            display: flex;

            align-items: center;

            justify-content: space-between;

            gap: 15px;

            padding:
                18px
                20px;

            border-bottom:
                1px solid
                var(--border);
        }


        .table-title {
            margin: 0;

            font-size: 15px;

            font-weight: 800;
        }


        .table-count {
            margin-top: 4px;

            color: var(--muted);

            font-size: 12px;

            font-weight: 600;
        }


        /* =================================================
           TABLE
        ================================================= */

        .table-wrap {
            overflow-x: auto;
        }


        table {
            width: 100%;

            min-width: 980px;

            border-collapse: collapse;
        }


        th {
            padding:
                13px
                18px;

            color: #64748b;

            background:
                #f8fafc;

            border-bottom:
                1px solid
                var(--border);

            text-align: left;

            font-size: 10px;

            font-weight: 800;

            letter-spacing: .09em;

            text-transform: uppercase;
        }


        td {
            padding:
                16px
                18px;

            border-bottom:
                1px solid
                #eef2f7;

            vertical-align: middle;

            font-size: 13px;
        }


        tbody tr {
            transition:
                background .2s ease;
        }


        tbody tr:hover {
            background:
                #fbfefd;
        }


        tbody tr:last-child td {
            border-bottom: 0;
        }


        /* =================================================
           ADMIN CELL
        ================================================= */

        .admin-cell {
            display: flex;

            align-items: center;

            gap: 12px;
        }


        .admin-table-avatar {
            width: 42px;
            height: 42px;

            flex: 0 0 42px;

            display: flex;

            align-items: center;
            justify-content: center;

            border-radius: 13px;

            color:
                var(--primary);

            background:
                var(--primary-soft);

            font-size: 14px;

            font-weight: 800;
        }


        .admin-table-name {
            color: var(--dark);

            font-size: 13px;

            font-weight: 800;
        }


        .admin-table-email {
            margin-top: 4px;

            color: var(--muted);

            font-size: 11px;
        }


        .email-cell {
            color: #475569;

            font-size: 12px;

            font-weight: 600;
        }


        .date-cell {
            color: #64748b;

            font-size: 11px;

            white-space: nowrap;
        }


        /* =================================================
           STATUS
        ================================================= */

        .status-badge {
            display: inline-flex;

            align-items: center;

            gap: 6px;

            padding:
                7px
                10px;

            border: 0;

            border-radius: 999px;

            cursor: pointer;

            font-size: 11px;

            font-weight: 800;
        }


        .status-badge.active {
            color: #166534;

            background:
                #dcfce7;
        }


        .status-badge.inactive {
            color: #991b1b;

            background:
                #fee2e2;
        }


        .status-dot {
            width: 6px;
            height: 6px;

            border-radius: 50%;

            background:
                currentColor;
        }


        /* =================================================
           ACTIONS
        ================================================= */

        .actions {
            display: flex;

            align-items: center;

            gap: 7px;
        }


        .icon-btn {
            width: 35px;
            height: 35px;

            display: inline-flex;

            align-items: center;
            justify-content: center;

            border:
                1px solid
                var(--border);

            border-radius: 10px;

            background: #fff;

            color: #475569;

            cursor: pointer;

            transition: all .2s ease;
        }


        .icon-btn:hover {
            transform:
                translateY(-1px);

            background:
                #f8fafc;

            border-color:
                #cbd5e1;
        }


        .icon-btn.edit:hover {
            color:
                var(--primary);

            border-color:
                rgba(15, 118, 110, .3);
        }


        .icon-btn.status:hover {
            color:
                var(--warning);

            border-color:
                rgba(217, 119, 6, .3);
        }


        .icon-btn.delete:hover {
            color:
                var(--danger);

            border-color:
                rgba(220, 38, 38, .3);
        }


        /* =================================================
           CURRENT ADMIN
        ================================================= */

        .current-admin-badge {
            display: inline-flex;

            align-items: center;

            gap: 5px;

            margin-top: 5px;

            padding:
                4px
                7px;

            border-radius: 7px;

            color:
                var(--primary);

            background:
                var(--primary-soft);

            font-size: 9px;

            font-weight: 800;

            text-transform: uppercase;

            letter-spacing: .04em;
        }


        /* =================================================
           EMPTY
        ================================================= */

        .empty-state {
            padding:
                70px
                20px;

            text-align: center;
        }


        .empty-icon {
            width: 64px;
            height: 64px;

            margin:
                0
                auto
                16px;

            display: flex;

            align-items: center;
            justify-content: center;

            border-radius: 18px;

            color:
                var(--primary);

            background:
                var(--primary-soft);

            font-size: 24px;
        }


        .empty-title {
            margin: 0;

            font-size: 16px;

            font-weight: 800;
        }


        .empty-text {
            max-width: 450px;

            margin:
                7px
                auto
                0;

            color: var(--muted);

            font-size: 13px;

            line-height: 1.6;
        }


        /* =================================================
           MODAL
        ================================================= */

        .modal {
            position: fixed;

            inset: 0;

            z-index: 200;

            display: none;

            align-items: center;
            justify-content: center;

            padding: 20px;

            background:
                rgba(15, 23, 42, .55);

            backdrop-filter:
                blur(7px);
        }


        .modal.show {
            display: flex;
        }


        .modal-card {
            width:
                min(620px, 100%);

            max-height:
                calc(100vh - 40px);

            overflow-y: auto;

            background:
                #fff;

            border-radius:
                22px;

            box-shadow:
                var(--shadow-lg);

            animation:
                modalIn .2s ease;
        }


        @keyframes modalIn {

            from {
                opacity: 0;

                transform:
                    translateY(10px)
                    scale(.98);
            }

            to {
                opacity: 1;

                transform:
                    translateY(0)
                    scale(1);
            }

        }


        .modal-header {
            display: flex;

            align-items: flex-start;

            justify-content: space-between;

            gap: 20px;

            padding:
                22px
                24px;

            border-bottom:
                1px solid
                var(--border);
        }


        .modal-title {
            margin: 0;

            font-size: 18px;

            font-weight: 800;

            letter-spacing: -.02em;
        }


        .modal-subtitle {
            margin:
                5px
                0
                0;

            color:
                var(--muted);

            font-size: 12px;
        }


        .modal-close {
            width: 36px;
            height: 36px;

            border:
                1px solid
                var(--border);

            border-radius: 10px;

            background: #fff;

            color:
                var(--muted);

            cursor: pointer;
        }


        .modal-body {
            padding: 24px;
        }


        .form-grid {
            display: grid;

            grid-template-columns:
                repeat(2, minmax(0, 1fr));

            gap: 17px;
        }


        .full {
            grid-column:
                1 / -1;
        }


        .helper {
            margin-top: 3px;

            color: #94a3b8;

            font-size: 11px;

            line-height: 1.5;
        }


        .password-note {
            padding:
                12px
                14px;

            border-radius: 12px;

            background:
                #f8fafc;

            border:
                1px solid
                var(--border);

            color:
                var(--muted);

            font-size: 11px;

            line-height: 1.55;
        }


        /* =================================================
           SWITCH
        ================================================= */

        .switch-row {
            display: flex;

            align-items: center;

            justify-content: space-between;

            gap: 20px;

            padding:
                13px
                14px;

            border:
                1px solid
                var(--border);

            border-radius: 13px;

            background:
                #fafafa;
        }


        .switch-info strong {
            display: block;

            font-size: 13px;
        }


        .switch-info span {
            display: block;

            margin-top: 3px;

            color:
                var(--muted);

            font-size: 11px;
        }


        .switch {
            position: relative;

            width: 48px;
            height: 27px;
        }


        .switch input {
            width: 0;
            height: 0;

            opacity: 0;
        }


        .slider {
            position: absolute;

            inset: 0;

            cursor: pointer;

            border-radius: 999px;

            background:
                #cbd5e1;

            transition:
                .2s;
        }


        .slider::before {
            content: "";

            position: absolute;

            width: 21px;
            height: 21px;

            top: 3px;
            left: 3px;

            border-radius: 50%;

            background:
                #fff;

            box-shadow:
                0 2px 5px
                rgba(15, 23, 42, .15);

            transition:
                .2s;
        }


        .switch input:checked + .slider {
            background:
                var(--primary);
        }


        .switch input:checked + .slider::before {
            transform:
                translateX(21px);
        }


        /* =================================================
           MODAL FOOTER
        ================================================= */

        .modal-footer {
            display: flex;

            align-items: center;

            justify-content: flex-end;

            gap: 10px;

            padding:
                18px
                24px;

            border-top:
                1px solid
                var(--border);
        }


        /* =================================================
           DELETE MODAL
        ================================================= */

        .delete-modal-card {
            width:
                min(430px, 100%);
        }


        .delete-icon {
            width: 55px;
            height: 55px;

            margin-bottom:
                15px;

            display: flex;

            align-items: center;
            justify-content: center;

            border-radius: 16px;

            color:
                var(--danger);

            background:
                var(--danger-bg);

            font-size: 20px;
        }


        /* =================================================
           RESPONSIVE
        ================================================= */

        @media (max-width: 1200px) {

            .stats-grid {
                grid-template-columns:
                    repeat(2, minmax(0, 1fr));
            }

            .filter-form {
                grid-template-columns:
                    repeat(2, minmax(0, 1fr));
            }

            .filter-actions {
                grid-column:
                    1 / -1;
            }

        }


        @media (max-width: 1000px) {

            .page-wrapper {
                margin-left: 0;
            }

        }


        @media (max-width: 700px) {

            .page-content {
                padding: 18px;
            }

            .topbar {
                padding:
                    12px
                    18px;
            }

            .admin-chip {
                display: none;
            }

            .page-header {
                align-items: flex-start;

                flex-direction: column;
            }

            .page-header .btn {
                width: 100%;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }

            .filter-form {
                grid-template-columns: 1fr;
            }

            .filter-actions {
                grid-column: auto;
            }

            .filter-actions .btn {
                flex: 1;
            }

            .form-grid {
                grid-template-columns: 1fr;
            }

            .full {
                grid-column: auto;
            }

            .modal-body {
                padding: 18px;
            }

            .modal-header {
                padding: 18px;
            }

            .modal-footer {
                padding:
                    16px
                    18px;
            }

        }

    </style>

</head>


<body>


<?php
/*
|--------------------------------------------------------------------------
| EXISTING ADMIN SIDEBAR
|--------------------------------------------------------------------------
*/
require_once __DIR__ . '/sidebar.php';
?>


<div class="page-wrapper">


    <!-- =================================================
         TOPBAR
    ================================================= -->

    <header class="topbar">

        <div class="topbar-left">

            <div class="topbar-icon">

                <i class="fa-solid fa-user-shield"></i>

            </div>

            <div>

                <h1 class="topbar-title">
                    Admin Users
                </h1>

                <p class="topbar-subtitle">
                    Manage administrator accounts
                </p>

            </div>

        </div>


        <div>

            <div class="admin-chip">

                <div class="admin-avatar">

                    <i class="fa-solid fa-user"></i>

                </div>

                <div class="admin-name">

                    <?= e(
                        $_SESSION['ADMIN_NAME']
                        ?? 'Administrator'
                    ) ?>

                </div>

            </div>

        </div>

    </header>


    <main class="page-content">


        <!-- =================================================
             PAGE HEADER
        ================================================= -->

        <section class="page-header">

            <div>

                <div class="eyebrow">

                    <i class="fa-solid fa-shield-halved"></i>

                    Access Management

                </div>


                <h2 class="page-title">
                    Administrator Accounts
                </h2>


                <p class="page-description">

                    Create and manage administrator accounts,
                    update credentials, control account status
                    and maintain secure access to the admin panel.

                </p>

            </div>


            <button
                type="button"
                class="btn btn-primary"
                onclick="openAddModal()"
            >

                <i class="fa-solid fa-user-plus"></i>

                Add Admin

            </button>

        </section>


        <!-- =================================================
             ALERT
        ================================================= -->

        <?php if ($message !== ''): ?>

            <div
                class="alert <?= $messageType === 'error'
                    ? 'alert-error'
                    : 'alert-success' ?>"
            >

                <i
                    class="fa-solid <?= $messageType === 'error'
                        ? 'fa-circle-exclamation'
                        : 'fa-circle-check' ?>"
                ></i>

                <span>
                    <?= e($message) ?>
                </span>

            </div>

        <?php endif; ?>


        <!-- =================================================
             STATISTICS
        ================================================= -->

        <section class="stats-grid">


            <div class="stat-card">

                <div class="stat-icon">

                    <i class="fa-solid fa-users"></i>

                </div>

                <div class="stat-number">

                    <?= number_format(
                        $totalAdmins
                    ) ?>

                </div>

                <div class="stat-label">
                    Total Admins
                </div>

            </div>


            <div class="stat-card">

                <div class="stat-icon">

                    <i class="fa-solid fa-user-check"></i>

                </div>

                <div class="stat-number">

                    <?= number_format(
                        $activeAdmins
                    ) ?>

                </div>

                <div class="stat-label">
                    Active Admins
                </div>

            </div>


            <div class="stat-card">

                <div class="stat-icon">

                    <i class="fa-solid fa-user-lock"></i>

                </div>

                <div class="stat-number">

                    <?= number_format(
                        $inactiveAdmins
                    ) ?>

                </div>

                <div class="stat-label">
                    Inactive Admins
                </div>

            </div>


            <div class="stat-card">

                <div class="stat-icon">

                    <i class="fa-solid fa-user-clock"></i>

                </div>

                <div class="stat-number">

                    <?= number_format(
                        $recentAdmins
                    ) ?>

                </div>

                <div class="stat-label">
                    Added Last 30 Days
                </div>

            </div>


        </section>


        <!-- =================================================
             FILTER
        ================================================= -->

        <section class="panel filter-panel">

            <form
                method="GET"
                class="filter-form"
            >


                <div class="field">

                    <label for="search">
                        Search
                    </label>

                    <input
                        type="text"
                        id="search"
                        name="search"
                        class="input"
                        placeholder="Search by name or email..."
                        value="<?= e($search) ?>"
                    >

                </div>


                <div class="field">

                    <label for="status">
                        Status
                    </label>

                    <select
                        id="status"
                        name="status"
                        class="select"
                    >

                        <option value="">
                            All Status
                        </option>

                        <option
                            value="1"
                            <?= $statusFilter === '1'
                                ? 'selected'
                                : '' ?>
                        >
                            Active
                        </option>

                        <option
                            value="0"
                            <?= $statusFilter === '0'
                                ? 'selected'
                                : '' ?>
                        >
                            Inactive
                        </option>

                    </select>

                </div>


                <div class="filter-actions">

                    <button
                        type="submit"
                        class="btn btn-primary"
                    >

                        <i class="fa-solid fa-filter"></i>

                        Apply

                    </button>


                    <a
                        href="<?= e(
                            strtok(
                                $_SERVER['REQUEST_URI'],
                                '?'
                            )
                        ) ?>"
                        class="btn btn-secondary"
                    >

                        <i class="fa-solid fa-rotate-left"></i>

                        Reset

                    </a>

                </div>


            </form>

        </section>


        <!-- =================================================
             ADMIN TABLE
        ================================================= -->

        <section class="panel">


            <div class="table-header">

                <div>

                    <h3 class="table-title">
                        Administrator List
                    </h3>

                    <div class="table-count">

                        <?= number_format(
                            count($admins)
                        ) ?>

                        result<?= count($admins) !== 1
                            ? 's'
                            : '' ?>

                    </div>

                </div>


                <button
                    type="button"
                    class="btn btn-primary"
                    onclick="openAddModal()"
                >

                    <i class="fa-solid fa-plus"></i>

                    New Admin

                </button>

            </div>


            <?php if (!empty($admins)): ?>


                <div class="table-wrap">

                    <table>

                        <thead>

                            <tr>

                                <th>
                                    Administrator
                                </th>

                                <th>
                                    Email
                                </th>

                                <th>
                                    Status
                                </th>

                                <th>
                                    Created
                                </th>

                                <th>
                                    Actions
                                </th>

                            </tr>

                        </thead>


                        <tbody>


                        <?php foreach ($admins as $admin): ?>


                            <?php

                            $initials = '';

                            $nameParts = preg_split(
                                '/\s+/',
                                trim(
                                    $admin['name']
                                )
                            );

                            if (!empty($nameParts[0])) {
                                $initials .=
                                    mb_substr(
                                        $nameParts[0],
                                        0,
                                        1
                                    );
                            }

                            if (
                                count($nameParts) > 1
                            ) {
                                $initials .=
                                    mb_substr(
                                        end($nameParts),
                                        0,
                                        1
                                    );
                            }

                            $initials =
                                strtoupper(
                                    $initials
                                );

                            ?>


                            <tr>


                                <!-- ADMIN -->

                                <td>

                                    <div class="admin-cell">


                                        <div class="admin-table-avatar">

                                            <?= e(
                                                $initials
                                            ) ?>

                                        </div>


                                        <div>

                                            <div
                                                class="admin-table-name"
                                            >

                                                <?= e(
                                                    $admin['name']
                                                ) ?>

                                            </div>


                                            <?php if (
                                                (int)$admin['id']
                                                ===
                                                $currentAdminId
                                            ): ?>

                                                <div
                                                    class="current-admin-badge"
                                                >

                                                    <i
                                                        class="fa-solid fa-user-check"
                                                    ></i>

                                                    You

                                                </div>

                                            <?php endif; ?>


                                        </div>

                                    </div>

                                </td>


                                <!-- EMAIL -->

                                <td>

                                    <div
                                        class="email-cell"
                                    >

                                        <?= e(
                                            $admin['email']
                                        ) ?>

                                    </div>

                                </td>


                                <!-- STATUS -->

                                <td>


                                    <form
                                        method="POST"
                                        style="display:inline;"
                                    >

                                        <?= csrf_field() ?>


                                        <input
                                            type="hidden"
                                            name="action"
                                            value="toggle_status"
                                        >


                                        <input
                                            type="hidden"
                                            name="id"
                                            value="<?= (int)$admin['id'] ?>"
                                        >


                                        <button
                                            type="submit"
                                            class="status-badge <?= (int)$admin['status'] === 1
                                                ? 'active'
                                                : 'inactive' ?>"
                                            <?= (int)$admin['id'] === $currentAdminId
                                                ? 'disabled'
                                                : '' ?>
                                            title="<?= (int)$admin['id'] === $currentAdminId
                                                ? 'You cannot deactivate yourself'
                                                : 'Change status' ?>"
                                        >

                                            <span
                                                class="status-dot"
                                            ></span>


                                            <?= (int)$admin['status'] === 1
                                                ? 'Active'
                                                : 'Inactive' ?>

                                        </button>

                                    </form>


                                </td>


                                <!-- CREATED -->

                                <td>

                                    <div
                                        class="date-cell"
                                    >

                                        <?php
                                        $createdTimestamp =
                                            strtotime(
                                                $admin['created_at']
                                            );
                                        ?>

                                        <?= $createdTimestamp
                                            ? e(
                                                date(
                                                    'd M Y',
                                                    $createdTimestamp
                                                )
                                            )
                                            : '—' ?>

                                        <?php if (
                                            $createdTimestamp
                                        ): ?>

                                            <br>

                                            <span
                                                style="
                                                    opacity:.65;
                                                    font-size:10px;
                                                "
                                            >

                                                <?= e(
                                                    date(
                                                        'h:i A',
                                                        $createdTimestamp
                                                    )
                                                ) ?>

                                            </span>

                                        <?php endif; ?>

                                    </div>

                                </td>


                                <!-- ACTIONS -->

                                <td>

                                    <div class="actions">


                                        <!-- EDIT -->

                                        <a
                                            href="?edit=<?= (int)$admin['id'] ?>"
                                            class="icon-btn edit"
                                            title="Edit admin"
                                        >

                                            <i
                                                class="fa-solid fa-pen"
                                            ></i>

                                        </a>


                                        <!-- STATUS -->

                                        <?php if (
                                            (int)$admin['id']
                                            !==
                                            $currentAdminId
                                        ): ?>

                                            <button
                                                type="button"
                                                class="icon-btn status"
                                                title="Change status"
                                                onclick="toggleStatus(
                                                    <?= (int)$admin['id'] ?>
                                                )"
                                            >

                                                <i
                                                    class="fa-solid fa-power-off"
                                                ></i>

                                            </button>

                                        <?php endif; ?>


                                        <!-- DELETE -->

                                        <?php if (
                                            (int)$admin['id']
                                            !==
                                            $currentAdminId
                                        ): ?>

                                            <button
                                                type="button"
                                                class="icon-btn delete"
                                                title="Delete admin"
                                                onclick="openDeleteModal(
                                                    <?= (int)$admin['id'] ?>,
                                                    <?= htmlspecialchars(
                                                        json_encode(
                                                            $admin['name'],
                                                            JSON_UNESCAPED_UNICODE
                                                        ),
                                                        ENT_QUOTES,
                                                        'UTF-8'
                                                    ) ?>
                                                )"
                                            >

                                                <i
                                                    class="fa-solid fa-trash"
                                                ></i>

                                            </button>

                                        <?php endif; ?>


                                    </div>

                                </td>


                            </tr>


                        <?php endforeach; ?>


                        </tbody>

                    </table>

                </div>


            <?php else: ?>


                <div class="empty-state">


                    <div class="empty-icon">

                        <i
                            class="fa-solid fa-user-shield"
                        ></i>

                    </div>


                    <h3 class="empty-title">
                        No administrators found
                    </h3>


                    <p class="empty-text">

                        No administrator accounts match
                        your current search or filter.

                    </p>


                    <button
                        type="button"
                        class="btn btn-primary"
                        style="margin-top:18px;"
                        onclick="openAddModal()"
                    >

                        <i
                            class="fa-solid fa-user-plus"
                        ></i>

                        Add First Admin

                    </button>


                </div>


            <?php endif; ?>


        </section>


    </main>

</div>


<!-- =====================================================
     ADD / EDIT MODAL
===================================================== -->

<div
    class="modal <?= $editAdmin
        ? 'show'
        : '' ?>"
    id="adminModal"
>


    <div class="modal-card">


        <div class="modal-header">


            <div>

                <h3 class="modal-title">

                    <?= $editAdmin
                        ? 'Edit Administrator'
                        : 'Add Administrator' ?>

                </h3>


                <p class="modal-subtitle">

                    <?= $editAdmin
                        ? 'Update administrator account details.'
                        : 'Create a secure administrator account.' ?>

                </p>

            </div>


            <button
                type="button"
                class="modal-close"
                onclick="closeModal()"
            >

                <i
                    class="fa-solid fa-xmark"
                ></i>

            </button>


        </div>


        <form
            method="POST"
            action=""
            autocomplete="off"
        >


            <?= csrf_field() ?>


            <input
                type="hidden"
                name="action"
                value="save"
            >


            <input
                type="hidden"
                name="id"
                value="<?= $editAdmin
                    ? (int)$editAdmin['id']
                    : 0 ?>"
            >


            <div class="modal-body">


                <div class="form-grid">


                    <!-- NAME -->

                    <div class="field full">

                        <label for="name">
                            Full Name *
                        </label>


                        <input
                            type="text"
                            id="name"
                            name="name"
                            class="input"
                            maxlength="100"
                            required
                            autocomplete="off"
                            placeholder="e.g. Ankit Maurya"
                            value="<?= $editAdmin
                                ? e($editAdmin['name'])
                                : '' ?>"
                        >


                        <div class="helper">

                            Administrator's display name.

                        </div>

                    </div>


                    <!-- EMAIL -->

                    <div class="field full">

                        <label for="email">
                            Email Address *
                        </label>


                        <input
                            type="email"
                            id="email"
                            name="email"
                            class="input"
                            maxlength="150"
                            required
                            autocomplete="off"
                            placeholder="admin@example.com"
                            value="<?= $editAdmin
                                ? e($editAdmin['email'])
                                : '' ?>"
                        >


                        <div class="helper">

                            Email is used for administrator login.

                        </div>

                    </div>


                    <!-- PASSWORD -->

                    <div class="field full">

                        <label for="password">

                            Password
                            <?= $editAdmin
                                ? ''
                                : '*' ?>

                        </label>


                        <input
                            type="password"
                            id="password"
                            name="password"
                            class="input"
                            minlength="8"
                            maxlength="72"
                            autocomplete="new-password"
                            placeholder="<?= $editAdmin
                                ? 'Leave blank to keep current password'
                                : 'Minimum 8 characters' ?>"
                            <?= $editAdmin
                                ? ''
                                : 'required' ?>
                        >


                        <div class="helper">

                            <?= $editAdmin
                                ? 'Leave blank if you do not want to change the current password.'
                                : 'Use a strong password with letters, numbers and symbols.' ?>

                        </div>

                    </div>


                    <!-- PASSWORD SECURITY -->

                    <div class="field full">

                        <div class="password-note">

                            <i
                                class="fa-solid fa-shield-halved"
                                style="
                                    color:var(--primary);
                                    margin-right:5px;
                                "
                            ></i>

                            Passwords are stored using PHP's secure
                            <strong>password_hash()</strong>
                            mechanism. Plain-text passwords are never
                            stored in the database.

                        </div>

                    </div>


                    <!-- STATUS -->

                    <div class="field full">

                        <div class="switch-row">


                            <div class="switch-info">

                                <strong>
                                    Active Account
                                </strong>

                                <span>

                                    Active administrators can
                                    access the admin panel.

                                </span>

                            </div>


                            <label class="switch">

                                <input
                                    type="checkbox"
                                    name="status"
                                    value="1"
                                    <?= (
                                        !$editAdmin ||
                                        (int)$editAdmin['status'] === 1
                                    )
                                        ? 'checked'
                                        : '' ?>
                                >

                                <span class="slider"></span>

                            </label>


                        </div>

                    </div>


                </div>

            </div>


            <div class="modal-footer">


                <button
                    type="button"
                    class="btn btn-secondary"
                    onclick="closeModal()"
                >

                    Cancel

                </button>


                <button
                    type="submit"
                    class="btn btn-primary"
                >

                    <i
                        class="fa-solid fa-check"
                    ></i>


                    <?= $editAdmin
                        ? 'Update Admin'
                        : 'Create Admin' ?>

                </button>


            </div>


        </form>


    </div>

</div>


<!-- =====================================================
     DELETE MODAL
===================================================== -->

<div
    class="modal"
    id="deleteModal"
>


    <div
        class="modal-card delete-modal-card"
    >


        <div class="modal-body">


            <div class="delete-icon">

                <i
                    class="fa-solid fa-user-xmark"
                ></i>

            </div>


            <h3 class="modal-title">
                Delete Administrator?
            </h3>


            <p
                style="
                    color:var(--muted);
                    font-size:13px;
                    line-height:1.6;
                    margin:8px 0 0;
                "
            >

                You are about to permanently delete

                <strong id="deleteAdminName"></strong>.

                This action cannot be undone.

            </p>


        </div>


        <div class="modal-footer">


            <button
                type="button"
                class="btn btn-secondary"
                onclick="closeDeleteModal()"
            >

                Cancel

            </button>


            <form
                method="POST"
                style="display:inline;"
            >

                <?= csrf_field() ?>


                <input
                    type="hidden"
                    name="action"
                    value="delete"
                >


                <input
                    type="hidden"
                    name="id"
                    id="deleteAdminId"
                    value=""
                >


                <button
                    type="submit"
                    class="btn btn-danger"
                >

                    <i
                        class="fa-solid fa-trash"
                    ></i>

                    Delete

                </button>


            </form>


        </div>


    </div>

</div>


<!-- =====================================================
     HIDDEN STATUS FORM
===================================================== -->

<form
    method="POST"
    id="statusForm"
    style="display:none;"
>

    <?= csrf_field() ?>


    <input
        type="hidden"
        name="action"
        value="toggle_status"
    >


    <input
        type="hidden"
        name="id"
        id="statusAdminId"
        value=""
    >

</form>


<script>

    const adminModal =
        document.getElementById('adminModal');

    const deleteModal =
        document.getElementById('deleteModal');


    /* =====================================================
       ADD ADMIN
    ===================================================== */

    function openAddModal()
    {
        const url =
            new URL(
                window.location.href
            );

        url.searchParams.delete(
            'edit'
        );

        url.searchParams.delete(
            'msg'
        );

        url.searchParams.delete(
            'msg_type'
        );

        window.history.replaceState(
            {},
            '',
            url.toString()
        );


        adminModal.classList.add(
            'show'
        );


        const form =
            adminModal.querySelector(
                'form'
            );


        if (form) {

            const id =
                form.querySelector(
                    'input[name="id"]'
                );

            const name =
                document.getElementById(
                    'name'
                );

            const email =
                document.getElementById(
                    'email'
                );

            const password =
                document.getElementById(
                    'password'
                );

            const status =
                form.querySelector(
                    'input[name="status"]'
                );


            if (id) {
                id.value = '0';
            }


            if (name) {
                name.value = '';
            }


            if (email) {
                email.value = '';
            }


            if (password) {
                password.value = '';

                password.required = true;
            }


            if (status) {
                status.checked = true;
            }

        }


        document.body.style.overflow =
            'hidden';


        setTimeout(
            function () {

                if (document.getElementById('name')) {

                    document
                        .getElementById('name')
                        .focus();

                }

            },
            100
        );
    }


    /* =====================================================
       CLOSE ADMIN MODAL
    ===================================================== */

    function closeModal()
    {
        adminModal.classList.remove(
            'show'
        );

        document.body.style.overflow =
            '';


        const url =
            new URL(
                window.location.href
            );

        url.searchParams.delete(
            'edit'
        );


        window.history.replaceState(
            {},
            '',
            url.toString()
        );
    }


    /* =====================================================
       DELETE MODAL
    ===================================================== */

    function openDeleteModal(
        id,
        name
    )
    {
        document.getElementById(
            'deleteAdminId'
        ).value = id;


        document.getElementById(
            'deleteAdminName'
        ).textContent = name;


        deleteModal.classList.add(
            'show'
        );


        document.body.style.overflow =
            'hidden';
    }


    function closeDeleteModal()
    {
        deleteModal.classList.remove(
            'show'
        );

        document.body.style.overflow =
            '';
    }


    /* =====================================================
       TOGGLE STATUS
    ===================================================== */

    function toggleStatus(id)
    {
        if (!id) {
            return;
        }


        document.getElementById(
            'statusAdminId'
        ).value = id;


        document.getElementById(
            'statusForm'
        ).submit();
    }


    /* =====================================================
       CLICK OUTSIDE MODAL
    ===================================================== */

    adminModal.addEventListener(
        'click',
        function(event) {

            if (
                event.target ===
                adminModal
            ) {
                closeModal();
            }

        }
    );


    deleteModal.addEventListener(
        'click',
        function(event) {

            if (
                event.target ===
                deleteModal
            ) {
                closeDeleteModal();
            }

        }
    );


    /* =====================================================
       ESC KEY
    ===================================================== */

    document.addEventListener(
        'keydown',
        function(event) {

            if (
                event.key !==
                'Escape'
            ) {
                return;
            }


            if (
                adminModal.classList.contains(
                    'show'
                )
            ) {
                closeModal();
            }


            if (
                deleteModal.classList.contains(
                    'show'
                )
            ) {
                closeDeleteModal();
            }

        }
    );


    /* =====================================================
       PASSWORD VISUAL SAFETY
    ===================================================== */

    const passwordInput =
        document.getElementById(
            'password'
        );


    if (passwordInput) {

        passwordInput.addEventListener(
            'input',
            function() {

                if (
                    this.value.length > 0 &&
                    this.value.length < 8
                ) {

                    this.style.borderColor =
                        '#fca5a5';

                } else {

                    this.style.borderColor =
                        '';

                }

            }
        );

    }

</script>


</body>
</html>