<?php
/**
 * Pure Chemical Admin
 * File: admin/settings.php
 *
 * Existing table:
 * settings
 *
 * Columns:
 * id
 * setting_key
 * setting_value
 * setting_group
 * updated_at
 */

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/includes/db.php';

if (file_exists(__DIR__ . '/includes/auth.php')) {
    require_once __DIR__ . '/includes/auth.php';
}

if (file_exists(__DIR__ . '/includes/functions.php')) {
    require_once __DIR__ . '/includes/functions.php';
}

if (file_exists(__DIR__ . '/includes/csrf.php')) {
    require_once __DIR__ . '/includes/csrf.php';
}

if (function_exists('requireAdmin')) {
    requireAdmin();
}

/* =========================================================
   HELPERS
========================================================= */

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

function settingsCsrfField()
{
    if (function_exists('csrf_field')) {
        return csrf_field();
    }

    if (empty($_SESSION['_csrf'])) {
        $_SESSION['_csrf'] = bin2hex(random_bytes(32));
    }

    return '<input type="hidden" name="_csrf" value="' .
        e($_SESSION['_csrf']) .
        '">';
}

function settingsVerifyCsrf()
{
    if (function_exists('csrf_verify')) {
        csrf_verify();
        return true;
    }

    $token = $_POST['_csrf'] ?? '';

    if (
        empty($_SESSION['_csrf']) ||
        empty($token) ||
        !hash_equals($_SESSION['_csrf'], $token)
    ) {
        throw new RuntimeException(
            'Invalid security token. Please refresh the page and try again.'
        );
    }

    return true;
}

function settingsFlash($type, $message)
{
    $_SESSION['settings_flash'] = [
        'type' => $type,
        'message' => $message
    ];
}

function settingsGetFlash()
{
    if (empty($_SESSION['settings_flash'])) {
        return null;
    }

    $flash = $_SESSION['settings_flash'];
    unset($_SESSION['settings_flash']);

    return $flash;
}

function settingsRedirect($url = 'settings.php')
{
    header('Location: ' . $url);
    exit;
}

function settingsNormalizeKey($key)
{
    $key = trim($key);

    /*
     * Allow:
     * letters
     * numbers
     * underscore
     * hyphen
     * dot
     */
    $key = preg_replace('/[^a-zA-Z0-9_.\-]/', '_', $key);

    return trim($key, '._-');
}

/* =========================================================
   DATABASE CHECK
========================================================= */

try {
    $tableCheck = $pdo->query("SHOW TABLES LIKE 'settings'")->fetchColumn();

    if (!$tableCheck) {
        throw new RuntimeException(
            'The settings table was not found in the selected database.'
        );
    }
} catch (Throwable $e) {
    http_response_code(500);
    exit(
        '<div style="font-family:Arial;padding:40px;color:#b91c1c;">
            <h2>Settings table error</h2>
            <p>' . e($e->getMessage()) . '</p>
        </div>'
    );
}

/* =========================================================
   ACTION HANDLER
========================================================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    try {

        settingsVerifyCsrf();

        $action = $_POST['action'] ?? '';

        /* =====================================================
           ADD / UPDATE
        ===================================================== */

        if ($action === 'save') {

            $id = (int)($_POST['id'] ?? 0);

            $settingKey = settingsNormalizeKey(
                $_POST['setting_key'] ?? ''
            );

            $settingValue = $_POST['setting_value'] ?? '';

            $settingGroup = trim(
                $_POST['setting_group'] ?? 'general'
            );

            if ($settingKey === '') {
                throw new RuntimeException(
                    'Setting key is required.'
                );
            }

            if ($settingGroup === '') {
                $settingGroup = 'general';
            }

            /*
             * Check duplicate setting_key
             */
            if ($id > 0) {

                $stmt = $pdo->prepare(
                    "SELECT id
                     FROM settings
                     WHERE setting_key = ?
                     AND id <> ?
                     LIMIT 1"
                );

                $stmt->execute([
                    $settingKey,
                    $id
                ]);

            } else {

                $stmt = $pdo->prepare(
                    "SELECT id
                     FROM settings
                     WHERE setting_key = ?
                     LIMIT 1"
                );

                $stmt->execute([
                    $settingKey
                ]);
            }

            if ($stmt->fetch()) {
                throw new RuntimeException(
                    'This setting key already exists.'
                );
            }

            /* =================================================
               UPDATE
            ================================================= */

            if ($id > 0) {

                $check = $pdo->prepare(
                    "SELECT id
                     FROM settings
                     WHERE id = ?
                     LIMIT 1"
                );

                $check->execute([$id]);

                if (!$check->fetch()) {
                    throw new RuntimeException(
                        'Setting not found.'
                    );
                }

                $stmt = $pdo->prepare(
                    "UPDATE settings
                     SET
                        setting_key = ?,
                        setting_value = ?,
                        setting_group = ?
                     WHERE id = ?"
                );

                $stmt->execute([
                    $settingKey,
                    $settingValue !== '' ? $settingValue : null,
                    $settingGroup,
                    $id
                ]);

                settingsFlash(
                    'success',
                    'Setting updated successfully.'
                );

            } else {

                /* =============================================
                   INSERT
                ============================================= */

                $stmt = $pdo->prepare(
                    "INSERT INTO settings
                    (
                        setting_key,
                        setting_value,
                        setting_group
                    )
                    VALUES
                    (
                        ?,
                        ?,
                        ?
                    )"
                );

                $stmt->execute([
                    $settingKey,
                    $settingValue !== '' ? $settingValue : null,
                    $settingGroup
                ]);

                settingsFlash(
                    'success',
                    'New setting added successfully.'
                );
            }

            settingsRedirect('settings.php');
        }

        /* =====================================================
           DELETE
        ===================================================== */

        if ($action === 'delete') {

            $id = (int)($_POST['id'] ?? 0);

            if ($id <= 0) {
                throw new RuntimeException(
                    'Invalid setting ID.'
                );
            }

            $stmt = $pdo->prepare(
                "SELECT id, setting_key
                 FROM settings
                 WHERE id = ?
                 LIMIT 1"
            );

            $stmt->execute([$id]);

            $setting = $stmt->fetch();

            if (!$setting) {
                throw new RuntimeException(
                    'Setting not found.'
                );
            }

            $stmt = $pdo->prepare(
                "DELETE FROM settings
                 WHERE id = ?"
            );

            $stmt->execute([$id]);

            settingsFlash(
                'success',
                'Setting "' .
                $setting['setting_key'] .
                '" deleted successfully.'
            );

            settingsRedirect('settings.php');
        }

    } catch (Throwable $e) {

        settingsFlash(
            'error',
            $e->getMessage()
        );

        settingsRedirect('settings.php');
    }
}

/* =========================================================
   FLASH
========================================================= */

$flash = settingsGetFlash();

/* =========================================================
   FILTERS
========================================================= */

$search = trim(
    $_GET['q'] ?? ''
);

$groupFilter = trim(
    $_GET['group'] ?? ''
);

$page = max(
    1,
    (int)($_GET['page'] ?? 1)
);

$perPage = 15;

$where = [];
$params = [];

/*
 * Search
 */
if ($search !== '') {

    $where[] = "(
        setting_key LIKE ?
        OR setting_value LIKE ?
        OR setting_group LIKE ?
    )";

    $searchLike = '%' . $search . '%';

    $params[] = $searchLike;
    $params[] = $searchLike;
    $params[] = $searchLike;
}

/*
 * Group
 */
if ($groupFilter !== '') {

    $where[] = "setting_group = ?";

    $params[] = $groupFilter;
}

$whereSql = '';

if (!empty($where)) {
    $whereSql = 'WHERE ' . implode(' AND ', $where);
}

/* =========================================================
   GROUPS
========================================================= */

$groups = [];

try {

    $groupsStmt = $pdo->query(
        "SELECT DISTINCT setting_group
         FROM settings
         WHERE setting_group IS NOT NULL
         AND setting_group <> ''
         ORDER BY setting_group ASC"
    );

    $groups = $groupsStmt->fetchAll(PDO::FETCH_COLUMN);

} catch (Throwable $e) {
    $groups = [];
}

/* =========================================================
   STATISTICS
========================================================= */

$totalSettings = 0;
$totalGroups = 0;

try {

    $stmt = $pdo->query(
        "SELECT COUNT(*) FROM settings"
    );

    $totalSettings = (int)$stmt->fetchColumn();

    $stmt = $pdo->query(
        "SELECT COUNT(DISTINCT setting_group)
         FROM settings
         WHERE setting_group IS NOT NULL
         AND setting_group <> ''"
    );

    $totalGroups = (int)$stmt->fetchColumn();

} catch (Throwable $e) {
    $totalSettings = 0;
    $totalGroups = 0;
}

/* =========================================================
   PAGINATION COUNT
========================================================= */

$countSql = "
    SELECT COUNT(*)
    FROM settings
    {$whereSql}
";

$countStmt = $pdo->prepare($countSql);
$countStmt->execute($params);

$totalFiltered = (int)$countStmt->fetchColumn();

$totalPages = max(
    1,
    (int)ceil($totalFiltered / $perPage)
);

if ($page > $totalPages) {
    $page = $totalPages;
}

$offset = ($page - 1) * $perPage;

/* =========================================================
   SETTINGS LIST
========================================================= */

$listSql = "
    SELECT
        id,
        setting_key,
        setting_value,
        setting_group,
        updated_at
    FROM settings
    {$whereSql}
    ORDER BY
        setting_group ASC,
        setting_key ASC
    LIMIT {$perPage}
    OFFSET {$offset}
";

$listStmt = $pdo->prepare($listSql);
$listStmt->execute($params);

$settings = $listStmt->fetchAll();

/* =========================================================
   EDIT RECORD
========================================================= */

$editSetting = null;

if (isset($_GET['edit'])) {

    $editId = (int)$_GET['edit'];

    if ($editId > 0) {

        $stmt = $pdo->prepare(
            "SELECT
                id,
                setting_key,
                setting_value,
                setting_group,
                updated_at
             FROM settings
             WHERE id = ?
             LIMIT 1"
        );

        $stmt->execute([
            $editId
        ]);

        $editSetting = $stmt->fetch();

        if (!$editSetting) {
            settingsFlash(
                'error',
                'Requested setting was not found.'
            );

            settingsRedirect('settings.php');
        }
    }
}

/* =========================================================
   MODAL STATE
========================================================= */

$openForm = isset($_GET['add']) || $editSetting !== null;

/* =========================================================
   PAGE URL HELPER
========================================================= */

function settingsQueryUrl($pageNumber)
{
    $params = [];

    if (!empty($_GET['q'])) {
        $params['q'] = $_GET['q'];
    }

    if (!empty($_GET['group'])) {
        $params['group'] = $_GET['group'];
    }

    $params['page'] = $pageNumber;

    return 'settings.php?' . http_build_query($params);
}

?>
<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>Settings | Pure Chemical Admin</title>

    <!-- Google Font -->
    <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"
    >

    <!-- Font Awesome -->
    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
    >

    <style>

        :root {
            --primary: #0f766e;
            --primary-dark: #115e59;
            --primary-soft: #ecfdf5;

            --dark: #0f172a;
            --dark-2: #1e293b;

            --text: #334155;
            --muted: #64748b;

            --border: #e2e8f0;
            --surface: #ffffff;
            --background: #f8fafc;

            --success: #059669;
            --danger: #dc2626;
            --warning: #d97706;

            --shadow:
                0 12px 35px rgba(15, 23, 42, 0.07);

            --shadow-lg:
                0 22px 60px rgba(15, 23, 42, 0.14);

            --radius: 18px;
        }

        * {
            box-sizing: border-box;
        }

        html {
            scroll-behavior: smooth;
        }

        body {
            margin: 0;
            background:
                radial-gradient(
                    circle at top right,
                    rgba(15, 118, 110, 0.06),
                    transparent 32%
                ),
                var(--background);

            color: var(--text);

            font-family:
                "Inter",
                -apple-system,
                BlinkMacSystemFont,
                "Segoe UI",
                sans-serif;

            font-size: 14px;
        }

        button,
        input,
        textarea,
        select {
            font: inherit;
        }

        button {
            cursor: pointer;
        }

        a {
            color: inherit;
            text-decoration: none;
        }

        /* =====================================================
           MAIN AREA
        ===================================================== */

        .settings-main {
            margin-left: 280px;
            min-height: 100vh;
        }

        /* =====================================================
           TOPBAR
        ===================================================== */

        .settings-topbar {
            position: sticky;
            top: 0;
            z-index: 100;

            height: 76px;

            display: flex;
            align-items: center;
            justify-content: space-between;

            padding: 0 32px;

            background: rgba(255, 255, 255, 0.90);

            border-bottom:
                1px solid rgba(226, 232, 240, 0.9);

            backdrop-filter: blur(18px);
            -webkit-backdrop-filter: blur(18px);
        }

        .topbar-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .topbar-icon {
            width: 44px;
            height: 44px;

            display: grid;
            place-items: center;

            border-radius: 13px;

            color: var(--primary);

            background:
                linear-gradient(
                    135deg,
                    #ecfdf5,
                    #dff7f1
                );

            border: 1px solid #ccefe6;

            font-size: 18px;
        }

        .topbar-title h1 {
            margin: 0;

            font-size: 19px;
            font-weight: 800;

            color: var(--dark);
            letter-spacing: -0.4px;
        }

        .topbar-title p {
            margin: 3px 0 0;

            color: var(--muted);
            font-size: 12px;
        }

        .topbar-right {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .admin-badge {
            display: flex;
            align-items: center;
            gap: 10px;

            padding: 8px 13px;

            border: 1px solid var(--border);
            border-radius: 12px;

            background: #fff;
        }

        .admin-avatar {
            width: 34px;
            height: 34px;

            display: grid;
            place-items: center;

            border-radius: 10px;

            color: #fff;

            background:
                linear-gradient(
                    135deg,
                    var(--primary),
                    #14b8a6
                );

            font-size: 13px;
        }

        .admin-info strong {
            display: block;

            color: var(--dark);

            font-size: 12px;
            font-weight: 700;
        }

        .admin-info span {
            display: block;

            margin-top: 2px;

            color: var(--muted);

            font-size: 10px;
        }

        /* =====================================================
           CONTENT
        ===================================================== */

        .settings-content {
            padding: 30px 32px 50px;
        }

        .page-heading {
            display: flex;
            align-items: flex-end;
            justify-content: space-between;

            gap: 20px;

            margin-bottom: 26px;
        }

        .page-heading h2 {
            margin: 0;

            color: var(--dark);

            font-size: 28px;
            line-height: 1.2;

            letter-spacing: -0.8px;
        }

        .page-heading p {
            margin: 8px 0 0;

            color: var(--muted);

            font-size: 13px;
        }

        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;

            min-height: 44px;

            padding: 0 16px;

            border: 0;
            border-radius: 12px;

            font-size: 13px;
            font-weight: 700;

            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(--primary),
                    #0d9488
                );

            box-shadow:
                0 9px 22px rgba(15, 118, 110, 0.20);
        }

        .btn-secondary {
            color: var(--dark);

            background: #fff;

            border: 1px solid var(--border);
        }

        .btn-danger {
            color: #fff;
            background: var(--danger);
        }

        .btn-small {
            min-height: 36px;
            padding: 0 11px;

            border-radius: 9px;

            font-size: 12px;
        }

        /* =====================================================
           FLASH
        ===================================================== */

        .flash {
            display: flex;
            align-items: center;
            gap: 11px;

            margin-bottom: 22px;

            padding: 14px 16px;

            border-radius: 14px;

            font-size: 13px;
            font-weight: 600;
        }

        .flash-success {
            color: #065f46;

            background: #ecfdf5;

            border: 1px solid #a7f3d0;
        }

        .flash-error {
            color: #991b1b;

            background: #fef2f2;

            border: 1px solid #fecaca;
        }

        /* =====================================================
           STATS
        ===================================================== */

        .stats-grid {
            display: grid;

            grid-template-columns:
                repeat(3, minmax(0, 1fr));

            gap: 17px;

            margin-bottom: 24px;
        }

        .stat-card {
            position: relative;

            overflow: hidden;

            padding: 20px;

            background: var(--surface);

            border: 1px solid var(--border);

            border-radius: var(--radius);

            box-shadow: var(--shadow);
        }

        .stat-card::after {
            content: "";

            position: absolute;

            width: 90px;
            height: 90px;

            right: -25px;
            bottom: -30px;

            border-radius: 50%;

            background: var(--primary-soft);
        }

        .stat-icon {
            width: 42px;
            height: 42px;

            display: grid;
            place-items: center;

            margin-bottom: 15px;

            border-radius: 12px;

            color: var(--primary);

            background: var(--primary-soft);

            font-size: 17px;
        }

        .stat-card strong {
            display: block;

            color: var(--dark);

            font-size: 25px;
            font-weight: 800;

            letter-spacing: -0.6px;
        }

        .stat-card span {
            display: block;

            margin-top: 5px;

            color: var(--muted);

            font-size: 12px;
        }

        /* =====================================================
           TOOLBAR
        ===================================================== */

        .toolbar-card {
            margin-bottom: 18px;

            padding: 18px;

            background: #fff;

            border: 1px solid var(--border);

            border-radius: var(--radius);

            box-shadow: var(--shadow);
        }

        .filter-form {
            display: grid;

            grid-template-columns:
                minmax(220px, 1.8fr)
                minmax(170px, 1fr)
                auto auto;

            gap: 11px;
        }

        .input-wrap {
            position: relative;
        }

        .input-wrap > i {
            position: absolute;

            left: 14px;
            top: 50%;

            transform: translateY(-50%);

            color: #94a3b8;

            pointer-events: none;
        }

        .form-control {
            width: 100%;

            height: 45px;

            padding: 0 13px;

            color: var(--dark);

            background: #fff;

            border: 1px solid #dbe3ec;

            border-radius: 11px;

            outline: none;

            transition:
                border-color .18s ease,
                box-shadow .18s ease;
        }

        .input-wrap .form-control {
            padding-left: 40px;
        }

        textarea.form-control {
            height: auto;

            min-height: 130px;

            padding: 13px;

            resize: vertical;
        }

        .form-control:focus {
            border-color: #5eead4;

            box-shadow:
                0 0 0 4px rgba(20, 184, 166, 0.10);
        }

        select.form-control {
            cursor: pointer;
        }

        /* =====================================================
           TABLE
        ===================================================== */

        .table-card {
            overflow: hidden;

            background: #fff;

            border: 1px solid var(--border);

            border-radius: var(--radius);

            box-shadow: var(--shadow);
        }

        .table-header {
            display: flex;
            align-items: center;
            justify-content: space-between;

            padding: 18px 20px;

            border-bottom: 1px solid var(--border);
        }

        .table-header h3 {
            margin: 0;

            color: var(--dark);

            font-size: 14px;
            font-weight: 800;
        }

        .table-header span {
            color: var(--muted);

            font-size: 11px;
        }

        .table-scroll {
            overflow-x: auto;
        }

        .settings-table {
            width: 100%;

            min-width: 850px;

            border-collapse: collapse;
        }

        .settings-table th {
            padding: 13px 18px;

            text-align: left;

            color: #64748b;

            background: #f8fafc;

            border-bottom: 1px solid var(--border);

            font-size: 10px;
            font-weight: 800;

            text-transform: uppercase;

            letter-spacing: .6px;
        }

        .settings-table td {
            padding: 16px 18px;

            vertical-align: middle;

            border-bottom: 1px solid #edf1f5;

            color: var(--text);

            font-size: 12px;
        }

        .settings-table tr:last-child td {
            border-bottom: 0;
        }

        .settings-table tbody tr {
            transition: background .15s ease;
        }

        .settings-table tbody tr:hover {
            background: #fbfefd;
        }

        .key-cell {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .key-icon {
            flex: 0 0 auto;

            width: 34px;
            height: 34px;

            display: grid;
            place-items: center;

            color: var(--primary);

            background: var(--primary-soft);

            border-radius: 9px;
        }

        .key-content strong {
            display: block;

            color: var(--dark);

            font-size: 12px;

            font-family:
                "SFMono-Regular",
                Consolas,
                "Liberation Mono",
                monospace;

            word-break: break-word;
        }

        .key-content small {
            display: block;

            margin-top: 4px;

            color: #94a3b8;

            font-size: 10px;
        }

        .group-chip {
            display: inline-flex;
            align-items: center;

            padding: 6px 9px;

            color: #0f766e;

            background: #ecfdf5;

            border: 1px solid #ccfbf1;

            border-radius: 8px;

            font-size: 10px;
            font-weight: 700;

            text-transform: uppercase;

            letter-spacing: .3px;
        }

        .value-preview {
            max-width: 340px;

            color: #475569;

            line-height: 1.5;

            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .null-value {
            color: #94a3b8;

            font-style: italic;
        }

        .updated-date {
            color: #64748b;

            font-size: 11px;
        }

        .actions {
            display: flex;
            align-items: center;
            gap: 7px;
        }

        .icon-btn {
            width: 35px;
            height: 35px;

            display: grid;
            place-items: center;

            border-radius: 9px;

            border: 1px solid var(--border);

            background: #fff;

            color: #475569;

            transition:
                background .15s ease,
                color .15s ease,
                border-color .15s ease;
        }

        .icon-btn:hover {
            color: var(--primary);

            border-color: #99f6e4;

            background: #f0fdfa;
        }

        .icon-btn.delete:hover {
            color: var(--danger);

            border-color: #fecaca;

            background: #fef2f2;
        }

        /* =====================================================
           EMPTY
        ===================================================== */

        .empty-state {
            padding: 65px 25px;

            text-align: center;
        }

        .empty-icon {
            width: 64px;
            height: 64px;

            display: grid;
            place-items: center;

            margin: 0 auto 15px;

            border-radius: 18px;

            color: var(--primary);

            background: var(--primary-soft);

            font-size: 24px;
        }

        .empty-state h3 {
            margin: 0;

            color: var(--dark);

            font-size: 16px;
        }

        .empty-state p {
            max-width: 430px;

            margin: 8px auto 0;

            color: var(--muted);

            font-size: 12px;

            line-height: 1.6;
        }

        /* =====================================================
           PAGINATION
        ===================================================== */

        .pagination {
            display: flex;
            align-items: center;
            justify-content: space-between;

            gap: 15px;

            padding: 17px 20px;

            border-top: 1px solid var(--border);
        }

        .pagination-info {
            color: var(--muted);

            font-size: 11px;
        }

        .pagination-links {
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .page-link {
            min-width: 34px;
            height: 34px;

            display: grid;
            place-items: center;

            padding: 0 9px;

            border: 1px solid var(--border);

            border-radius: 8px;

            color: #475569;

            background: #fff;

            font-size: 11px;
            font-weight: 700;
        }

        .page-link:hover {
            color: var(--primary);

            background: #f0fdfa;

            border-color: #99f6e4;
        }

        .page-link.active {
            color: #fff;

            background: var(--primary);

            border-color: var(--primary);
        }

        .page-link.disabled {
            opacity: .45;

            pointer-events: none;
        }

        /* =====================================================
           MODAL
        ===================================================== */

        .modal-backdrop {
            position: fixed;

            inset: 0;

            z-index: 1000;

            display: none;

            align-items: center;
            justify-content: center;

            padding: 20px;

            background:
                rgba(15, 23, 42, 0.62);

            backdrop-filter: blur(6px);
        }

        .modal-backdrop.show {
            display: flex;
        }

        .modal {
            width: min(680px, 100%);

            max-height: calc(100vh - 40px);

            overflow-y: auto;

            background: #fff;

            border-radius: 22px;

            box-shadow: var(--shadow-lg);

            animation: modalIn .18s ease;
        }

        @keyframes modalIn {

            from {
                opacity: 0;
                transform: translateY(12px) scale(.98);
            }

            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }

        .modal-head {
            position: sticky;

            top: 0;

            z-index: 2;

            display: flex;
            align-items: center;
            justify-content: space-between;

            padding: 20px 22px;

            background: rgba(255,255,255,.95);

            border-bottom: 1px solid var(--border);

            backdrop-filter: blur(12px);
        }

        .modal-title {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .modal-title-icon {
            width: 40px;
            height: 40px;

            display: grid;
            place-items: center;

            border-radius: 11px;

            color: var(--primary);

            background: var(--primary-soft);
        }

        .modal-title h3 {
            margin: 0;

            color: var(--dark);

            font-size: 16px;
            font-weight: 800;
        }

        .modal-title p {
            margin: 3px 0 0;

            color: var(--muted);

            font-size: 11px;
        }

        .modal-close {
            width: 36px;
            height: 36px;

            display: grid;
            place-items: center;

            border: 1px solid var(--border);

            border-radius: 10px;

            background: #fff;

            color: #64748b;
        }

        .modal-close:hover {
            color: var(--danger);

            background: #fef2f2;
        }

        .modal-body {
            padding: 22px;
        }

        .form-grid {
            display: grid;

            grid-template-columns:
                repeat(2, minmax(0, 1fr));

            gap: 17px;
        }

        .form-group {
            display: flex;
            flex-direction: column;

            gap: 7px;
        }

        .form-group.full {
            grid-column: 1 / -1;
        }

        .form-label {
            color: #334155;

            font-size: 11px;
            font-weight: 800;
        }

        .required {
            color: var(--danger);
        }

        .help-text {
            color: #94a3b8;

            font-size: 10px;
            line-height: 1.5;
        }

        .modal-footer {
            display: flex;
            align-items: center;
            justify-content: flex-end;

            gap: 9px;

            padding: 17px 22px;

            border-top: 1px solid var(--border);

            background: #f8fafc;
        }

        /* =====================================================
           DELETE MODAL
        ===================================================== */

        .delete-modal {
            width: min(430px, 100%);
        }

        .delete-body {
            padding: 28px;

            text-align: center;
        }

        .delete-icon {
            width: 62px;
            height: 62px;

            display: grid;
            place-items: center;

            margin: 0 auto 17px;

            color: var(--danger);

            background: #fef2f2;

            border: 1px solid #fecaca;

            border-radius: 18px;

            font-size: 22px;
        }

        .delete-body h3 {
            margin: 0;

            color: var(--dark);

            font-size: 17px;
        }

        .delete-body p {
            margin: 9px 0 0;

            color: var(--muted);

            font-size: 12px;

            line-height: 1.6;
        }

        .delete-key {
            display: inline-block;

            max-width: 100%;

            margin-top: 13px;

            padding: 8px 10px;

            color: #991b1b;

            background: #fef2f2;

            border: 1px solid #fecaca;

            border-radius: 8px;

            font-family: monospace;

            font-size: 11px;

            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        /* =====================================================
           RESPONSIVE
        ===================================================== */

        @media (max-width: 1100px) {

            .settings-main {
                margin-left: 0;
            }

            .stats-grid {
                grid-template-columns:
                    repeat(2, minmax(0, 1fr));
            }

            .filter-form {
                grid-template-columns:
                    1fr 1fr;
            }
        }

        @media (max-width: 700px) {

            .settings-topbar {
                height: 68px;

                padding: 0 16px;
            }

            .topbar-title h1 {
                font-size: 16px;
            }

            .topbar-title p {
                display: none;
            }

            .admin-info {
                display: none;
            }

            .settings-content {
                padding: 22px 15px 40px;
            }

            .page-heading {
                align-items: flex-start;

                flex-direction: column;
            }

            .page-heading h2 {
                font-size: 24px;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }

            .filter-form {
                grid-template-columns: 1fr;
            }

            .form-grid {
                grid-template-columns: 1fr;
            }

            .form-group.full {
                grid-column: auto;
            }

            .pagination {
                align-items: flex-start;

                flex-direction: column;
            }

            .pagination-links {
                width: 100%;

                overflow-x: auto;
            }
        }

    </style>

</head>

<body>

<?php
/*
|--------------------------------------------------------------------------
| EXISTING ADMIN SIDEBAR
|--------------------------------------------------------------------------
|
| Sidebar deliberately included separately as requested.
|
*/
require_once __DIR__ . '/sidebar.php';
?>

<div class="settings-main">

    <!-- =====================================================
         TOPBAR
    ====================================================== -->

    <header class="settings-topbar">

        <div class="topbar-left">

            <div class="topbar-icon">
                <i class="fa-solid fa-sliders"></i>
            </div>

            <div class="topbar-title">

                <h1>
                    Settings
                </h1>

                <p>
                    Manage website configuration and system values
                </p>

            </div>

        </div>

        <div class="topbar-right">

            <div class="admin-badge">

                <div class="admin-avatar">
                    <i class="fa-solid fa-user-shield"></i>
                </div>

                <div class="admin-info">

                    <strong>
                        <?= e($_SESSION['ADMIN_NAME'] ?? 'Administrator'); ?>
                    </strong>

                    <span>
                        Administrator
                    </span>

                </div>

            </div>

        </div>

    </header>


    <!-- =====================================================
         CONTENT
    ====================================================== -->

    <main class="settings-content">

        <!-- PAGE HEADING -->

        <div class="page-heading">

            <div>

                <h2>
                    Website Settings
                </h2>

                <p>
                    Centralized configuration for your Pure Chemical website.
                </p>

            </div>

            <button
                type="button"
                class="btn btn-primary"
                onclick="openSettingModal()"
            >
                <i class="fa-solid fa-plus"></i>

                Add Setting
            </button>

        </div>


        <!-- FLASH -->

        <?php if ($flash): ?>

            <div
                class="flash
                <?= $flash['type'] === 'success'
                    ? 'flash-success'
                    : 'flash-error'; ?>"
            >

                <i class="fa-solid
                    <?= $flash['type'] === 'success'
                        ? 'fa-circle-check'
                        : 'fa-circle-exclamation'; ?>">
                </i>

                <span>
                    <?= e($flash['message']); ?>
                </span>

            </div>

        <?php endif; ?>


        <!-- =================================================
             STATS
        ================================================== -->

        <section class="stats-grid">

            <div class="stat-card">

                <div class="stat-icon">
                    <i class="fa-solid fa-sliders"></i>
                </div>

                <strong>
                    <?= number_format($totalSettings); ?>
                </strong>

                <span>
                    Total Settings
                </span>

            </div>


            <div class="stat-card">

                <div class="stat-icon">
                    <i class="fa-solid fa-layer-group"></i>
                </div>

                <strong>
                    <?= number_format($totalGroups); ?>
                </strong>

                <span>
                    Setting Groups
                </span>

            </div>


            <div class="stat-card">

                <div class="stat-icon">
                    <i class="fa-solid fa-database"></i>
                </div>

                <strong>
                    <?= number_format($totalFiltered); ?>
                </strong>

                <span>
                    Matching Records
                </span>

            </div>

        </section>


        <!-- =================================================
             FILTER
        ================================================== -->

        <section class="toolbar-card">

            <form
                method="GET"
                action="settings.php"
                class="filter-form"
            >

                <div class="input-wrap">

                    <i class="fa-solid fa-magnifying-glass"></i>

                    <input
                        type="text"
                        name="q"
                        class="form-control"
                        placeholder="Search key, value or group..."
                        value="<?= e($search); ?>"
                    >

                </div>


                <select
                    name="group"
                    class="form-control"
                >

                    <option value="">
                        All Groups
                    </option>

                    <?php foreach ($groups as $group): ?>

                        <option
                            value="<?= e($group); ?>"
                            <?= $groupFilter === $group
                                ? 'selected'
                                : ''; ?>
                        >
                            <?= e($group); ?>
                        </option>

                    <?php endforeach; ?>

                </select>


                <button
                    type="submit"
                    class="btn btn-primary"
                >
                    <i class="fa-solid fa-filter"></i>

                    Filter
                </button>


                <?php if ($search !== '' || $groupFilter !== ''): ?>

                    <a
                        href="settings.php"
                        class="btn btn-secondary"
                    >
                        <i class="fa-solid fa-rotate-left"></i>

                        Reset
                    </a>

                <?php endif; ?>

            </form>

        </section>


        <!-- =================================================
             TABLE
        ================================================== -->

        <section class="table-card">

            <div class="table-header">

                <div>

                    <h3>
                        Configuration Settings
                    </h3>

                </div>

                <span>
                    <?= number_format($totalFiltered); ?>
                    record<?= $totalFiltered == 1 ? '' : 's'; ?>
                </span>

            </div>


            <?php if (empty($settings)): ?>

                <div class="empty-state">

                    <div class="empty-icon">
                        <i class="fa-solid fa-sliders"></i>
                    </div>

                    <h3>
                        No settings found
                    </h3>

                    <p>
                        No settings match your current search or filter.
                        Add your first configuration setting to get started.
                    </p>

                </div>

            <?php else: ?>

                <div class="table-scroll">

                    <table class="settings-table">

                        <thead>

                            <tr>

                                <th>
                                    Setting
                                </th>

                                <th>
                                    Group
                                </th>

                                <th>
                                    Value
                                </th>

                                <th>
                                    Updated
                                </th>

                                <th>
                                    Actions
                                </th>

                            </tr>

                        </thead>

                        <tbody>

                        <?php foreach ($settings as $setting): ?>

                            <?php
                                $rawValue = $setting['setting_value'];

                                $displayValue =
                                    $rawValue === null ||
                                    $rawValue === ''
                                        ? ''
                                        : trim((string)$rawValue);

                                if ($displayValue !== '') {
                                    $preview = preg_replace(
                                        '/\s+/',
                                        ' ',
                                        $displayValue
                                    );
                                } else {
                                    $preview = '';
                                }
                            ?>

                            <tr>

                                <!-- SETTING KEY -->

                                <td>

                                    <div class="key-cell">

                                        <div class="key-icon">

                                            <i class="fa-solid fa-key"></i>

                                        </div>

                                        <div class="key-content">

                                            <strong>
                                                <?= e($setting['setting_key']); ?>
                                            </strong>

                                            <small>
                                                ID #<?= (int)$setting['id']; ?>
                                            </small>

                                        </div>

                                    </div>

                                </td>


                                <!-- GROUP -->

                                <td>

                                    <span class="group-chip">

                                        <?= e(
                                            $setting['setting_group']
                                                ?: 'general'
                                        ); ?>

                                    </span>

                                </td>


                                <!-- VALUE -->

                                <td>

                                    <?php if ($preview === ''): ?>

                                        <span class="null-value">
                                            Empty / NULL
                                        </span>

                                    <?php else: ?>

                                        <div
                                            class="value-preview"
                                            title="<?= e($displayValue); ?>"
                                        >
                                            <?= e($preview); ?>
                                        </div>

                                    <?php endif; ?>

                                </td>


                                <!-- UPDATED -->

                                <td>

                                    <div class="updated-date">

                                        <?php
                                        if (!empty($setting['updated_at'])) {
                                            echo e(
                                                date(
                                                    'd M Y, h:i A',
                                                    strtotime(
                                                        $setting['updated_at']
                                                    )
                                                )
                                            );
                                        } else {
                                            echo '—';
                                        }
                                        ?>

                                    </div>

                                </td>


                                <!-- ACTIONS -->

                                <td>

                                    <div class="actions">

                                        <a
                                            href="settings.php?edit=<?= (int)$setting['id']; ?>"
                                            class="icon-btn"
                                            title="Edit Setting"
                                        >
                                            <i class="fa-solid fa-pen"></i>
                                        </a>


                                        <button
                                            type="button"
                                            class="icon-btn delete"
                                            title="Delete Setting"
                                            onclick="openDeleteModal(
                                                <?= (int)$setting['id']; ?>,
                                                '<?= e($setting['setting_key']); ?>'
                                            )"
                                        >
                                            <i class="fa-solid fa-trash"></i>
                                        </button>

                                    </div>

                                </td>

                            </tr>

                        <?php endforeach; ?>

                        </tbody>

                    </table>

                </div>


                <!-- =================================================
                     PAGINATION
                ================================================== -->

                <?php if ($totalPages > 1): ?>

                    <div class="pagination">

                        <div class="pagination-info">

                            Showing

                            <strong>
                                <?= $totalFiltered > 0
                                    ? $offset + 1
                                    : 0; ?>
                            </strong>

                            to

                            <strong>
                                <?= min(
                                    $offset + $perPage,
                                    $totalFiltered
                                ); ?>
                            </strong>

                            of

                            <strong>
                                <?= number_format($totalFiltered); ?>
                            </strong>

                            settings

                        </div>


                        <div class="pagination-links">

                            <?php if ($page > 1): ?>

                                <a
                                    href="<?= e(
                                        settingsQueryUrl($page - 1)
                                    ); ?>"
                                    class="page-link"
                                >
                                    <i class="fa-solid fa-chevron-left"></i>
                                </a>

                            <?php else: ?>

                                <span class="page-link disabled">
                                    <i class="fa-solid fa-chevron-left"></i>
                                </span>

                            <?php endif; ?>


                            <?php

                            $startPage = max(
                                1,
                                $page - 2
                            );

                            $endPage = min(
                                $totalPages,
                                $page + 2
                            );

                            for (
                                $p = $startPage;
                                $p <= $endPage;
                                $p++
                            ):
                            ?>

                                <a
                                    href="<?= e(
                                        settingsQueryUrl($p)
                                    ); ?>"
                                    class="page-link
                                    <?= $p === $page
                                        ? 'active'
                                        : ''; ?>"
                                >
                                    <?= $p; ?>
                                </a>

                            <?php endfor; ?>


                            <?php if ($page < $totalPages): ?>

                                <a
                                    href="<?= e(
                                        settingsQueryUrl($page + 1)
                                    ); ?>"
                                    class="page-link"
                                >
                                    <i class="fa-solid fa-chevron-right"></i>
                                </a>

                            <?php else: ?>

                                <span class="page-link disabled">
                                    <i class="fa-solid fa-chevron-right"></i>
                                </span>

                            <?php endif; ?>

                        </div>

                    </div>

                <?php endif; ?>

            <?php endif; ?>

        </section>

    </main>

</div>


<!-- =========================================================
     ADD / EDIT MODAL
========================================================= -->

<div
    class="modal-backdrop <?= $openForm ? 'show' : ''; ?>"
    id="settingModal"
>

    <div
        class="modal"
        role="dialog"
        aria-modal="true"
    >

        <div class="modal-head">

            <div class="modal-title">

                <div class="modal-title-icon">

                    <i class="fa-solid
                        <?= $editSetting
                            ? 'fa-pen'
                            : 'fa-plus'; ?>">
                    </i>

                </div>

                <div>

                    <h3>

                        <?= $editSetting
                            ? 'Edit Setting'
                            : 'Add New Setting'; ?>

                    </h3>

                    <p>
                        Store website configuration in the settings table.
                    </p>

                </div>

            </div>


            <button
                type="button"
                class="modal-close"
                onclick="closeSettingModal()"
            >
                <i class="fa-solid fa-xmark"></i>
            </button>

        </div>


        <form
            method="POST"
            action="settings.php"
        >

            <?= settingsCsrfField(); ?>

            <input
                type="hidden"
                name="action"
                value="save"
            >

            <input
                type="hidden"
                name="id"
                value="<?= $editSetting
                    ? (int)$editSetting['id']
                    : 0; ?>"
            >


            <div class="modal-body">

                <div class="form-grid">

                    <!-- SETTING KEY -->

                    <div class="form-group full">

                        <label class="form-label">

                            Setting Key

                            <span class="required">
                                *
                            </span>

                        </label>

                        <input
                            type="text"
                            name="setting_key"
                            class="form-control"
                            required
                            maxlength="150"
                            placeholder="Example: site_name"
                            value="<?= $editSetting
                                ? e($editSetting['setting_key'])
                                : ''; ?>"
                        >

                        <div class="help-text">

                            Use a unique key such as
                            <strong>site_name</strong>,
                            <strong>contact_email</strong>,
                            <strong>company_phone</strong>.

                            Spaces will automatically be converted.

                        </div>

                    </div>


                    <!-- GROUP -->

                    <div class="form-group">

                        <label class="form-label">

                            Setting Group

                            <span class="required">
                                *
                            </span>

                        </label>

                        <input
                            type="text"
                            name="setting_group"
                            class="form-control"
                            required
                            maxlength="100"
                            list="settingGroupList"
                            placeholder="general"
                            value="<?= $editSetting
                                ? e(
                                    $editSetting['setting_group']
                                )
                                : 'general'; ?>"
                        >

                        <datalist id="settingGroupList">

                            <?php foreach ($groups as $group): ?>

                                <option value="<?= e($group); ?>"></option>

                            <?php endforeach; ?>

                        </datalist>

                        <div class="help-text">
                            Group settings logically, e.g. general,
                            contact, social, seo.
                        </div>

                    </div>


                    <!-- VALUE TYPE INFO -->

                    <div class="form-group">

                        <label class="form-label">
                            Storage
                        </label>

                        <div
                            style="
                                min-height:45px;
                                display:flex;
                                align-items:center;
                                gap:9px;
                                padding:0 13px;
                                background:#f8fafc;
                                border:1px solid #e2e8f0;
                                border-radius:11px;
                                color:#64748b;
                                font-size:11px;
                            "
                        >

                            <i
                                class="fa-solid fa-database"
                                style="color:#0f766e;"
                            ></i>

                            <span>
                                Long text value
                            </span>

                        </div>

                        <div class="help-text">
                            The database column is LONGTEXT, so large
                            configuration values are supported.
                        </div>

                    </div>


                    <!-- VALUE -->

                    <div class="form-group full">

                        <label class="form-label">
                            Setting Value
                        </label>

                        <textarea
                            name="setting_value"
                            class="form-control"
                            placeholder="Enter setting value..."
                        ><?= $editSetting
                            ? e(
                                $editSetting['setting_value']
                            )
                            : ''; ?></textarea>

                        <div class="help-text">

                            Leave empty if this setting intentionally
                            requires a NULL/empty value.

                        </div>

                    </div>

                </div>

            </div>


            <div class="modal-footer">

                <button
                    type="button"
                    class="btn btn-secondary"
                    onclick="closeSettingModal()"
                >
                    Cancel
                </button>

                <button
                    type="submit"
                    class="btn btn-primary"
                >

                    <i class="fa-solid
                        <?= $editSetting
                            ? 'fa-floppy-disk'
                            : 'fa-plus'; ?>">
                    </i>

                    <?= $editSetting
                        ? 'Update Setting'
                        : 'Save Setting'; ?>

                </button>

            </div>

        </form>

    </div>

</div>


<!-- =========================================================
     DELETE MODAL
========================================================= -->

<div
    class="modal-backdrop"
    id="deleteModal"
>

    <div class="modal delete-modal">

        <div class="delete-body">

            <div class="delete-icon">

                <i class="fa-solid fa-trash"></i>

            </div>

            <h3>
                Delete Setting?
            </h3>

            <p>
                This action will permanently remove this setting
                from the database. Make sure the setting is not
                required by the frontend or admin system.
            </p>

            <div
                class="delete-key"
                id="deleteSettingKey"
            >
            </div>

        </div>


        <form
            method="POST"
            action="settings.php"
        >

            <?= settingsCsrfField(); ?>

            <input
                type="hidden"
                name="action"
                value="delete"
            >

            <input
                type="hidden"
                name="id"
                id="deleteSettingId"
                value=""
            >


            <div class="modal-footer">

                <button
                    type="button"
                    class="btn btn-secondary"
                    onclick="closeDeleteModal()"
                >
                    Cancel
                </button>

                <button
                    type="submit"
                    class="btn btn-danger"
                >
                    <i class="fa-solid fa-trash"></i>

                    Delete Setting
                </button>

            </div>

        </form>

    </div>

</div>


<script>

    /* =========================================================
       SETTING MODAL
    ========================================================= */

    const settingModal =
        document.getElementById('settingModal');

    function openSettingModal() {

        if (!settingModal) {
            return;
        }

        settingModal.classList.add('show');

        document.body.style.overflow = 'hidden';

        const firstInput =
            settingModal.querySelector(
                'input[name="setting_key"]'
            );

        if (firstInput) {
            setTimeout(function () {
                firstInput.focus();
            }, 120);
        }
    }

    function closeSettingModal() {

        if (!settingModal) {
            return;
        }

        settingModal.classList.remove('show');

        document.body.style.overflow = '';

        /*
         * If this page was opened through ?add=1 or ?edit=ID,
         * remove the query parameters when closing.
         */
        const url =
            new URL(window.location.href);

        if (
            url.searchParams.has('add') ||
            url.searchParams.has('edit')
        ) {

            url.searchParams.delete('add');
            url.searchParams.delete('edit');

            window.history.replaceState(
                {},
                document.title,
                url.toString()
            );
        }
    }


    /* =========================================================
       DELETE MODAL
    ========================================================= */

    const deleteModal =
        document.getElementById('deleteModal');

    function openDeleteModal(id, key) {

        if (!deleteModal) {
            return;
        }

        document.getElementById(
            'deleteSettingId'
        ).value = id;

        document.getElementById(
            'deleteSettingKey'
        ).textContent = key;

        deleteModal.classList.add('show');

        document.body.style.overflow = 'hidden';
    }

    function closeDeleteModal() {

        if (!deleteModal) {
            return;
        }

        deleteModal.classList.remove('show');

        document.body.style.overflow = '';
    }


    /* =========================================================
       BACKDROP CLICK
    ========================================================= */

    if (settingModal) {

        settingModal.addEventListener(
            'click',
            function (event) {

                if (event.target === settingModal) {
                    closeSettingModal();
                }

            }
        );
    }


    if (deleteModal) {

        deleteModal.addEventListener(
            'click',
            function (event) {

                if (event.target === deleteModal) {
                    closeDeleteModal();
                }

            }
        );
    }


    /* =========================================================
       ESC KEY
    ========================================================= */

    document.addEventListener(
        'keydown',
        function (event) {

            if (event.key !== 'Escape') {
                return;
            }

            closeSettingModal();
            closeDeleteModal();

        }
    );


    /* =========================================================
       CTRL + K SEARCH
    ========================================================= */

    document.addEventListener(
        'keydown',
        function (event) {

            if (
                (event.ctrlKey || event.metaKey) &&
                event.key.toLowerCase() === 'k'
            ) {

                event.preventDefault();

                const search =
                    document.querySelector(
                        'input[name="q"]'
                    );

                if (search) {
                    search.focus();
                }

            }

        }
    );

</script>

</body>
</html>