<?php
/**
 * Pure Chemical Admin
 * Site Setting Groups Management
 *
 * Table:
 * site_setting_groups
 *
 * Columns:
 * id
 * name
 * slug
 * sort_order
 * status
 */

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();
}

if (file_exists(__DIR__ . '/includes/csrf.php')) {
    require_once __DIR__ . '/includes/csrf.php';
}

/* ---------------------------------------------------------
   Helpers
--------------------------------------------------------- */

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('admin_csrf_token')) {
    function admin_csrf_token()
    {
        if (function_exists('csrf_token')) {
            return csrf_token();
        }

        if (empty($_SESSION['site_setting_groups_csrf'])) {
            $_SESSION['site_setting_groups_csrf'] = bin2hex(random_bytes(32));
        }

        return $_SESSION['site_setting_groups_csrf'];
    }
}

if (!function_exists('admin_csrf_field')) {
    function admin_csrf_field()
    {
        $token = admin_csrf_token();

        return '<input type="hidden" name="csrf_token" value="' . e($token) . '">';
    }
}

if (!function_exists('admin_verify_csrf')) {
    function admin_verify_csrf()
    {
        if (function_exists('csrf_verify')) {
            return csrf_verify();
        }

        $token = $_POST['csrf_token'] ?? '';

        if (
            empty($token) ||
            empty($_SESSION['site_setting_groups_csrf']) ||
            !hash_equals($_SESSION['site_setting_groups_csrf'], $token)
        ) {
            return false;
        }

        return true;
    }
}

function redirectWithMessage($type, $message)
{
    $_SESSION['site_setting_groups_flash'] = [
        'type' => $type,
        'message' => $message
    ];

    header('Location: site_setting_groups.php');
    exit;
}

function slugify($text)
{
    $text = trim((string)$text);

    if ($text === '') {
        return '';
    }

    $text = strtolower($text);

    $converted = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $text);

    if ($converted !== false) {
        $text = $converted;
    }

    $text = preg_replace('/[^a-z0-9]+/', '-', $text);
    $text = trim($text, '-');

    return $text;
}

/* ---------------------------------------------------------
   Flash Message
--------------------------------------------------------- */

$flash = $_SESSION['site_setting_groups_flash'] ?? null;
unset($_SESSION['site_setting_groups_flash']);

/* ---------------------------------------------------------
   Current Action
--------------------------------------------------------- */

$action = $_GET['action'] ?? '';
$editId = isset($_GET['edit']) ? (int)$_GET['edit'] : 0;

/* ---------------------------------------------------------
   POST Actions
--------------------------------------------------------- */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!admin_verify_csrf()) {
        redirectWithMessage(
            'error',
            'Security verification failed. Please refresh the page and try again.'
        );
    }

    $postAction = $_POST['form_action'] ?? '';

    /* -----------------------------------------------------
       SAVE GROUP
    ----------------------------------------------------- */

    if ($postAction === 'save') {

        $id = (int)($_POST['id'] ?? 0);

        $name = trim($_POST['name'] ?? '');
        $slug = trim($_POST['slug'] ?? '');
        $sortOrder = (int)($_POST['sort_order'] ?? 0);
        $status = isset($_POST['status']) ? 1 : 0;

        if ($name === '') {
            redirectWithMessage(
                'error',
                'Group name is required.'
            );
        }

        if (mb_strlen($name) > 150) {
            redirectWithMessage(
                'error',
                'Group name cannot exceed 150 characters.'
            );
        }

        /* Auto generate slug when empty */
        if ($slug === '') {
            $slug = slugify($name);
        } else {
            $slug = slugify($slug);
        }

        if ($slug === '') {
            redirectWithMessage(
                'error',
                'Please enter a valid slug.'
            );
        }

        if (mb_strlen($slug) > 180) {
            redirectWithMessage(
                'error',
                'Slug cannot exceed 180 characters.'
            );
        }

        /* Check duplicate name */
        if ($id > 0) {

            $stmt = $pdo->prepare("
                SELECT id
                FROM site_setting_groups
                WHERE name = :name
                  AND id != :id
                LIMIT 1
            ");

            $stmt->execute([
                ':name' => $name,
                ':id' => $id
            ]);

        } else {

            $stmt = $pdo->prepare("
                SELECT id
                FROM site_setting_groups
                WHERE name = :name
                LIMIT 1
            ");

            $stmt->execute([
                ':name' => $name
            ]);
        }

        if ($stmt->fetch()) {
            redirectWithMessage(
                'error',
                'A setting group with this name already exists.'
            );
        }

        /* Check duplicate slug */
        if ($id > 0) {

            $stmt = $pdo->prepare("
                SELECT id
                FROM site_setting_groups
                WHERE slug = :slug
                  AND id != :id
                LIMIT 1
            ");

            $stmt->execute([
                ':slug' => $slug,
                ':id' => $id
            ]);

        } else {

            $stmt = $pdo->prepare("
                SELECT id
                FROM site_setting_groups
                WHERE slug = :slug
                LIMIT 1
            ");

            $stmt->execute([
                ':slug' => $slug
            ]);
        }

        if ($stmt->fetch()) {
            redirectWithMessage(
                'error',
                'A setting group with this slug already exists.'
            );
        }

        /* Update */
        if ($id > 0) {

            $stmt = $pdo->prepare("
                UPDATE site_setting_groups
                SET
                    name = :name,
                    slug = :slug,
                    sort_order = :sort_order,
                    status = :status
                WHERE id = :id
                LIMIT 1
            ");

            $stmt->execute([
                ':name' => $name,
                ':slug' => $slug,
                ':sort_order' => $sortOrder,
                ':status' => $status,
                ':id' => $id
            ]);

            redirectWithMessage(
                'success',
                'Setting group updated successfully.'
            );
        }

        /* Insert */
        $stmt = $pdo->prepare("
            INSERT INTO site_setting_groups
            (
                name,
                slug,
                sort_order,
                status
            )
            VALUES
            (
                :name,
                :slug,
                :sort_order,
                :status
            )
        ");

        $stmt->execute([
            ':name' => $name,
            ':slug' => $slug,
            ':sort_order' => $sortOrder,
            ':status' => $status
        ]);

        redirectWithMessage(
            'success',
            'Setting group created successfully.'
        );
    }

    /* -----------------------------------------------------
       DELETE GROUP
    ----------------------------------------------------- */

    if ($postAction === 'delete') {

        $id = (int)($_POST['id'] ?? 0);

        if ($id <= 0) {
            redirectWithMessage(
                'error',
                'Invalid group selected.'
            );
        }

        /* Check if group is used by site_settings */
        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM site_settings
            WHERE group_id = :group_id
        ");

        $stmt->execute([
            ':group_id' => $id
        ]);

        $usedCount = (int)$stmt->fetchColumn();

        if ($usedCount > 0) {

            redirectWithMessage(
                'error',
                "This group is currently used by {$usedCount} site setting(s). Move those settings to another group before deleting this group."
            );
        }

        $stmt = $pdo->prepare("
            DELETE FROM site_setting_groups
            WHERE id = :id
            LIMIT 1
        ");

        $stmt->execute([
            ':id' => $id
        ]);

        if ($stmt->rowCount() > 0) {

            redirectWithMessage(
                'success',
                'Setting group deleted successfully.'
            );
        }

        redirectWithMessage(
            'error',
            'Setting group could not be deleted.'
        );
    }

    /* -----------------------------------------------------
       QUICK STATUS TOGGLE
    ----------------------------------------------------- */

    if ($postAction === 'toggle_status') {

        $id = (int)($_POST['id'] ?? 0);

        if ($id <= 0) {
            redirectWithMessage(
                'error',
                'Invalid group selected.'
            );
        }

        $stmt = $pdo->prepare("
            UPDATE site_setting_groups
            SET status = IF(status = 1, 0, 1)
            WHERE id = :id
            LIMIT 1
        ");

        $stmt->execute([
            ':id' => $id
        ]);

        redirectWithMessage(
            'success',
            'Group status updated.'
        );
    }
}

/* ---------------------------------------------------------
   Search
--------------------------------------------------------- */

$search = trim($_GET['search'] ?? '');

$where = [];
$params = [];

if ($search !== '') {

    $where[] = "
        (
            g.name LIKE :search
            OR g.slug LIKE :search
        )
    ";

    $params[':search'] = '%' . $search . '%';
}

$whereSql = '';

if (!empty($where)) {
    $whereSql = 'WHERE ' . implode(' AND ', $where);
}

/* ---------------------------------------------------------
   Statistics
--------------------------------------------------------- */

$totalGroups = (int)$pdo
    ->query("SELECT COUNT(*) FROM site_setting_groups")
    ->fetchColumn();

$activeGroups = (int)$pdo
    ->query("
        SELECT COUNT(*)
        FROM site_setting_groups
        WHERE status = 1
    ")
    ->fetchColumn();

$inactiveGroups = $totalGroups - $activeGroups;

$usedGroups = (int)$pdo
    ->query("
        SELECT COUNT(DISTINCT group_id)
        FROM site_settings
        WHERE group_id IS NOT NULL
    ")
    ->fetchColumn();

/* ---------------------------------------------------------
   Group List
--------------------------------------------------------- */

$sql = "
    SELECT
        g.id,
        g.name,
        g.slug,
        g.sort_order,
        g.status,
        COUNT(s.id) AS settings_count
    FROM site_setting_groups g
    LEFT JOIN site_settings s
        ON s.group_id = g.id
    {$whereSql}
    GROUP BY
        g.id,
        g.name,
        g.slug,
        g.sort_order,
        g.status
    ORDER BY
        g.sort_order ASC,
        g.name ASC,
        g.id DESC
";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$groups = $stmt->fetchAll();

/* ---------------------------------------------------------
   Edit Record
--------------------------------------------------------- */

$editGroup = null;

if ($editId > 0) {

    $stmt = $pdo->prepare("
        SELECT
            id,
            name,
            slug,
            sort_order,
            status
        FROM site_setting_groups
        WHERE id = :id
        LIMIT 1
    ");

    $stmt->execute([
        ':id' => $editId
    ]);

    $editGroup = $stmt->fetch();

    if (!$editGroup) {
        redirectWithMessage(
            'error',
            'Requested setting group was not found.'
        );
    }
}

/* ---------------------------------------------------------
   Page Mode
--------------------------------------------------------- */

$isEdit = !empty($editGroup);

$formName = $editGroup['name'] ?? '';
$formSlug = $editGroup['slug'] ?? '';
$formSortOrder = $editGroup['sort_order'] ?? 0;
$formStatus = isset($editGroup['status'])
    ? (int)$editGroup['status']
    : 1;

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>
        Site Setting Groups | Pure Chemical Admin
    </title>

    <meta
        name="theme-color"
        content="#0f766e"
    >

    <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 {
            --pc-primary: #0f766e;
            --pc-primary-dark: #0b5f59;
            --pc-primary-soft: #e7f6f3;

            --pc-bg: #f5f7fb;
            --pc-card: #ffffff;

            --pc-text: #172033;
            --pc-muted: #6b7280;
            --pc-border: #e5e7eb;

            --pc-success: #15803d;
            --pc-success-bg: #ecfdf3;

            --pc-danger: #dc2626;
            --pc-danger-bg: #fef2f2;

            --pc-warning: #d97706;
            --pc-warning-bg: #fff7ed;

            --sidebar-width: 280px;

            --shadow-sm:
                0 1px 2px rgba(15, 23, 42, .04);

            --shadow-md:
                0 10px 30px rgba(15, 23, 42, .07);

            --shadow-lg:
                0 20px 60px rgba(15, 23, 42, .13);

            --radius-lg: 18px;
            --radius-md: 12px;
        }

        * {
            box-sizing: border-box;
        }

        html {
            scroll-behavior: smooth;
        }

        body {
            margin: 0;
            padding: 0;
            background: var(--pc-bg);
            color: var(--pc-text);
            font-family: Inter, Arial, sans-serif;
            font-size: 14px;
        }

        button,
        input,
        select {
            font-family: inherit;
        }

        a {
            color: inherit;
            text-decoration: none;
        }

        /* --------------------------------------------------
           Main Layout
        -------------------------------------------------- */

        .pc-main {
            min-height: 100vh;
            margin-left: var(--sidebar-width);
        }

        .pc-page {
            width: 100%;
            max-width: 1700px;
            margin: 0 auto;
            padding: 28px;
        }

        /* --------------------------------------------------
           Topbar
        -------------------------------------------------- */

        .pc-topbar {
            position: sticky;
            top: 0;
            z-index: 100;

            min-height: 76px;

            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 20px;

            padding: 14px 28px;

            background: rgba(255, 255, 255, .88);
            border-bottom: 1px solid rgba(226, 232, 240, .85);

            backdrop-filter: blur(18px);
            -webkit-backdrop-filter: blur(18px);
        }

        .topbar-left {
            display: flex;
            align-items: center;
            gap: 14px;
            min-width: 0;
        }

        .topbar-icon {
            width: 44px;
            height: 44px;

            display: grid;
            place-items: center;

            flex: 0 0 auto;

            color: var(--pc-primary);
            background: var(--pc-primary-soft);

            border: 1px solid #ccece7;
            border-radius: 13px;

            font-size: 18px;
        }

        .topbar-eyebrow {
            margin-bottom: 3px;

            color: var(--pc-primary);
            font-size: 11px;
            font-weight: 800;

            text-transform: uppercase;
            letter-spacing: .11em;
        }

        .topbar-title {
            margin: 0;

            font-size: 20px;
            line-height: 1.2;
            font-weight: 800;

            color: var(--pc-text);
        }

        .topbar-subtitle {
            margin-top: 3px;

            color: var(--pc-muted);
            font-size: 12px;
        }

        .topbar-actions {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        /* --------------------------------------------------
           Buttons
        -------------------------------------------------- */

        .btn {
            min-height: 42px;

            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;

            padding: 0 15px;

            border-radius: 11px;

            border: 1px solid transparent;

            font-size: 13px;
            font-weight: 700;

            cursor: pointer;

            transition:
                transform .18s ease,
                box-shadow .18s ease,
                background .18s ease;
        }

        .btn:hover {
            transform: translateY(-1px);
        }

        .btn-primary {
            color: #fff;
            background:
                linear-gradient(
                    135deg,
                    var(--pc-primary),
                    var(--pc-primary-dark)
                );

            box-shadow:
                0 8px 18px rgba(15, 118, 110, .22);
        }

        .btn-primary:hover {
            box-shadow:
                0 12px 24px rgba(15, 118, 110, .28);
        }

        .btn-light {
            color: #374151;
            background: #fff;
            border-color: var(--pc-border);
        }

        .btn-light:hover {
            background: #f8fafc;
        }

        .btn-danger {
            color: var(--pc-danger);
            background: var(--pc-danger-bg);
            border-color: #fecaca;
        }

        .btn-icon {
            width: 38px;
            height: 38px;

            padding: 0;

            display: inline-grid;
            place-items: center;

            border-radius: 10px;
        }

        /* --------------------------------------------------
           Hero
        -------------------------------------------------- */

        .page-hero {
            position: relative;

            overflow: hidden;

            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            gap: 24px;

            margin-bottom: 22px;
            padding: 25px;

            background:
                radial-gradient(
                    circle at 90% 10%,
                    rgba(15, 118, 110, .13),
                    transparent 30%
                ),
                #fff;

            border: 1px solid var(--pc-border);
            border-radius: var(--radius-lg);

            box-shadow: var(--shadow-sm);
        }

        .hero-content {
            max-width: 760px;
        }

        .hero-kicker {
            display: inline-flex;
            align-items: center;
            gap: 7px;

            margin-bottom: 9px;

            color: var(--pc-primary);
            font-size: 11px;
            font-weight: 800;

            text-transform: uppercase;
            letter-spacing: .1em;
        }

        .hero-title {
            margin: 0;

            font-size: clamp(24px, 3vw, 32px);
            line-height: 1.15;
            font-weight: 800;

            letter-spacing: -.035em;
        }

        .hero-description {
            margin: 9px 0 0;

            color: var(--pc-muted);

            line-height: 1.7;
            max-width: 680px;
        }

        /* --------------------------------------------------
           Stats
        -------------------------------------------------- */

        .stats-grid {
            display: grid;

            grid-template-columns:
                repeat(4, minmax(0, 1fr));

            gap: 15px;

            margin-bottom: 22px;
        }

        .stat-card {
            display: flex;
            align-items: center;
            gap: 13px;

            min-width: 0;

            padding: 17px;

            background: #fff;

            border: 1px solid var(--pc-border);
            border-radius: 15px;

            box-shadow: var(--shadow-sm);
        }

        .stat-icon {
            width: 43px;
            height: 43px;

            flex: 0 0 auto;

            display: grid;
            place-items: center;

            color: var(--pc-primary);
            background: var(--pc-primary-soft);

            border-radius: 12px;
        }

        .stat-card:nth-child(2) .stat-icon {
            color: var(--pc-success);
            background: var(--pc-success-bg);
        }

        .stat-card:nth-child(3) .stat-icon {
            color: var(--pc-warning);
            background: var(--pc-warning-bg);
        }

        .stat-card:nth-child(4) .stat-icon {
            color: #4f46e5;
            background: #eef2ff;
        }

        .stat-label {
            margin-bottom: 4px;

            color: var(--pc-muted);
            font-size: 11px;
            font-weight: 700;

            text-transform: uppercase;
            letter-spacing: .06em;
        }

        .stat-value {
            font-size: 23px;
            line-height: 1;
            font-weight: 800;
        }

        /* --------------------------------------------------
           Toolbar
        -------------------------------------------------- */

        .content-card {
            background: #fff;

            border: 1px solid var(--pc-border);
            border-radius: var(--radius-lg);

            box-shadow: var(--shadow-sm);
        }

        .toolbar {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 15px;

            padding: 17px 18px;

            border-bottom: 1px solid var(--pc-border);
        }

        .search-form {
            display: flex;
            align-items: center;
            gap: 9px;

            flex: 1;
            max-width: 520px;
        }

        .search-box {
            position: relative;
            flex: 1;
        }

        .search-box i {
            position: absolute;
            left: 13px;
            top: 50%;

            transform: translateY(-50%);

            color: #9ca3af;
        }

        .form-control {
            width: 100%;
            min-height: 43px;

            padding: 0 13px;

            color: var(--pc-text);
            background: #fff;

            border: 1px solid #dbe1e8;
            border-radius: 11px;

            outline: none;

            transition:
                border-color .18s ease,
                box-shadow .18s ease;
        }

        .search-box .form-control {
            padding-left: 39px;
        }

        .form-control:focus {
            border-color: rgba(15, 118, 110, .65);

            box-shadow:
                0 0 0 4px rgba(15, 118, 110, .09);
        }

        /* --------------------------------------------------
           Table
        -------------------------------------------------- */

        .table-wrap {
            overflow-x: auto;
        }

        .groups-table {
            width: 100%;
            min-width: 900px;

            border-collapse: collapse;
        }

        .groups-table th {
            padding: 13px 18px;

            color: #64748b;

            background: #f8fafc;

            border-bottom: 1px solid var(--pc-border);

            font-size: 11px;
            font-weight: 800;

            text-align: left;
            text-transform: uppercase;
            letter-spacing: .07em;

            white-space: nowrap;
        }

        .groups-table td {
            padding: 16px 18px;

            border-bottom: 1px solid #edf0f3;

            vertical-align: middle;
        }

        .groups-table tbody tr {
            transition: background .15s ease;
        }

        .groups-table tbody tr:hover {
            background: #fbfdfd;
        }

        .group-main {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .group-avatar {
            width: 42px;
            height: 42px;

            flex: 0 0 auto;

            display: grid;
            place-items: center;

            color: var(--pc-primary);

            background:
                linear-gradient(
                    145deg,
                    #ecfdf9,
                    #e0f2f1
                );

            border: 1px solid #cdeae6;
            border-radius: 12px;

            font-size: 16px;
        }

        .group-name {
            font-weight: 800;
            color: var(--pc-text);
        }

        .group-id {
            margin-top: 3px;

            color: #9ca3af;
            font-size: 11px;
        }

        .slug-code {
            display: inline-block;

            max-width: 260px;

            padding: 6px 9px;

            color: #475569;
            background: #f8fafc;

            border: 1px solid #e2e8f0;
            border-radius: 8px;

            font-family: Consolas, Monaco, monospace;
            font-size: 12px;

            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .count-pill {
            display: inline-flex;
            align-items: center;
            justify-content: center;

            min-width: 34px;
            height: 30px;

            padding: 0 9px;

            color: #334155;
            background: #f1f5f9;

            border: 1px solid #e2e8f0;
            border-radius: 9px;

            font-size: 12px;
            font-weight: 800;
        }

        .order-number {
            color: #475569;
            font-weight: 700;
        }

        /* --------------------------------------------------
           Status
        -------------------------------------------------- */

        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;

            padding: 6px 9px;

            border-radius: 999px;

            font-size: 11px;
            font-weight: 800;
        }

        .status-badge::before {
            content: "";

            width: 6px;
            height: 6px;

            border-radius: 50%;
        }

        .status-active {
            color: var(--pc-success);
            background: var(--pc-success-bg);
        }

        .status-active::before {
            background: var(--pc-success);
        }

        .status-inactive {
            color: #64748b;
            background: #f1f5f9;
        }

        .status-inactive::before {
            background: #94a3b8;
        }

        /* --------------------------------------------------
           Row Actions
        -------------------------------------------------- */

        .row-actions {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            gap: 7px;
        }

        .action-btn {
            width: 36px;
            height: 36px;

            display: grid;
            place-items: center;

            color: #64748b;
            background: #fff;

            border: 1px solid #e2e8f0;
            border-radius: 9px;

            cursor: pointer;

            transition: all .17s ease;
        }

        .action-btn:hover {
            color: var(--pc-primary);
            border-color: #b9dfda;
            background: #f0fdfa;
        }

        .action-btn.danger:hover {
            color: var(--pc-danger);
            border-color: #fecaca;
            background: var(--pc-danger-bg);
        }

        .inline-form {
            display: inline;
            margin: 0;
        }

        /* --------------------------------------------------
           Empty State
        -------------------------------------------------- */

        .empty-state {
            padding: 65px 25px;

            text-align: center;
        }

        .empty-icon {
            width: 64px;
            height: 64px;

            margin: 0 auto 15px;

            display: grid;
            place-items: center;

            color: var(--pc-primary);
            background: var(--pc-primary-soft);

            border-radius: 18px;

            font-size: 25px;
        }

        .empty-title {
            margin: 0;

            font-size: 18px;
            font-weight: 800;
        }

        .empty-text {
            max-width: 480px;

            margin: 7px auto 18px;

            color: var(--pc-muted);
            line-height: 1.6;
        }

        /* --------------------------------------------------
           Pagination/Footer
        -------------------------------------------------- */

        .table-footer {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 15px;

            padding: 15px 18px;

            color: var(--pc-muted);

            font-size: 12px;
        }

        /* --------------------------------------------------
           Flash
        -------------------------------------------------- */

        .flash {
            position: fixed;

            top: 92px;
            right: 25px;

            z-index: 1000;

            width: min(420px, calc(100vw - 30px));

            display: flex;
            align-items: flex-start;
            gap: 11px;

            padding: 14px 15px;

            background: #fff;

            border: 1px solid var(--pc-border);
            border-radius: 13px;

            box-shadow: var(--shadow-lg);

            animation: flashIn .28s ease;
        }

        .flash.success {
            border-left: 4px solid var(--pc-success);
        }

        .flash.error {
            border-left: 4px solid var(--pc-danger);
        }

        .flash-icon {
            width: 31px;
            height: 31px;

            flex: 0 0 auto;

            display: grid;
            place-items: center;

            border-radius: 9px;
        }

        .flash.success .flash-icon {
            color: var(--pc-success);
            background: var(--pc-success-bg);
        }

        .flash.error .flash-icon {
            color: var(--pc-danger);
            background: var(--pc-danger-bg);
        }

        .flash-message {
            flex: 1;

            color: #334155;
            font-size: 13px;
            line-height: 1.55;
        }

        .flash-close {
            padding: 4px;

            color: #94a3b8;

            background: transparent;
            border: 0;

            cursor: pointer;
        }

        @keyframes flashIn {
            from {
                opacity: 0;
                transform: translateY(-8px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* --------------------------------------------------
           Modal
        -------------------------------------------------- */

        .modal-backdrop {
            position: fixed;
            inset: 0;

            z-index: 900;

            display: none;
            align-items: center;
            justify-content: center;

            padding: 20px;

            background: rgba(15, 23, 42, .55);

            backdrop-filter: blur(6px);
            -webkit-backdrop-filter: blur(6px);
        }

        .modal-backdrop.active {
            display: flex;
        }

        .modal {
            width: min(560px, 100%);

            max-height: calc(100vh - 40px);
            overflow-y: auto;

            background: #fff;

            border: 1px solid rgba(255,255,255,.5);
            border-radius: 20px;

            box-shadow: var(--shadow-lg);

            animation: modalIn .2s ease;
        }

        @keyframes modalIn {
            from {
                opacity: 0;
                transform: translateY(12px) scale(.98);
            }

            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }

        .modal-head {
            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            gap: 15px;

            padding: 20px 21px;

            border-bottom: 1px solid var(--pc-border);
        }

        .modal-title {
            margin: 0;

            font-size: 18px;
            font-weight: 800;
        }

        .modal-description {
            margin: 5px 0 0;

            color: var(--pc-muted);
            font-size: 12px;
            line-height: 1.5;
        }

        .modal-close {
            width: 34px;
            height: 34px;

            display: grid;
            place-items: center;

            color: #64748b;
            background: #f8fafc;

            border: 1px solid #e2e8f0;
            border-radius: 9px;

            cursor: pointer;
        }

        .modal-body {
            padding: 21px;
        }

        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 9px;

            padding: 15px 21px;

            border-top: 1px solid var(--pc-border);
            background: #fafafa;
        }

        /* --------------------------------------------------
           Form
        -------------------------------------------------- */

        .form-group {
            margin-bottom: 17px;
        }

        .form-group:last-child {
            margin-bottom: 0;
        }

        .form-label {
            display: block;

            margin-bottom: 7px;

            color: #334155;

            font-size: 12px;
            font-weight: 800;
        }

        .required {
            color: var(--pc-danger);
        }

        .form-help {
            margin-top: 6px;

            color: #94a3b8;

            font-size: 11px;
            line-height: 1.5;
        }

        .form-row {
            display: grid;

            grid-template-columns:
                minmax(0, 1fr)
                minmax(0, 1fr);

            gap: 13px;
        }

        .slug-row {
            display: flex;
            gap: 8px;
        }

        .slug-row .form-control {
            flex: 1;
        }

        .checkbox-wrap {
            display: flex;
            align-items: center;
            gap: 10px;

            min-height: 43px;

            padding: 0 12px;

            background: #f8fafc;

            border: 1px solid #e2e8f0;
            border-radius: 11px;
        }

        .checkbox-wrap input {
            width: 17px;
            height: 17px;

            accent-color: var(--pc-primary);
        }

        .checkbox-label {
            color: #475569;
            font-size: 13px;
            font-weight: 600;
        }

        /* --------------------------------------------------
           Delete Modal
        -------------------------------------------------- */

        .delete-modal {
            width: min(440px, 100%);
        }

        .delete-icon {
            width: 54px;
            height: 54px;

            margin: 0 auto 14px;

            display: grid;
            place-items: center;

            color: var(--pc-danger);
            background: var(--pc-danger-bg);

            border-radius: 16px;

            font-size: 21px;
        }

        .delete-content {
            padding: 28px 24px;

            text-align: center;
        }

        .delete-title {
            margin: 0;

            font-size: 19px;
            font-weight: 800;
        }

        .delete-text {
            margin: 8px auto 0;

            color: var(--pc-muted);

            line-height: 1.6;
        }

        /* --------------------------------------------------
           Responsive
        -------------------------------------------------- */

        @media (max-width: 1200px) {

            .stats-grid {
                grid-template-columns:
                    repeat(2, minmax(0, 1fr));
            }

        }

        @media (max-width: 1100px) {

            .pc-main {
                margin-left: 0;
            }

        }

        @media (max-width: 760px) {

            .pc-page {
                padding: 17px;
            }

            .pc-topbar {
                padding: 12px 17px;
            }

            .topbar-subtitle {
                display: none;
            }

            .topbar-actions .btn-light {
                display: none;
            }

            .page-hero {
                padding: 20px;
            }

            .stats-grid {
                grid-template-columns: 1fr 1fr;
                gap: 10px;
            }

            .stat-card {
                padding: 13px;
            }

            .stat-icon {
                width: 38px;
                height: 38px;
            }

            .stat-value {
                font-size: 19px;
            }

            .toolbar {
                align-items: stretch;
                flex-direction: column;
            }

            .search-form {
                max-width: none;
            }

            .form-row {
                grid-template-columns: 1fr;
            }

        }

        @media (max-width: 480px) {

            .topbar-title {
                font-size: 17px;
            }

            .topbar-icon {
                width: 38px;
                height: 38px;
            }

            .topbar-actions .btn-primary {
                width: 42px;
                padding: 0;
                font-size: 0;
            }

            .topbar-actions .btn-primary i {
                font-size: 14px;
            }

            .stats-grid {
                grid-template-columns: 1fr 1fr;
            }

            .stat-card {
                gap: 9px;
            }

            .stat-label {
                font-size: 9px;
            }

            .table-footer {
                align-items: flex-start;
                flex-direction: column;
            }

        }

    </style>
</head>

<body>

<?php
/*
|--------------------------------------------------------------------------
| IMPORTANT
|--------------------------------------------------------------------------
| Sidebar is intentionally included separately.
| No admin/header.php is included here.
|--------------------------------------------------------------------------
*/
require_once __DIR__ . '/sidebar.php';
?>

<main class="pc-main">

    <!-- =====================================================
         TOPBAR
    ====================================================== -->

    <header class="pc-topbar">

        <div class="topbar-left">

            <div class="topbar-icon">
                <i class="fa-solid fa-layer-group"></i>
            </div>

            <div>

                <div class="topbar-eyebrow">
                    Website Configuration
                </div>

                <h1 class="topbar-title">
                    Site Setting Groups
                </h1>

                <div class="topbar-subtitle">
                    Organize your website settings into manageable groups.
                </div>

            </div>

        </div>

        <div class="topbar-actions">

            <a
                href="site_setting_groups.php"
                class="btn btn-light"
            >
                <i class="fa-solid fa-rotate"></i>
                Refresh
            </a>

            <button
                type="button"
                class="btn btn-primary"
                onclick="openGroupModal()"
            >
                <i class="fa-solid fa-plus"></i>
                Add Group
            </button>

        </div>

    </header>


    <div class="pc-page">

        <!-- =================================================
             HERO
        ================================================== -->

        <section class="page-hero">

            <div class="hero-content">

                <div class="hero-kicker">
                    <i class="fa-solid fa-sliders"></i>
                    Configuration Structure
                </div>

                <h2 class="hero-title">
                    Manage Setting Groups
                </h2>

                <p class="hero-description">
                    Create clean and reusable groups for your website
                    configuration such as General, Contact, SEO,
                    Social Media, Header, Footer and other sections.
                </p>

            </div>

        </section>


        <!-- =================================================
             STATS
        ================================================== -->

        <section class="stats-grid">

            <div class="stat-card">

                <div class="stat-icon">
                    <i class="fa-solid fa-layer-group"></i>
                </div>

                <div>

                    <div class="stat-label">
                        Total Groups
                    </div>

                    <div class="stat-value">
                        <?= number_format($totalGroups) ?>
                    </div>

                </div>

            </div>


            <div class="stat-card">

                <div class="stat-icon">
                    <i class="fa-solid fa-circle-check"></i>
                </div>

                <div>

                    <div class="stat-label">
                        Active
                    </div>

                    <div class="stat-value">
                        <?= number_format($activeGroups) ?>
                    </div>

                </div>

            </div>


            <div class="stat-card">

                <div class="stat-icon">
                    <i class="fa-solid fa-circle-pause"></i>
                </div>

                <div>

                    <div class="stat-label">
                        Inactive
                    </div>

                    <div class="stat-value">
                        <?= number_format($inactiveGroups) ?>
                    </div>

                </div>

            </div>


            <div class="stat-card">

                <div class="stat-icon">
                    <i class="fa-solid fa-link"></i>
                </div>

                <div>

                    <div class="stat-label">
                        Groups In Use
                    </div>

                    <div class="stat-value">
                        <?= number_format($usedGroups) ?>
                    </div>

                </div>

            </div>

        </section>


        <!-- =================================================
             MAIN CARD
        ================================================== -->

        <section class="content-card">

            <div class="toolbar">

                <form
                    method="get"
                    action="site_setting_groups.php"
                    class="search-form"
                >

                    <div class="search-box">

                        <i class="fa-solid fa-magnifying-glass"></i>

                        <input
                            type="search"
                            name="search"
                            class="form-control"
                            value="<?= e($search) ?>"
                            placeholder="Search group name or slug..."
                        >

                    </div>

                    <button
                        type="submit"
                        class="btn btn-light"
                    >
                        Search
                    </button>

                    <?php if ($search !== ''): ?>

                        <a
                            href="site_setting_groups.php"
                            class="btn btn-light"
                            title="Clear search"
                        >
                            <i class="fa-solid fa-xmark"></i>
                        </a>

                    <?php endif; ?>

                </form>


                <button
                    type="button"
                    class="btn btn-primary"
                    onclick="openGroupModal()"
                >
                    <i class="fa-solid fa-plus"></i>
                    New Group
                </button>

            </div>


            <?php if (!empty($groups)): ?>

                <div class="table-wrap">

                    <table class="groups-table">

                        <thead>

                            <tr>

                                <th>
                                    Group
                                </th>

                                <th>
                                    Slug
                                </th>

                                <th>
                                    Settings
                                </th>

                                <th>
                                    Order
                                </th>

                                <th>
                                    Status
                                </th>

                                <th style="text-align:right;">
                                    Actions
                                </th>

                            </tr>

                        </thead>

                        <tbody>

                        <?php foreach ($groups as $group): ?>

                            <tr>

                                <td>

                                    <div class="group-main">

                                        <div class="group-avatar">
                                            <i class="fa-solid fa-layer-group"></i>
                                        </div>

                                        <div>

                                            <div class="group-name">
                                                <?= e($group['name']) ?>
                                            </div>

                                            <div class="group-id">
                                                ID #<?= (int)$group['id'] ?>
                                            </div>

                                        </div>

                                    </div>

                                </td>


                                <td>

                                    <span class="slug-code">
                                        <?= e($group['slug']) ?>
                                    </span>

                                </td>


                                <td>

                                    <span class="count-pill">
                                        <?= number_format((int)$group['settings_count']) ?>
                                    </span>

                                </td>


                                <td>

                                    <span class="order-number">
                                        <?= (int)$group['sort_order'] ?>
                                    </span>

                                </td>


                                <td>

                                    <?php if ((int)$group['status'] === 1): ?>

                                        <span class="status-badge status-active">
                                            Active
                                        </span>

                                    <?php else: ?>

                                        <span class="status-badge status-inactive">
                                            Inactive
                                        </span>

                                    <?php endif; ?>

                                </td>


                                <td>

                                    <div class="row-actions">

                                        <!-- Edit -->

                                        <a
                                            href="site_setting_groups.php?edit=<?= (int)$group['id'] ?>"
                                            class="action-btn"
                                            title="Edit group"
                                        >
                                            <i class="fa-solid fa-pen"></i>
                                        </a>


                                        <!-- Toggle Status -->

                                        <form
                                            method="post"
                                            class="inline-form"
                                        >

                                            <?= admin_csrf_field() ?>

                                            <input
                                                type="hidden"
                                                name="form_action"
                                                value="toggle_status"
                                            >

                                            <input
                                                type="hidden"
                                                name="id"
                                                value="<?= (int)$group['id'] ?>"
                                            >

                                            <button
                                                type="submit"
                                                class="action-btn"
                                                title="Toggle status"
                                            >

                                                <?php if ((int)$group['status'] === 1): ?>

                                                    <i class="fa-solid fa-toggle-on"></i>

                                                <?php else: ?>

                                                    <i class="fa-solid fa-toggle-off"></i>

                                                <?php endif; ?>

                                            </button>

                                        </form>


                                        <!-- Delete -->

                                        <button
                                            type="button"
                                            class="action-btn danger"
                                            title="Delete group"
                                            onclick="openDeleteModal(
                                                <?= (int)$group['id'] ?>,
                                                <?= htmlspecialchars(
                                                    json_encode($group['name']),
                                                    ENT_QUOTES,
                                                    'UTF-8'
                                                ) ?>
                                            )"
                                        >
                                            <i class="fa-solid fa-trash"></i>
                                        </button>

                                    </div>

                                </td>

                            </tr>

                        <?php endforeach; ?>

                        </tbody>

                    </table>

                </div>


                <div class="table-footer">

                    <div>
                        Showing
                        <strong><?= count($groups) ?></strong>
                        group<?= count($groups) !== 1 ? 's' : '' ?>
                        <?php if ($search !== ''): ?>
                            for
                            <strong>
                                "<?= e($search) ?>"
                            </strong>
                        <?php endif; ?>
                    </div>

                    <div>
                        Setting groups are managed from the
                        <strong>site_setting_groups</strong> table.
                    </div>

                </div>


            <?php else: ?>

                <div class="empty-state">

                    <div class="empty-icon">
                        <i class="fa-solid fa-layer-group"></i>
                    </div>

                    <h3 class="empty-title">
                        No Setting Groups Found
                    </h3>

                    <p class="empty-text">

                        <?php if ($search !== ''): ?>

                            No setting group matches
                            <strong>
                                "<?= e($search) ?>"
                            </strong>.
                            Try another search.

                        <?php else: ?>

                            There are currently no site setting groups.
                            Create your first group to organize website
                            configuration settings.

                        <?php endif; ?>

                    </p>

                    <?php if ($search !== ''): ?>

                        <a
                            href="site_setting_groups.php"
                            class="btn btn-light"
                        >
                            <i class="fa-solid fa-arrow-left"></i>
                            Clear Search
                        </a>

                    <?php else: ?>

                        <button
                            type="button"
                            class="btn btn-primary"
                            onclick="openGroupModal()"
                        >
                            <i class="fa-solid fa-plus"></i>
                            Create First Group
                        </button>

                    <?php endif; ?>

                </div>

            <?php endif; ?>

        </section>

    </div>

</main>


<!-- =========================================================
     ADD / EDIT MODAL
========================================================== -->

<div
    class="modal-backdrop <?= $isEdit ? 'active' : '' ?>"
    id="groupModal"
>

    <div
        class="modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="groupModalTitle"
    >

        <form
            method="post"
            action="site_setting_groups.php"
        >

            <?= admin_csrf_field() ?>

            <input
                type="hidden"
                name="form_action"
                value="save"
            >

            <input
                type="hidden"
                name="id"
                value="<?= $isEdit ? (int)$editGroup['id'] : 0 ?>"
            >


            <div class="modal-head">

                <div>

                    <h3
                        class="modal-title"
                        id="groupModalTitle"
                    >
                        <?= $isEdit
                            ? 'Edit Setting Group'
                            : 'Create Setting Group'
                        ?>
                    </h3>

                    <p class="modal-description">
                        <?= $isEdit
                            ? 'Update the selected setting group.'
                            : 'Create a new group for website settings.'
                        ?>
                    </p>

                </div>

                <button
                    type="button"
                    class="modal-close"
                    onclick="closeGroupModal()"
                    aria-label="Close"
                >
                    <i class="fa-solid fa-xmark"></i>
                </button>

            </div>


            <div class="modal-body">

                <!-- Name -->

                <div class="form-group">

                    <label class="form-label">
                        Group Name
                        <span class="required">*</span>
                    </label>

                    <input
                        type="text"
                        name="name"
                        id="groupName"
                        class="form-control"
                        maxlength="150"
                        value="<?= e($formName) ?>"
                        placeholder="e.g. General Settings"
                        required
                    >

                    <div class="form-help">
                        A clear human-readable name for this setting group.
                    </div>

                </div>


                <!-- Slug -->

                <div class="form-group">

                    <label class="form-label">
                        Slug
                        <span class="required">*</span>
                    </label>

                    <div class="slug-row">

                        <input
                            type="text"
                            name="slug"
                            id="groupSlug"
                            class="form-control"
                            maxlength="180"
                            value="<?= e($formSlug) ?>"
                            placeholder="general-settings"
                            required
                        >

                        <button
                            type="button"
                            class="btn btn-light"
                            onclick="generateSlug()"
                            title="Generate slug"
                        >
                            <i class="fa-solid fa-wand-magic-sparkles"></i>
                        </button>

                    </div>

                    <div class="form-help">
                        Slug is automatically generated from the group name
                        when left empty.
                    </div>

                </div>


                <!-- Order + Status -->

                <div class="form-row">

                    <div class="form-group">

                        <label class="form-label">
                            Sort Order
                        </label>

                        <input
                            type="number"
                            name="sort_order"
                            class="form-control"
                            min="0"
                            step="1"
                            value="<?= (int)$formSortOrder ?>"
                        >

                        <div class="form-help">
                            Lower numbers appear first.
                        </div>

                    </div>


                    <div class="form-group">

                        <label class="form-label">
                            Group Status
                        </label>

                        <label class="checkbox-wrap">

                            <input
                                type="checkbox"
                                name="status"
                                value="1"
                                <?= $formStatus === 1 ? 'checked' : '' ?>
                            >

                            <span class="checkbox-label">
                                Active group
                            </span>

                        </label>

                        <div class="form-help">
                            Inactive groups can remain stored without being
                            used publicly.
                        </div>

                    </div>

                </div>

            </div>


            <div class="modal-footer">

                <button
                    type="button"
                    class="btn btn-light"
                    onclick="closeGroupModal()"
                >
                    Cancel
                </button>

                <button
                    type="submit"
                    class="btn btn-primary"
                >

                    <i class="fa-solid fa-check"></i>

                    <?= $isEdit
                        ? 'Update Group'
                        : 'Create Group'
                    ?>

                </button>

            </div>

        </form>

    </div>

</div>


<!-- =========================================================
     DELETE MODAL
========================================================== -->

<div
    class="modal-backdrop"
    id="deleteModal"
>

    <div class="modal delete-modal">

        <div class="delete-content">

            <div class="delete-icon">
                <i class="fa-solid fa-trash"></i>
            </div>

            <h3 class="delete-title">
                Delete Setting Group?
            </h3>

            <p class="delete-text">
                You are about to delete
                <strong id="deleteGroupName"></strong>.
                This action cannot be undone.
            </p>

        </div>


        <form
            method="post"
            action="site_setting_groups.php"
        >

            <?= admin_csrf_field() ?>

            <input
                type="hidden"
                name="form_action"
                value="delete"
            >

            <input
                type="hidden"
                name="id"
                id="deleteGroupId"
                value=""
            >

            <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 Group
                </button>

            </div>

        </form>

    </div>

</div>


<!-- =========================================================
     FLASH MESSAGE
========================================================== -->

<?php if ($flash): ?>

    <div
        class="flash <?= $flash['type'] === 'success' ? 'success' : 'error' ?>"
        id="flashMessage"
    >

        <div class="flash-icon">

            <?php if ($flash['type'] === 'success'): ?>

                <i class="fa-solid fa-check"></i>

            <?php else: ?>

                <i class="fa-solid fa-triangle-exclamation"></i>

            <?php endif; ?>

        </div>

        <div class="flash-message">
            <?= e($flash['message']) ?>
        </div>

        <button
            type="button"
            class="flash-close"
            onclick="closeFlash()"
        >
            <i class="fa-solid fa-xmark"></i>
        </button>

    </div>

<?php endif; ?>


<script>

    /* ========================================================
       Modal Helpers
    ======================================================== */

    const groupModal =
        document.getElementById('groupModal');

    const deleteModal =
        document.getElementById('deleteModal');


    function openGroupModal() {

        if (!groupModal) {
            return;
        }

        groupModal.classList.add('active');

        document.body.style.overflow = 'hidden';

        setTimeout(function () {

            const nameInput =
                document.getElementById('groupName');

            if (nameInput) {
                nameInput.focus();
            }

        }, 100);

    }


    function closeGroupModal() {

        if (!groupModal) {
            return;
        }

        groupModal.classList.remove('active');

        document.body.style.overflow = '';

        /*
         * If this is edit mode, return to normal listing.
         */
        <?php if ($isEdit): ?>

        setTimeout(function () {

            window.location.href =
                'site_setting_groups.php';

        }, 120);

        <?php endif; ?>

    }


    function openDeleteModal(id, name) {

        if (!deleteModal) {
            return;
        }

        document.getElementById('deleteGroupId').value = id;

        document.getElementById('deleteGroupName').textContent =
            name;

        deleteModal.classList.add('active');

        document.body.style.overflow = 'hidden';

    }


    function closeDeleteModal() {

        if (!deleteModal) {
            return;
        }

        deleteModal.classList.remove('active');

        document.body.style.overflow = '';

    }


    /* ========================================================
       Slug Generator
    ======================================================== */

    function makeSlug(value) {

        return value
            .toString()
            .toLowerCase()
            .trim()
            .normalize('NFD')
            .replace(/[\u0300-\u036f]/g, '')
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-+|-+$/g, '');

    }


    function generateSlug() {

        const nameInput =
            document.getElementById('groupName');

        const slugInput =
            document.getElementById('groupSlug');

        if (!nameInput || !slugInput) {
            return;
        }

        slugInput.value =
            makeSlug(nameInput.value);

    }


    /*
     * Automatically suggest slug only when the user
     * has not manually changed it.
     */

    const groupNameInput =
        document.getElementById('groupName');

    const groupSlugInput =
        document.getElementById('groupSlug');

    let slugManuallyChanged =
        <?= $isEdit && $formSlug !== '' ? 'true' : 'false' ?>;


    if (groupSlugInput) {

        groupSlugInput.addEventListener(
            'input',
            function () {

                slugManuallyChanged = true;

            }
        );

    }


    if (groupNameInput) {

        groupNameInput.addEventListener(
            'input',
            function () {

                if (!slugManuallyChanged) {

                    groupSlugInput.value =
                        makeSlug(groupNameInput.value);

                }

            }
        );

    }


    /* ========================================================
       ESC Key
    ======================================================== */

    document.addEventListener(
        'keydown',
        function (event) {

            if (event.key !== 'Escape') {
                return;
            }

            if (
                groupModal &&
                groupModal.classList.contains('active')
            ) {
                closeGroupModal();
            }

            if (
                deleteModal &&
                deleteModal.classList.contains('active')
            ) {
                closeDeleteModal();
            }

        }
    );


    /* ========================================================
       Click Outside Modal
    ======================================================== */

    if (groupModal) {

        groupModal.addEventListener(
            'click',
            function (event) {

                if (event.target === groupModal) {
                    closeGroupModal();
                }

            }
        );

    }


    if (deleteModal) {

        deleteModal.addEventListener(
            'click',
            function (event) {

                if (event.target === deleteModal) {
                    closeDeleteModal();
                }

            }
        );

    }


    /* ========================================================
       Flash Message
    ======================================================== */

    function closeFlash() {

        const flash =
            document.getElementById('flashMessage');

        if (flash) {

            flash.style.opacity = '0';

            flash.style.transform =
                'translateY(-8px)';

            setTimeout(function () {

                flash.remove();

            }, 200);

        }

    }


    /*
     * Automatically hide success messages.
     */

    <?php if ($flash && $flash['type'] === 'success'): ?>

    setTimeout(function () {

        closeFlash();

    }, 4500);

    <?php endif; ?>


    /* ========================================================
       Body Overflow Safety
    ======================================================== */

    window.addEventListener(
        'beforeunload',
        function () {

            document.body.style.overflow = '';

        }
    );

</script>

</body>
</html>