<?php
/**
 * Pure Chemical Admin
 * File: admin/user.php
 *
 * Existing tables used:
 *   users
 *   roles
 *   media
 *
 * No new table is created.
 */

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()) .
            '">';
    }
}

function verify_csrf()
{
    $token = $_POST['csrf_token'] ?? '';

    if (
        empty($token) ||
        empty($_SESSION['csrf_token']) ||
        !hash_equals(
            $_SESSION['csrf_token'],
            $token
        )
    ) {
        throw new RuntimeException(
            'Invalid security token. Please refresh the page and try again.'
        );
    }
}

function flash_message($type, $message)
{
    $_SESSION['user_page_flash'] = [
        'type' => $type,
        'message' => $message
    ];
}

function get_flash_message()
{
    $flash = $_SESSION['user_page_flash'] ?? null;

    unset($_SESSION['user_page_flash']);

    return $flash;
}

function redirect_user_page($params = [])
{
    $url = 'user.php';

    if (!empty($params)) {
        $url .= '?' . http_build_query($params);
    }

    header('Location: ' . $url);
    exit;
}

/* =========================================================
   CURRENT ADMIN
========================================================= */

$currentAdminId = 0;

if (!empty($_SESSION['ADMIN_ID'])) {
    $currentAdminId = (int)$_SESSION['ADMIN_ID'];
} elseif (!empty($_SESSION['admin_id'])) {
    $currentAdminId = (int)$_SESSION['admin_id'];
}

/* =========================================================
   ACTIONS
========================================================= */

$action = $_POST['action'] ?? '';

try {

    /* =====================================================
       SAVE USER
    ===================================================== */

    if ($action === 'save') {

        verify_csrf();

        $id = (int)($_POST['id'] ?? 0);

        $roleId = !empty($_POST['role_id'])
            ? (int)$_POST['role_id']
            : null;

        $name = trim($_POST['name'] ?? '');

        $username = trim(
            $_POST['username'] ?? ''
        );

        $email = trim(
            $_POST['email'] ?? ''
        );

        $password = $_POST['password'] ?? '';

        $mobile = trim(
            $_POST['mobile'] ?? ''
        );

        $avatarId = !empty($_POST['avatar_id'])
            ? (int)$_POST['avatar_id']
            : null;

        $status = isset($_POST['status'])
            ? (int)$_POST['status']
            : 1;


        /* ---------------------------------------------
           VALIDATION
        --------------------------------------------- */

        if ($name === '') {
            throw new RuntimeException(
                'Please enter user name.'
            );
        }

        if (mb_strlen($name) > 150) {
            throw new RuntimeException(
                'User name cannot exceed 150 characters.'
            );
        }


        if ($email === '') {
            throw new RuntimeException(
                'Please enter email address.'
            );
        }

        if (!filter_var(
            $email,
            FILTER_VALIDATE_EMAIL
        )) {
            throw new RuntimeException(
                'Please enter a valid email address.'
            );
        }

        if (mb_strlen($email) > 190) {
            throw new RuntimeException(
                'Email address cannot exceed 190 characters.'
            );
        }


        if ($username !== '') {

            if (mb_strlen($username) > 100) {
                throw new RuntimeException(
                    'Username cannot exceed 100 characters.'
                );
            }

            if (!preg_match(
                '/^[a-zA-Z0-9._-]+$/',
                $username
            )) {
                throw new RuntimeException(
                    'Username can contain only letters, numbers, dot, underscore and hyphen.'
                );
            }
        }


        if ($mobile !== '' && mb_strlen($mobile) > 30) {
            throw new RuntimeException(
                'Mobile number cannot exceed 30 characters.'
            );
        }


        $status = $status === 1 ? 1 : 0;


        /* ---------------------------------------------
           ROLE CHECK
        --------------------------------------------- */

        if ($roleId !== null) {

            $roleCheck = $pdo->prepare("
                SELECT id
                FROM roles
                WHERE id = :id
                LIMIT 1
            ");

            $roleCheck->execute([
                ':id' => $roleId
            ]);

            if (!$roleCheck->fetch()) {
                throw new RuntimeException(
                    'Selected role does not exist.'
                );
            }
        }


        /* ---------------------------------------------
           AVATAR CHECK
        --------------------------------------------- */

        if ($avatarId !== null) {

            $avatarCheck = $pdo->prepare("
                SELECT id
                FROM media
                WHERE id = :id
                LIMIT 1
            ");

            $avatarCheck->execute([
                ':id' => $avatarId
            ]);

            if (!$avatarCheck->fetch()) {
                throw new RuntimeException(
                    'Selected avatar media does not exist.'
                );
            }
        }


        /* ---------------------------------------------
           DUPLICATE EMAIL
        --------------------------------------------- */

        $sql = "
            SELECT id
            FROM users
            WHERE LOWER(email) = LOWER(:email)
        ";

        if ($id > 0) {
            $sql .= "
                AND id != :id
            ";
        }

        $sql .= " LIMIT 1";

        $stmt = $pdo->prepare($sql);

        $params = [
            ':email' => $email
        ];

        if ($id > 0) {
            $params[':id'] = $id;
        }

        $stmt->execute($params);

        if ($stmt->fetch()) {
            throw new RuntimeException(
                'This email address is already registered.'
            );
        }


        /* ---------------------------------------------
           DUPLICATE USERNAME
        --------------------------------------------- */

        if ($username !== '') {

            $sql = "
                SELECT id
                FROM users
                WHERE LOWER(username) = LOWER(:username)
            ";

            if ($id > 0) {
                $sql .= "
                    AND id != :id
                ";
            }

            $sql .= " LIMIT 1";

            $stmt = $pdo->prepare($sql);

            $params = [
                ':username' => $username
            ];

            if ($id > 0) {
                $params[':id'] = $id;
            }

            $stmt->execute($params);

            if ($stmt->fetch()) {
                throw new RuntimeException(
                    'This username is already in use.'
                );
            }
        }


        /* =================================================
           UPDATE USER
        ================================================= */

        if ($id > 0) {

            $checkStmt = $pdo->prepare("
                SELECT id
                FROM users
                WHERE id = :id
                LIMIT 1
            ");

            $checkStmt->execute([
                ':id' => $id
            ]);

            if (!$checkStmt->fetch()) {
                throw new RuntimeException(
                    'User not found.'
                );
            }


            /* -----------------------------------------
               PASSWORD PROVIDED
            ----------------------------------------- */

            if ($password !== '') {

                if (strlen($password) < 6) {
                    throw new RuntimeException(
                        'Password must contain at least 6 characters.'
                    );
                }

                $passwordHash = password_hash(
                    $password,
                    PASSWORD_DEFAULT
                );

                $update = $pdo->prepare("
                    UPDATE users
                    SET
                        role_id = :role_id,
                        name = :name,
                        username = :username,
                        email = :email,
                        password = :password,
                        mobile = :mobile,
                        avatar_id = :avatar_id,
                        status = :status
                    WHERE id = :id
                ");

                $update->execute([
                    ':role_id' => $roleId,
                    ':name' => $name,
                    ':username' => $username !== ''
                        ? $username
                        : null,
                    ':email' => $email,
                    ':password' => $passwordHash,
                    ':mobile' => $mobile !== ''
                        ? $mobile
                        : null,
                    ':avatar_id' => $avatarId,
                    ':status' => $status,
                    ':id' => $id
                ]);

            } else {

                $update = $pdo->prepare("
                    UPDATE users
                    SET
                        role_id = :role_id,
                        name = :name,
                        username = :username,
                        email = :email,
                        mobile = :mobile,
                        avatar_id = :avatar_id,
                        status = :status
                    WHERE id = :id
                ");

                $update->execute([
                    ':role_id' => $roleId,
                    ':name' => $name,
                    ':username' => $username !== ''
                        ? $username
                        : null,
                    ':email' => $email,
                    ':mobile' => $mobile !== ''
                        ? $mobile
                        : null,
                    ':avatar_id' => $avatarId,
                    ':status' => $status,
                    ':id' => $id
                ]);
            }


            flash_message(
                'success',
                'User updated successfully.'
            );

            redirect_user_page();
        }


        /* =================================================
           CREATE USER
        ================================================= */

        if ($password === '') {
            throw new RuntimeException(
                'Password is required when creating a new user.'
            );
        }

        if (strlen($password) < 6) {
            throw new RuntimeException(
                'Password must contain at least 6 characters.'
            );
        }

        $passwordHash = password_hash(
            $password,
            PASSWORD_DEFAULT
        );

        $insert = $pdo->prepare("
            INSERT INTO users
            (
                role_id,
                name,
                username,
                email,
                password,
                mobile,
                avatar_id,
                status
            )
            VALUES
            (
                :role_id,
                :name,
                :username,
                :email,
                :password,
                :mobile,
                :avatar_id,
                :status
            )
        ");

        $insert->execute([
            ':role_id' => $roleId,
            ':name' => $name,
            ':username' => $username !== ''
                ? $username
                : null,
            ':email' => $email,
            ':password' => $passwordHash,
            ':mobile' => $mobile !== ''
                ? $mobile
                : null,
            ':avatar_id' => $avatarId,
            ':status' => $status
        ]);

        flash_message(
            'success',
            'New user created successfully.'
        );

        redirect_user_page();
    }


    /* =====================================================
       DELETE
    ===================================================== */

    if ($action === 'delete') {

        verify_csrf();

        $id = (int)($_POST['id'] ?? 0);

        if ($id <= 0) {
            throw new RuntimeException(
                'Invalid user ID.'
            );
        }

        $stmt = $pdo->prepare("
            SELECT
                id,
                name,
                email
            FROM users
            WHERE id = :id
            LIMIT 1
        ");

        $stmt->execute([
            ':id' => $id
        ]);

        $user = $stmt->fetch();

        if (!$user) {
            throw new RuntimeException(
                'User not found.'
            );
        }

        $delete = $pdo->prepare("
            DELETE FROM users
            WHERE id = :id
            LIMIT 1
        ");

        $delete->execute([
            ':id' => $id
        ]);

        flash_message(
            'success',
            'User deleted successfully.'
        );

        redirect_user_page();
    }


    /* =====================================================
       TOGGLE STATUS
    ===================================================== */

    if ($action === 'toggle_status') {

        verify_csrf();

        $id = (int)($_POST['id'] ?? 0);

        if ($id <= 0) {
            throw new RuntimeException(
                'Invalid user ID.'
            );
        }

        $stmt = $pdo->prepare("
            SELECT status
            FROM users
            WHERE id = :id
            LIMIT 1
        ");

        $stmt->execute([
            ':id' => $id
        ]);

        $user = $stmt->fetch();

        if (!$user) {
            throw new RuntimeException(
                'User not found.'
            );
        }

        $newStatus =
            ((int)$user['status'] === 1)
                ? 0
                : 1;

        $update = $pdo->prepare("
            UPDATE users
            SET status = :status
            WHERE id = :id
        ");

        $update->execute([
            ':status' => $newStatus,
            ':id' => $id
        ]);

        flash_message(
            'success',
            $newStatus === 1
                ? 'User activated successfully.'
                : 'User deactivated successfully.'
        );

        redirect_user_page();
    }

} catch (Throwable $e) {

    flash_message(
        'error',
        $e->getMessage()
    );

    redirect_user_page();
}


/* =========================================================
   FLASH
========================================================= */

$flash = get_flash_message();


/* =========================================================
   FILTERS
========================================================= */

$search = trim(
    $_GET['search'] ?? ''
);

$roleFilter = $_GET['role'] ?? '';

$statusFilter = $_GET['status'] ?? '';


/* =========================================================
   ROLES
========================================================= */

$roles = [];

try {

    $roleStmt = $pdo->query("
        SELECT
            id,
            name
        FROM roles
        ORDER BY name ASC, id ASC
    ");

    $roles = $roleStmt->fetchAll();

} catch (Throwable $e) {

    $roles = [];
}


/* =========================================================
   MEDIA / AVATARS
========================================================= */

$mediaItems = [];

try {

    $mediaStmt = $pdo->query("
        SELECT
            id,
            file_name,
            file_path,
            title
        FROM media
        ORDER BY id DESC
        LIMIT 100
    ");

    $mediaItems = $mediaStmt->fetchAll();

} catch (Throwable $e) {

    $mediaItems = [];
}


/* =========================================================
   STATISTICS
========================================================= */

$totalUsers = (int)$pdo
    ->query("
        SELECT COUNT(*)
        FROM users
    ")
    ->fetchColumn();


$activeUsers = (int)$pdo
    ->query("
        SELECT COUNT(*)
        FROM users
        WHERE status = 1
    ")
    ->fetchColumn();


$inactiveUsers = (int)$pdo
    ->query("
        SELECT COUNT(*)
        FROM users
        WHERE status = 0
    ")
    ->fetchColumn();


$onlineUsers = (int)$pdo
    ->query("
        SELECT COUNT(*)
        FROM users
        WHERE last_login_at IS NOT NULL
        AND last_login_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    ")
    ->fetchColumn();


/* =========================================================
   USERS LIST
========================================================= */

$where = [];
$params = [];


if ($search !== '') {

    $where[] = "
        (
            u.name LIKE :search
            OR u.username LIKE :search
            OR u.email LIKE :search
            OR u.mobile LIKE :search
        )
    ";

    $params[':search'] =
        '%' . $search . '%';
}


if (
    $roleFilter !== '' &&
    ctype_digit((string)$roleFilter)
) {

    $where[] = "
        u.role_id = :role_id
    ";

    $params[':role_id'] =
        (int)$roleFilter;
}


if (
    $statusFilter === '0' ||
    $statusFilter === '1'
) {

    $where[] = "
        u.status = :status
    ";

    $params[':status'] =
        (int)$statusFilter;
}


$listSql = "
    SELECT
        u.id,
        u.role_id,
        u.name,
        u.username,
        u.email,
        u.mobile,
        u.avatar_id,
        u.last_login_at,
        u.status,
        u.created_at,
        u.updated_at,

        r.name AS role_name,

        m.file_name AS avatar_file,
        m.file_path AS avatar_path,
        m.title AS avatar_title

    FROM users u

    LEFT JOIN roles r
        ON r.id = u.role_id

    LEFT JOIN media m
        ON m.id = u.avatar_id
";


if (!empty($where)) {

    $listSql .= "
        WHERE " .
        implode(
            " AND ",
            $where
        );
}


$listSql .= "
    ORDER BY u.id DESC
";


$listStmt = $pdo->prepare(
    $listSql
);

$listStmt->execute(
    $params
);

$users = $listStmt->fetchAll();


/* =========================================================
   EDIT USER
========================================================= */

$editUser = null;

if (!empty($_GET['edit'])) {

    $editId = (int)$_GET['edit'];

    if ($editId > 0) {

        $editStmt = $pdo->prepare("
            SELECT
                id,
                role_id,
                name,
                username,
                email,
                mobile,
                avatar_id,
                status
            FROM users
            WHERE id = :id
            LIMIT 1
        ");

        $editStmt->execute([
            ':id' => $editId
        ]);

        $editUser =
            $editStmt->fetch() ?: null;
    }
}

?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>
        Users | Pure Chemical Admin
    </title>

    <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: #16a34a;
            --primary-dark: #15803d;
            --primary-soft: #ecfdf3;

            --text: #17211b;
            --muted: #758079;

            --bg: #f5f8f6;
            --card: #ffffff;
            --border: #e6ece8;

            --danger: #dc2626;
            --danger-soft: #fef2f2;

            --warning: #d97706;
            --warning-soft: #fffbeb;

            --blue: #2563eb;
            --blue-soft: #eff6ff;

            --shadow:
                0 12px 35px rgba(
                    16,
                    24,
                    40,
                    0.06
                );

            --radius: 18px;
        }


        * {
            box-sizing: border-box;
        }


        html {
            scroll-behavior: smooth;
        }


        body {
            margin: 0;

            font-family:
                "Inter",
                sans-serif;

            background:
                var(--bg);

            color:
                var(--text);
        }


        button,
        input,
        select {
            font-family: inherit;
        }


        a {
            color: inherit;
            text-decoration: none;
        }


        /* =================================================
           PAGE
        ================================================= */

        .user-page {
            margin-left: 280px;
            min-height: 100vh;
        }


        /* =================================================
           TOPBAR
        ================================================= */

        .topbar {
            position: sticky;

            top: 0;

            z-index: 100;

            height: 78px;

            display: flex;

            align-items: center;

            justify-content: space-between;

            padding:
                0 30px;

            background:
                rgba(
                    255,
                    255,
                    255,
                    0.94
                );

            border-bottom:
                1px solid
                var(--border);

            backdrop-filter:
                blur(18px);
        }


        .topbar-left {
            display: flex;

            align-items: center;

            gap: 13px;
        }


        .topbar-icon {
            width: 43px;
            height: 43px;

            display: flex;

            align-items: center;
            justify-content: center;

            border-radius: 13px;

            color:
                var(--primary);

            background:
                var(--primary-soft);
        }


        .topbar-title h1 {
            margin: 0;

            font-size: 19px;

            font-weight: 800;
        }


        .topbar-title p {
            margin:
                4px 0 0;

            color:
                var(--muted);

            font-size: 11px;
        }


        .topbar-right {
            display: flex;

            align-items: center;

            gap: 10px;
        }


        .admin-badge {
            display: flex;

            align-items: center;

            gap: 8px;

            padding:
                9px 13px;

            border:
                1px solid
                var(--border);

            border-radius: 12px;

            background: #fff;

            font-size: 12px;

            font-weight: 700;
        }


        .admin-badge i {
            color:
                var(--primary);
        }


        /* =================================================
           CONTENT
        ================================================= */

        .content {
            padding: 30px;
        }


        .page-heading {
            display: flex;

            align-items: flex-end;

            justify-content: space-between;

            gap: 20px;

            margin-bottom: 24px;
        }


        .page-heading h2 {
            margin: 0 0 6px;

            font-size: 28px;

            font-weight: 800;

            letter-spacing:
                -0.7px;
        }


        .page-heading p {
            margin: 0;

            color:
                var(--muted);

            font-size: 13px;
        }


        /* =================================================
           BUTTONS
        ================================================= */

        .btn {
            min-height: 43px;

            display: inline-flex;

            align-items: center;

            justify-content: center;

            gap: 8px;

            padding:
                0 16px;

            border: 0;

            border-radius: 12px;

            cursor: pointer;

            font-size: 12px;

            font-weight: 750;

            transition:
                0.2s ease;
        }


        .btn-primary {
            color: #fff;

            background:
                var(--primary);

            box-shadow:
                0 8px 20px
                rgba(
                    22,
                    163,
                    74,
                    0.20
                );
        }


        .btn-primary:hover {
            background:
                var(--primary-dark);

            transform:
                translateY(-1px);
        }


        .btn-light {
            color:
                var(--text);

            background:
                #fff;

            border:
                1px solid
                var(--border);
        }


        .btn-light:hover {
            border-color:
                #cbd5cf;
        }


        .btn-danger {
            color: #fff;

            background:
                var(--danger);
        }


        /* =================================================
           STATS
        ================================================= */

        .stats {
            display: grid;

            grid-template-columns:
                repeat(
                    4,
                    minmax(0, 1fr)
                );

            gap: 17px;

            margin-bottom: 21px;
        }


        .stat-card {
            position: relative;

            padding: 20px;

            background:
                var(--card);

            border:
                1px solid
                var(--border);

            border-radius:
                var(--radius);

            box-shadow:
                var(--shadow);

            overflow: hidden;
        }


        .stat-card::after {
            content: "";

            position: absolute;

            width: 90px;
            height: 90px;

            right: -40px;
            bottom: -40px;

            border-radius: 50%;

            background:
                var(--primary-soft);
        }


        .stat-icon {
            width: 42px;
            height: 42px;

            display: flex;

            align-items: center;
            justify-content: center;

            margin-bottom: 13px;

            border-radius: 13px;

            color:
                var(--primary);

            background:
                var(--primary-soft);
        }


        .stat-value {
            font-size: 25px;

            font-weight: 800;

            letter-spacing:
                -0.5px;
        }


        .stat-label {
            margin-top: 4px;

            color:
                var(--muted);

            font-size: 11px;

            font-weight: 650;
        }


        /* =================================================
           FILTER BAR
        ================================================= */

        .filter-card {
            display: flex;

            align-items: center;

            justify-content: space-between;

            gap: 12px;

            padding: 15px;

            margin-bottom: 18px;

            background: #fff;

            border:
                1px solid
                var(--border);

            border-radius:
                var(--radius);

            box-shadow:
                var(--shadow);
        }


        .filters {
            display: flex;

            align-items: center;

            gap: 9px;

            flex: 1;
        }


        .search {
            position: relative;

            flex: 1;

            max-width: 430px;
        }


        .search i {
            position: absolute;

            left: 13px;

            top: 50%;

            transform:
                translateY(-50%);

            color:
                #9aa49f;

            font-size: 12px;
        }


        .search input,
        .filter-select {
            width: 100%;

            height: 43px;

            padding:
                0 12px 0 38px;

            outline: none;

            background:
                #fafcfb;

            border:
                1px solid
                var(--border);

            border-radius: 11px;

            font-size: 12px;

            color:
                var(--text);
        }


        .filter-select {
            min-width: 150px;

            padding-left: 12px;
        }


        .search input:focus,
        .filter-select:focus {
            border-color:
                rgba(
                    22,
                    163,
                    74,
                    0.45
                );

            box-shadow:
                0 0 0 3px
                rgba(
                    22,
                    163,
                    74,
                    0.08
                );
        }


        /* =================================================
           TABLE
        ================================================= */

        .table-card {
            background: #fff;

            border:
                1px solid
                var(--border);

            border-radius:
                var(--radius);

            box-shadow:
                var(--shadow);

            overflow: hidden;
        }


        .table-header {
            display: flex;

            align-items: center;

            justify-content: space-between;

            padding:
                18px 21px;

            border-bottom:
                1px solid
                var(--border);
        }


        .table-header h3 {
            margin: 0;

            font-size: 15px;

            font-weight: 800;
        }


        .table-header span {
            display: block;

            margin-top: 4px;

            color:
                var(--muted);

            font-size: 10px;
        }


        .table-wrap {
            width: 100%;

            overflow-x: auto;
        }


        table {
            width: 100%;

            min-width: 1100px;

            border-collapse:
                collapse;
        }


        th {
            padding:
                13px 18px;

            text-align: left;

            background:
                #fafcfb;

            color:
                #7b867f;

            font-size: 9px;

            font-weight: 800;

            text-transform:
                uppercase;

            letter-spacing:
                0.7px;

            white-space:
                nowrap;
        }


        td {
            padding:
                14px 18px;

            border-top:
                1px solid
                #edf1ee;

            font-size: 12px;

            vertical-align:
                middle;
        }


        tbody tr {
            transition:
                0.18s ease;
        }


        tbody tr:hover {
            background:
                #fbfdfc;
        }


        /* =================================================
           USER CELL
        ================================================= */

        .user-cell {
            display: flex;

            align-items: center;

            gap: 11px;
        }


        .avatar {
            width: 40px;
            height: 40px;

            flex: 0 0 40px;

            display: flex;

            align-items: center;
            justify-content: center;

            overflow: hidden;

            border-radius: 12px;

            color:
                var(--primary);

            background:
                var(--primary-soft);

            font-size: 13px;

            font-weight: 800;
        }


        .avatar img {
            width: 100%;
            height: 100%;

            object-fit: cover;
        }


        .user-name {
            font-weight: 750;
        }


        .user-id {
            margin-top: 3px;

            color:
                #98a39d;

            font-size: 9px;
        }


        .email {
            color:
                #4e5953;

            font-weight: 600;
        }


        .username {
            color:
                #647069;

            font-size: 11px;
        }


        .role-badge {
            display: inline-flex;

            align-items: center;

            gap: 5px;

            padding:
                6px 9px;

            border-radius:
                999px;

            color:
                #2563eb;

            background:
                #eff6ff;

            font-size: 9px;

            font-weight: 800;
        }


        .role-empty {
            color:
                #a0aaa4;

            font-size: 11px;
        }


        .status {
            display: inline-flex;

            align-items: center;

            gap: 5px;

            padding:
                6px 9px;

            border-radius:
                999px;

            font-size: 9px;

            font-weight: 800;
        }


        .status.active {
            color:
                #15803d;

            background:
                #ecfdf3;
        }


        .status.inactive {
            color:
                #b45309;

            background:
                #fffbeb;
        }


        .last-login {
            color:
                #6c7770;

            font-size: 10px;

            line-height: 1.5;
        }


        .actions {
            display: flex;

            align-items: center;

            gap: 5px;
        }


        .action-btn {
            width: 33px;
            height: 33px;

            display: inline-flex;

            align-items: center;
            justify-content: center;

            border:
                1px solid
                var(--border);

            border-radius: 9px;

            background:
                #fff;

            color:
                #68736d;

            cursor: pointer;

            transition:
                0.18s ease;
        }


        .action-btn:hover {
            color:
                var(--primary);

            background:
                var(--primary-soft);

            border-color:
                rgba(
                    22,
                    163,
                    74,
                    0.3
                );
        }


        .action-btn.danger:hover {
            color:
                var(--danger);

            background:
                var(--danger-soft);

            border-color:
                rgba(
                    220,
                    38,
                    38,
                    0.25
                );
        }


        /* =================================================
           EMPTY
        ================================================= */

        .empty {
            padding:
                65px 20px;

            text-align: center;
        }


        .empty-icon {
            width: 62px;
            height: 62px;

            display: flex;

            align-items: center;
            justify-content: center;

            margin:
                0 auto 15px;

            border-radius: 18px;

            color:
                var(--primary);

            background:
                var(--primary-soft);

            font-size: 21px;
        }


        .empty h3 {
            margin:
                0 0 6px;

            font-size: 16px;
        }


        .empty p {
            margin: 0;

            color:
                var(--muted);

            font-size: 11px;
        }


        /* =================================================
           ALERT
        ================================================= */

        .alert {
            display: flex;

            align-items: flex-start;

            gap: 10px;

            padding:
                13px 15px;

            margin-bottom: 20px;

            border-radius: 12px;

            font-size: 12px;

            font-weight: 600;
        }


        .alert.success {
            color:
                #166534;

            background:
                #f0fdf4;

            border:
                1px solid
                #bbf7d0;
        }


        .alert.error {
            color:
                #991b1b;

            background:
                #fef2f2;

            border:
                1px solid
                #fecaca;
        }


        /* =================================================
           MODAL
        ================================================= */

        .modal {
            position: fixed;

            inset: 0;

            z-index: 999;

            display: none;

            align-items: center;

            justify-content: center;

            padding: 20px;

            background:
                rgba(
                    15,
                    23,
                    18,
                    0.52
                );

            backdrop-filter:
                blur(6px);
        }


        .modal.show {
            display: flex;
        }


        .modal-card {
            width: 100%;

            max-width: 650px;

            max-height:
                calc(
                    100vh - 40px
                );

            overflow-y: auto;

            background:
                #fff;

            border-radius:
                22px;

            box-shadow:
                0 30px 80px
                rgba(
                    0,
                    0,
                    0,
                    0.20
                );

            animation:
                modalIn
                0.2s ease;
        }


        @keyframes modalIn {

            from {
                opacity: 0;

                transform:
                    translateY(12px)
                    scale(0.98);
            }

            to {
                opacity: 1;

                transform:
                    translateY(0)
                    scale(1);
            }
        }


        .modal-head {
            display: flex;

            align-items: center;

            justify-content: space-between;

            padding:
                20px 22px;

            border-bottom:
                1px solid
                var(--border);
        }


        .modal-head h3 {
            margin: 0;

            font-size: 17px;

            font-weight: 800;
        }


        .modal-head p {
            margin:
                4px 0 0;

            color:
                var(--muted);

            font-size: 10px;
        }


        .close-btn {
            width: 35px;
            height: 35px;

            display: flex;

            align-items: center;
            justify-content: center;

            border:
                1px solid
                var(--border);

            border-radius: 10px;

            background: #fff;

            color:
                #66716b;

            cursor: pointer;
        }


        .modal-body {
            padding:
                22px;
        }


        .form-grid {
            display: grid;

            grid-template-columns:
                repeat(
                    2,
                    minmax(0, 1fr)
                );

            gap: 15px;
        }


        .field.full {
            grid-column:
                1 / -1;
        }


        .field label {
            display: block;

            margin-bottom: 7px;

            color:
                #4f5a54;

            font-size: 10px;

            font-weight: 800;
        }


        .field label span {
            color:
                var(--danger);
        }


        .field input,
        .field select {
            width: 100%;

            height: 44px;

            padding:
                0 12px;

            outline: none;

            border:
                1px solid
                var(--border);

            border-radius: 11px;

            background:
                #fbfcfb;

            color:
                var(--text);

            font-size: 12px;
        }


        .field input:focus,
        .field select:focus {
            border-color:
                rgba(
                    22,
                    163,
                    74,
                    0.45
                );

            box-shadow:
                0 0 0 3px
                rgba(
                    22,
                    163,
                    74,
                    0.08
                );
        }


        .field small {
            display: block;

            margin-top: 5px;

            color:
                #8c9690;

            font-size: 9px;
        }


        .modal-footer {
            display: flex;

            align-items: center;

            justify-content: flex-end;

            gap: 9px;

            padding:
                17px 22px;

            border-top:
                1px solid
                var(--border);
        }


        /* =================================================
           DELETE MODAL
        ================================================= */

        .delete-card {
            max-width: 430px;
        }


        .delete-content {
            padding:
                28px 24px;

            text-align: center;
        }


        .delete-icon {
            width: 58px;
            height: 58px;

            display: flex;

            align-items: center;
            justify-content: center;

            margin:
                0 auto 15px;

            border-radius: 17px;

            color:
                var(--danger);

            background:
                var(--danger-soft);

            font-size: 20px;
        }


        .delete-content h3 {
            margin:
                0 0 7px;

            font-size: 17px;
        }


        .delete-content p {
            margin: 0;

            color:
                var(--muted);

            font-size: 11px;

            line-height: 1.6;
        }


        /* =================================================
           RESPONSIVE
        ================================================= */

        @media (max-width: 1200px) {

            .stats {
                grid-template-columns:
                    repeat(
                        2,
                        minmax(0, 1fr)
                    );
            }
        }


        @media (max-width: 1100px) {

            .user-page {
                margin-left: 0;
            }

            .content {
                padding: 22px;
            }

            .topbar {
                padding:
                    0 20px;
            }
        }


        @media (max-width: 760px) {

            .page-heading {
                align-items:
                    flex-start;

                flex-direction:
                    column;
            }

            .filter-card {
                align-items:
                    stretch;

                flex-direction:
                    column;
            }

            .filters {
                align-items:
                    stretch;

                flex-direction:
                    column;
            }

            .search {
                max-width:
                    none;
            }

            .stats {
                grid-template-columns:
                    1fr;
            }

            .form-grid {
                grid-template-columns:
                    1fr;
            }

            .field.full {
                grid-column:
                    auto;
            }

            .topbar-title p {
                display:
                    none;
            }

            .admin-badge {
                display:
                    none;
            }
        }


        @media (max-width: 520px) {

            .content {
                padding:
                    16px;
            }

            .topbar {
                height:
                    68px;
            }

            .page-heading h2 {
                font-size:
                    24px;
            }

            .modal {
                padding:
                    10px;
            }

            .modal-card {
                max-height:
                    calc(
                        100vh - 20px
                    );

                border-radius:
                    18px;
            }
        }

    </style>

</head>


<body>


<?php
/*
 * Existing admin sidebar.
 * Sidebar is intentionally included separately.
 */
require_once __DIR__ . '/sidebar.php';
?>


<div class="user-page">


    <!-- =================================================
         TOPBAR
    ================================================= -->

    <header class="topbar">

        <div class="topbar-left">

            <div class="topbar-icon">

                <i class="fa-solid fa-users"></i>

            </div>

            <div class="topbar-title">

                <h1>
                    Website Users
                </h1>

                <p>
                    Manage website accounts
                </p>

            </div>

        </div>


        <div class="topbar-right">

            <div class="admin-badge">

                <i class="fa-solid fa-shield-halved"></i>

                Admin Panel

            </div>


            <button
                type="button"
                class="btn btn-primary"
                onclick="openUserModal()"
            >

                <i class="fa-solid fa-user-plus"></i>

                Add User

            </button>

        </div>

    </header>


    <!-- =================================================
         CONTENT
    ================================================= -->

    <main class="content">


        <!-- PAGE HEADING -->

        <div class="page-heading">

            <div>

                <h2>
                    Users
                </h2>

                <p>
                    Manage website users, roles,
                    account status and login activity.
                </p>

            </div>


            <button
                type="button"
                class="btn btn-primary"
                onclick="openUserModal()"
            >

                <i class="fa-solid fa-plus"></i>

                Create User

            </button>

        </div>


        <!-- ALERT -->

        <?php if ($flash): ?>

            <div
                class="alert <?= $flash['type'] === 'success'
                    ? 'success'
                    : 'error'; ?>"
            >

                <i
                    class="fa-solid <?= $flash['type'] === 'success'
                        ? 'fa-circle-check'
                        : 'fa-circle-exclamation'; ?>"
                ></i>

                <div>

                    <?= e(
                        $flash['message']
                    ); ?>

                </div>

            </div>

        <?php endif; ?>


        <!-- =================================================
             STATS
        ================================================= -->

        <section class="stats">


            <div class="stat-card">

                <div class="stat-icon">

                    <i class="fa-solid fa-users"></i>

                </div>

                <div class="stat-value">

                    <?= number_format(
                        $totalUsers
                    ); ?>

                </div>

                <div class="stat-label">

                    Total Users

                </div>

            </div>


            <div class="stat-card">

                <div class="stat-icon">

                    <i class="fa-solid fa-user-check"></i>

                </div>

                <div class="stat-value">

                    <?= number_format(
                        $activeUsers
                    ); ?>

                </div>

                <div class="stat-label">

                    Active Users

                </div>

            </div>


            <div class="stat-card">

                <div class="stat-icon">

                    <i class="fa-solid fa-user-slash"></i>

                </div>

                <div class="stat-value">

                    <?= number_format(
                        $inactiveUsers
                    ); ?>

                </div>

                <div class="stat-label">

                    Inactive Users

                </div>

            </div>


            <div class="stat-card">

                <div class="stat-icon">

                    <i class="fa-solid fa-clock-rotate-left"></i>

                </div>

                <div class="stat-value">

                    <?= number_format(
                        $onlineUsers
                    ); ?>

                </div>

                <div class="stat-label">

                    Logged In Last 30 Days

                </div>

            </div>


        </section>


        <!-- =================================================
             FILTERS
        ================================================= -->

        <form
            method="get"
            class="filter-card"
        >

            <div class="filters">


                <div class="search">

                    <i
                        class="fa-solid fa-magnifying-glass"
                    ></i>

                    <input
                        type="search"
                        name="search"
                        value="<?= e(
                            $search
                        ); ?>"
                        placeholder="Search name, username, email or mobile..."
                    >

                </div>


                <select
                    name="role"
                    class="filter-select"
                    onchange="this.form.submit()"
                >

                    <option value="">
                        All Roles
                    </option>


                    <?php foreach ($roles as $role): ?>

                        <option
                            value="<?= (int)$role['id']; ?>"
                            <?= (string)$roleFilter ===
                            (string)$role['id']
                                ? 'selected'
                                : ''; ?>
                        >

                            <?= e(
                                $role['name']
                            ); ?>

                        </option>

                    <?php endforeach; ?>

                </select>


                <select
                    name="status"
                    class="filter-select"
                    onchange="this.form.submit()"
                >

                    <option value="">
                        All Status
                    </option>

                    <option
                        value="1"
                        <?= $statusFilter === '1'
                            ? 'selected'
                            : ''; ?>
                    >
                        Active
                    </option>

                    <option
                        value="0"
                        <?= $statusFilter === '0'
                            ? 'selected'
                            : ''; ?>
                    >
                        Inactive
                    </option>

                </select>


            </div>


            <button
                type="submit"
                class="btn btn-light"
            >

                <i class="fa-solid fa-filter"></i>

                Filter

            </button>

        </form>


        <!-- =================================================
             USER TABLE
        ================================================= -->

        <section class="table-card">


            <div class="table-header">

                <div>

                    <h3>
                        User Directory
                    </h3>

                    <span>
                        <?= number_format(
                            count($users)
                        ); ?>

                        result<?= count($users) === 1
                            ? ''
                            : 's'; ?>
                    </span>

                </div>


                <button
                    type="button"
                    class="btn btn-light"
                    onclick="openUserModal()"
                >

                    <i class="fa-solid fa-user-plus"></i>

                    New User

                </button>

            </div>


            <div class="table-wrap">


                <?php if (!empty($users)): ?>


                    <table>

                        <thead>

                            <tr>

                                <th>
                                    User
                                </th>

                                <th>
                                    Email
                                </th>

                                <th>
                                    Mobile
                                </th>

                                <th>
                                    Role
                                </th>

                                <th>
                                    Status
                                </th>

                                <th>
                                    Last Login
                                </th>

                                <th>
                                    Actions
                                </th>

                            </tr>

                        </thead>


                        <tbody>


                        <?php foreach ($users as $user): ?>


                            <?php

                            $initial =
                                strtoupper(
                                    mb_substr(
                                        trim(
                                            $user['name']
                                        ),
                                        0,
                                        1
                                    )
                                );


                            $avatarUrl = '';

                            if (!empty(
                                $user['avatar_path']
                            )) {

                                $avatarUrl =
                                    $user['avatar_path'];

                            }


                            $lastLogin =
                                'Never';

                            if (!empty(
                                $user['last_login_at']
                            )) {

                                $lastLogin =
                                    date(
                                        'd M Y, h:i A',
                                        strtotime(
                                            $user['last_login_at']
                                        )
                                    );
                            }

                            ?>


                            <tr>


                                <!-- USER -->

                                <td>

                                    <div class="user-cell">


                                        <div class="avatar">

                                            <?php if (
                                                $avatarUrl !== ''
                                            ): ?>

                                                <img
                                                    src="<?= e(
                                                        $avatarUrl
                                                    ); ?>"
                                                    alt="<?= e(
                                                        $user['name']
                                                    ); ?>"
                                                >

                                            <?php else: ?>

                                                <?= e(
                                                    $initial ?: 'U'
                                                ); ?>

                                            <?php endif; ?>

                                        </div>


                                        <div>

                                            <div class="user-name">

                                                <?= e(
                                                    $user['name']
                                                ); ?>

                                            </div>


                                            <div class="user-id">

                                                #<?= (int)$user['id']; ?>

                                                <?php if (
                                                    !empty(
                                                        $user['username']
                                                    )
                                                ): ?>

                                                    · @<?= e(
                                                        $user['username']
                                                    ); ?>

                                                <?php endif; ?>

                                            </div>

                                        </div>

                                    </div>

                                </td>


                                <!-- EMAIL -->

                                <td>

                                    <div class="email">

                                        <?= e(
                                            $user['email']
                                        ); ?>

                                    </div>

                                </td>


                                <!-- MOBILE -->

                                <td>

                                    <?php if (
                                        !empty(
                                            $user['mobile']
                                        )
                                    ): ?>

                                        <?= e(
                                            $user['mobile']
                                        ); ?>

                                    <?php else: ?>

                                        <span
                                            style="color:#a0aaa4;"
                                        >
                                            —
                                        </span>

                                    <?php endif; ?>

                                </td>


                                <!-- ROLE -->

                                <td>

                                    <?php if (
                                        !empty(
                                            $user['role_name']
                                        )
                                    ): ?>

                                        <span
                                            class="role-badge"
                                        >

                                            <i
                                                class="fa-solid fa-user-shield"
                                            ></i>

                                            <?= e(
                                                $user['role_name']
                                            ); ?>

                                        </span>

                                    <?php else: ?>

                                        <span
                                            class="role-empty"
                                        >
                                            No role
                                        </span>

                                    <?php endif; ?>

                                </td>


                                <!-- STATUS -->

                                <td>

                                    <?php if (
                                        (int)$user['status'] === 1
                                    ): ?>

                                        <span
                                            class="status active"
                                        >

                                            <i
                                                class="fa-solid fa-circle"
                                            ></i>

                                            Active

                                        </span>

                                    <?php else: ?>

                                        <span
                                            class="status inactive"
                                        >

                                            <i
                                                class="fa-solid fa-circle"
                                            ></i>

                                            Inactive

                                        </span>

                                    <?php endif; ?>

                                </td>


                                <!-- LAST LOGIN -->

                                <td>

                                    <div class="last-login">

                                        <?php if (
                                            !empty(
                                                $user['last_login_at']
                                            )
                                        ): ?>

                                            <i
                                                class="fa-regular fa-clock"
                                            ></i>

                                            <?= e(
                                                $lastLogin
                                            ); ?>

                                        <?php else: ?>

                                            <span
                                                style="color:#a0aaa4;"
                                            >
                                                Never logged in
                                            </span>

                                        <?php endif; ?>

                                    </div>

                                </td>


                                <!-- ACTIONS -->

                                <td>

                                    <div class="actions">


                                        <!-- EDIT -->

                                        <button
                                            type="button"
                                            class="action-btn"
                                            title="Edit User"
                                            onclick='editUser(
                                                <?= json_encode(
                                                    [
                                                        'id' =>
                                                            (int)$user['id'],

                                                        'role_id' =>
                                                            $user['role_id'] !== null
                                                                ? (int)$user['role_id']
                                                                : '',

                                                        'name' =>
                                                            $user['name'],

                                                        'username' =>
                                                            $user['username'],

                                                        'email' =>
                                                            $user['email'],

                                                        'mobile' =>
                                                            $user['mobile'],

                                                        'avatar_id' =>
                                                            $user['avatar_id'] !== null
                                                                ? (int)$user['avatar_id']
                                                                : '',

                                                        'status' =>
                                                            (int)$user['status']
                                                    ],
                                                    JSON_HEX_TAG |
                                                    JSON_HEX_APOS |
                                                    JSON_HEX_AMP |
                                                    JSON_HEX_QUOT
                                                ); ?>
                                            )'
                                        >

                                            <i
                                                class="fa-solid fa-pen"
                                            ></i>

                                        </button>


                                        <!-- TOGGLE STATUS -->

                                        <form
                                            method="post"
                                            style="display:inline;"
                                            onsubmit="return confirm(
                                                'Change this user account status?'
                                            );"
                                        >

                                            <?= csrf_field(); ?>

                                            <input
                                                type="hidden"
                                                name="action"
                                                value="toggle_status"
                                            >

                                            <input
                                                type="hidden"
                                                name="id"
                                                value="<?= (int)$user['id']; ?>"
                                            >

                                            <button
                                                type="submit"
                                                class="action-btn"
                                                title="<?= (int)$user['status'] === 1
                                                    ? 'Deactivate User'
                                                    : 'Activate User'; ?>"
                                            >

                                                <i
                                                    class="fa-solid <?= (int)$user['status'] === 1
                                                        ? 'fa-user-slash'
                                                        : 'fa-user-check'; ?>"
                                                ></i>

                                            </button>

                                        </form>


                                        <!-- DELETE -->

                                        <button
                                            type="button"
                                            class="action-btn danger"
                                            title="Delete User"
                                            onclick='openDeleteModal(
                                                <?= (int)$user['id']; ?>,
                                                <?= json_encode(
                                                    $user['name'],
                                                    JSON_HEX_TAG |
                                                    JSON_HEX_APOS |
                                                    JSON_HEX_AMP |
                                                    JSON_HEX_QUOT
                                                ); ?>
                                            )'
                                        >

                                            <i
                                                class="fa-solid fa-trash"
                                            ></i>

                                        </button>


                                    </div>

                                </td>


                            </tr>


                        <?php endforeach; ?>


                        </tbody>

                    </table>


                <?php else: ?>


                    <div class="empty">

                        <div class="empty-icon">

                            <i
                                class="fa-solid fa-users"
                            ></i>

                        </div>


                        <h3>
                            No users found
                        </h3>


                        <p>
                            No users match your
                            current search or filters.
                        </p>

                    </div>


                <?php endif; ?>


            </div>

        </section>


    </main>

</div>


<!-- =====================================================
     USER MODAL
===================================================== -->

<div
    class="modal <?= $editUser
        ? 'show'
        : ''; ?>"
    id="userModal"
>


    <div class="modal-card">


        <div class="modal-head">

            <div>

                <h3 id="modalTitle">

                    <?= $editUser
                        ? 'Edit User'
                        : 'Create User'; ?>

                </h3>

                <p>
                    Manage user account information.
                </p>

            </div>


            <button
                type="button"
                class="close-btn"
                onclick="closeUserModal()"
            >

                <i
                    class="fa-solid fa-xmark"
                ></i>

            </button>

        </div>


        <form
            method="post"
            id="userForm"
        >

            <?= csrf_field(); ?>


            <input
                type="hidden"
                name="action"
                value="save"
            >


            <input
                type="hidden"
                name="id"
                id="user_id"
                value="<?= $editUser
                    ? (int)$editUser['id']
                    : 0; ?>"
            >


            <div class="modal-body">


                <div class="form-grid">


                    <!-- NAME -->

                    <div class="field full">

                        <label>
                            Full Name
                            <span>*</span>
                        </label>

                        <input
                            type="text"
                            name="name"
                            id="user_name"
                            maxlength="150"
                            required
                            placeholder="Enter user's full name"
                            value="<?= $editUser
                                ? e(
                                    $editUser['name']
                                )
                                : ''; ?>"
                        >

                    </div>


                    <!-- USERNAME -->

                    <div class="field">

                        <label>
                            Username
                        </label>

                        <input
                            type="text"
                            name="username"
                            id="user_username"
                            maxlength="100"
                            placeholder="john.doe"
                            value="<?= $editUser
                                ? e(
                                    $editUser['username']
                                )
                                : ''; ?>"
                        >

                        <small>
                            Letters, numbers, dot,
                            underscore and hyphen.
                        </small>

                    </div>


                    <!-- EMAIL -->

                    <div class="field">

                        <label>
                            Email
                            <span>*</span>
                        </label>

                        <input
                            type="email"
                            name="email"
                            id="user_email"
                            maxlength="190"
                            required
                            placeholder="user@example.com"
                            value="<?= $editUser
                                ? e(
                                    $editUser['email']
                                )
                                : ''; ?>"
                        >

                    </div>


                    <!-- MOBILE -->

                    <div class="field">

                        <label>
                            Mobile
                        </label>

                        <input
                            type="text"
                            name="mobile"
                            id="user_mobile"
                            maxlength="30"
                            placeholder="+91 9876543210"
                            value="<?= $editUser
                                ? e(
                                    $editUser['mobile']
                                )
                                : ''; ?>"
                        >

                    </div>


                    <!-- ROLE -->

                    <div class="field">

                        <label>
                            Role
                        </label>

                        <select
                            name="role_id"
                            id="user_role"
                        >

                            <option value="">
                                No Role
                            </option>


                            <?php foreach (
                                $roles
                                as $role
                            ): ?>

                                <option
                                    value="<?= (int)$role['id']; ?>"
                                    <?= $editUser &&
                                    (string)$editUser['role_id'] ===
                                    (string)$role['id']
                                        ? 'selected'
                                        : ''; ?>
                                >

                                    <?= e(
                                        $role['name']
                                    ); ?>

                                </option>

                            <?php endforeach; ?>

                        </select>

                    </div>


                    <!-- PASSWORD -->

                    <div class="field">

                        <label>
                            Password
                            <span
                                id="passwordRequired"
                            >
                                *
                            </span>
                        </label>

                        <input
                            type="password"
                            name="password"
                            id="user_password"
                            minlength="6"
                            placeholder="Enter password"
                            <?= $editUser
                                ? ''
                                : 'required'; ?>
                        >

                        <small
                            id="passwordHelp"
                        >
                            <?= $editUser
                                ? 'Leave blank to keep current password.'
                                : 'Minimum 6 characters.'; ?>
                        </small>

                    </div>


                    <!-- AVATAR -->

                    <div class="field">

                        <label>
                            Avatar
                        </label>

                        <select
                            name="avatar_id"
                            id="user_avatar"
                        >

                            <option value="">
                                No Avatar
                            </option>


                            <?php foreach (
                                $mediaItems
                                as $media
                            ): ?>

                                <option
                                    value="<?= (int)$media['id']; ?>"
                                    <?= $editUser &&
                                    (string)$editUser['avatar_id'] ===
                                    (string)$media['id']
                                        ? 'selected'
                                        : ''; ?>
                                >

                                    #<?= (int)$media['id']; ?>

                                    ·

                                    <?= e(
                                        $media['title']
                                        ?: $media['file_name']
                                        ?: 'Media'
                                    ); ?>

                                </option>

                            <?php endforeach; ?>

                        </select>

                        <small>
                            Select an existing media item.
                        </small>

                    </div>


                    <!-- STATUS -->

                    <div class="field">

                        <label>
                            Account Status
                        </label>

                        <select
                            name="status"
                            id="user_status"
                        >

                            <option
                                value="1"
                                <?= !$editUser ||
                                (int)$editUser['status'] === 1
                                    ? 'selected'
                                    : ''; ?>
                            >
                                Active
                            </option>

                            <option
                                value="0"
                                <?= $editUser &&
                                (int)$editUser['status'] === 0
                                    ? 'selected'
                                    : ''; ?>
                            >
                                Inactive
                            </option>

                        </select>

                    </div>


                </div>

            </div>


            <div class="modal-footer">

                <button
                    type="button"
                    class="btn btn-light"
                    onclick="closeUserModal()"
                >

                    Cancel

                </button>


                <button
                    type="submit"
                    class="btn btn-primary"
                >

                    <i
                        class="fa-solid fa-floppy-disk"
                    ></i>

                    <span id="saveText">

                        <?= $editUser
                            ? 'Update User'
                            : 'Create User'; ?>

                    </span>

                </button>

            </div>


        </form>


    </div>

</div>


<!-- =====================================================
     DELETE MODAL
===================================================== -->

<div
    class="modal"
    id="deleteModal"
>


    <div
        class="modal-card delete-card"
    >


        <div class="delete-content">


            <div class="delete-icon">

                <i
                    class="fa-solid fa-trash"
                ></i>

            </div>


            <h3>
                Delete User?
            </h3>


            <p>

                You are about to permanently
                delete

                <strong
                    id="deleteUserName"
                ></strong>.

                This action cannot be undone.

            </p>


        </div>


        <form
            method="post"
        >

            <?= csrf_field(); ?>


            <input
                type="hidden"
                name="action"
                value="delete"
            >


            <input
                type="hidden"
                name="id"
                id="deleteUserId"
            >


            <div class="modal-footer">

                <button
                    type="button"
                    class="btn btn-light"
                    onclick="closeDeleteModal()"
                >

                    Cancel

                </button>


                <button
                    type="submit"
                    class="btn btn-danger"
                >

                    <i
                        class="fa-solid fa-trash"
                    ></i>

                    Delete User

                </button>

            </div>


        </form>


    </div>

</div>


<script>

/* =========================================================
   USER MODAL
========================================================= */

const userModal =
    document.getElementById(
        'userModal'
    );


function openUserModal()
{
    document.getElementById(
        'user_id'
    ).value = '0';


    document.getElementById(
        'user_name'
    ).value = '';


    document.getElementById(
        'user_username'
    ).value = '';


    document.getElementById(
        'user_email'
    ).value = '';


    document.getElementById(
        'user_mobile'
    ).value = '';


    document.getElementById(
        'user_role'
    ).value = '';


    document.getElementById(
        'user_avatar'
    ).value = '';


    document.getElementById(
        'user_password'
    ).value = '';


    document.getElementById(
        'user_status'
    ).value = '1';


    document.getElementById(
        'user_password'
    ).required = true;


    document.getElementById(
        'passwordRequired'
    ).style.display = 'inline';


    document.getElementById(
        'passwordHelp'
    ).textContent =
        'Minimum 6 characters.';


    document.getElementById(
        'modalTitle'
    ).textContent =
        'Create User';


    document.getElementById(
        'saveText'
    ).textContent =
        'Create User';


    userModal.classList.add(
        'show'
    );


    document.body.style.overflow =
        'hidden';


    setTimeout(
        function () {

            document.getElementById(
                'user_name'
            ).focus();

        },
        100
    );
}


/* =========================================================
   EDIT USER
========================================================= */

function editUser(user)
{
    document.getElementById(
        'user_id'
    ).value =
        user.id;


    document.getElementById(
        'user_name'
    ).value =
        user.name || '';


    document.getElementById(
        'user_username'
    ).value =
        user.username || '';


    document.getElementById(
        'user_email'
    ).value =
        user.email || '';


    document.getElementById(
        'user_mobile'
    ).value =
        user.mobile || '';


    document.getElementById(
        'user_role'
    ).value =
        user.role_id || '';


    document.getElementById(
        'user_avatar'
    ).value =
        user.avatar_id || '';


    document.getElementById(
        'user_password'
    ).value =
        '';


    document.getElementById(
        'user_password'
    ).required =
        false;


    document.getElementById(
        'passwordRequired'
    ).style.display =
        'none';


    document.getElementById(
        'passwordHelp'
    ).textContent =
        'Leave blank to keep current password.';


    document.getElementById(
        'user_status'
    ).value =
        String(
            user.status
        );


    document.getElementById(
        'modalTitle'
    ).textContent =
        'Edit User';


    document.getElementById(
        'saveText'
    ).textContent =
        'Update User';


    userModal.classList.add(
        'show'
    );


    document.body.style.overflow =
        'hidden';
}


/* =========================================================
   CLOSE USER MODAL
========================================================= */

function closeUserModal()
{
    userModal.classList.remove(
        'show'
    );

    document.body.style.overflow =
        '';


    if (
        window.location.search
            .indexOf('edit=') !== -1
    ) {

        window.history.replaceState(
            {},
            document.title,
            window.location.pathname
        );
    }
}


/* =========================================================
   DELETE MODAL
========================================================= */

const deleteModal =
    document.getElementById(
        'deleteModal'
    );


function openDeleteModal(
    id,
    name
)
{
    document.getElementById(
        'deleteUserId'
    ).value =
        id;


    document.getElementById(
        'deleteUserName'
    ).textContent =
        name;


    deleteModal.classList.add(
        'show'
    );


    document.body.style.overflow =
        'hidden';
}


function closeDeleteModal()
{
    deleteModal.classList.remove(
        'show'
    );

    document.body.style.overflow =
        '';
}


/* =========================================================
   OUTSIDE CLICK
========================================================= */

document
    .querySelectorAll('.modal')
    .forEach(
        function (modal) {

            modal.addEventListener(
                'click',
                function (event) {

                    if (
                        event.target ===
                        modal
                    ) {

                        modal.classList.remove(
                            'show'
                        );

                        document.body.style.overflow =
                            '';

                    }

                }
            );

        }
    );


/* =========================================================
   ESC KEY
========================================================= */

document.addEventListener(
    'keydown',
    function (event) {

        if (
            event.key === 'Escape'
        ) {

            document
                .querySelectorAll(
                    '.modal.show'
                )
                .forEach(
                    function (modal) {

                        modal.classList.remove(
                            'show'
                        );

                    }
                );


            document.body.style.overflow =
                '';
        }

    }
);

</script>


</body>
</html>