<?php
/**
 * Pure Chemical Admin
 * Statistics Management
 *
 * Existing table used:
 * statistics
 *
 * Columns:
 * id
 * label
 * value
 * suffix
 * prefix
 * description
 * section_key
 * 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();
}

/* -------------------------------------------------------
   Helpers
------------------------------------------------------- */

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('csrf_token')) {
    function csrf_token()
    {
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        }

        return $_SESSION['csrf_token'];
    }
}

if (!function_exists('csrf_field')) {
    function csrf_field()
    {
        return '<input type="hidden" name="csrf_token" value="' .
            e(csrf_token()) .
            '">';
    }
}

if (!function_exists('csrf_verify')) {
    function csrf_verify()
    {
        $token = $_POST['csrf_token'] ?? '';

        if (
            empty($_SESSION['csrf_token']) ||
            empty($token) ||
            !hash_equals($_SESSION['csrf_token'], $token)
        ) {
            throw new Exception('Invalid security token. Please refresh the page and try again.');
        }
    }
}

function redirectWithMessage($type, $message)
{
    $url = strtok($_SERVER['REQUEST_URI'], '?');

    header(
        'Location: ' .
        $url .
        '?' .
        http_build_query([
            'msg_type' => $type,
            'msg'      => $message
        ])
    );

    exit;
}

function slugSectionKey($value)
{
    $value = trim((string)$value);

    $value = strtolower($value);

    $value = preg_replace('/[^a-z0-9]+/', '_', $value);
    $value = trim($value, '_');

    return $value;
}

/* -------------------------------------------------------
   POST ACTIONS
------------------------------------------------------- */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    try {

        csrf_verify();

        $action = $_POST['action'] ?? '';

        /* -----------------------------------------------
           SAVE / UPDATE
        ------------------------------------------------ */

        if ($action === 'save') {

            $id = isset($_POST['id'])
                ? (int)$_POST['id']
                : 0;

            $label = trim($_POST['label'] ?? '');
            $value = trim($_POST['value'] ?? '');
            $suffix = trim($_POST['suffix'] ?? '');
            $prefix = trim($_POST['prefix'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $sectionKey = trim($_POST['section_key'] ?? '');
            $sortOrder = (int)($_POST['sort_order'] ?? 0);
            $status = isset($_POST['status']) ? 1 : 0;

            /* Validation */

            if ($label === '') {
                throw new Exception('Statistic label is required.');
            }

            if (mb_strlen($label) > 255) {
                throw new Exception('Statistic label is too long.');
            }

            if ($value === '') {
                throw new Exception('Statistic value is required.');
            }

            if ($sectionKey === '') {
                $sectionKey = 'homepage_statistics';
            }

            $sectionKey = slugSectionKey($sectionKey);

            if ($sectionKey === '') {
                throw new Exception('Please enter a valid section key.');
            }

            if (mb_strlen($sectionKey) > 150) {
                throw new Exception('Section key is too long.');
            }

            if ($sortOrder < 0) {
                $sortOrder = 0;
            }

            /* Update */

            if ($id > 0) {

                $check = $pdo->prepare("
                    SELECT id
                    FROM statistics
                    WHERE id = :id
                    LIMIT 1
                ");

                $check->execute([
                    ':id' => $id
                ]);

                if (!$check->fetch()) {
                    throw new Exception('Statistic record not found.');
                }

                $stmt = $pdo->prepare("
                    UPDATE statistics
                    SET
                        label = :label,
                        value = :value,
                        suffix = :suffix,
                        prefix = :prefix,
                        description = :description,
                        section_key = :section_key,
                        sort_order = :sort_order,
                        status = :status
                    WHERE id = :id
                ");

                $stmt->execute([
                    ':label'       => $label,
                    ':value'       => $value,
                    ':suffix'      => $suffix !== '' ? $suffix : null,
                    ':prefix'      => $prefix !== '' ? $prefix : null,
                    ':description' => $description !== '' ? $description : null,
                    ':section_key' => $sectionKey,
                    ':sort_order'  => $sortOrder,
                    ':status'      => $status,
                    ':id'          => $id
                ]);

                redirectWithMessage(
                    'success',
                    'Statistic updated successfully.'
                );
            }

            /* Insert */

            $stmt = $pdo->prepare("
                INSERT INTO statistics
                (
                    label,
                    value,
                    suffix,
                    prefix,
                    description,
                    section_key,
                    sort_order,
                    status
                )
                VALUES
                (
                    :label,
                    :value,
                    :suffix,
                    :prefix,
                    :description,
                    :section_key,
                    :sort_order,
                    :status
                )
            ");

            $stmt->execute([
                ':label'       => $label,
                ':value'       => $value,
                ':suffix'      => $suffix !== '' ? $suffix : null,
                ':prefix'      => $prefix !== '' ? $prefix : null,
                ':description' => $description !== '' ? $description : null,
                ':section_key' => $sectionKey,
                ':sort_order'  => $sortOrder,
                ':status'      => $status
            ]);

            redirectWithMessage(
                'success',
                'Statistic added successfully.'
            );
        }

        /* -----------------------------------------------
           DELETE
        ------------------------------------------------ */

        if ($action === 'delete') {

            $id = (int)($_POST['id'] ?? 0);

            if ($id <= 0) {
                throw new Exception('Invalid statistic ID.');
            }

            $stmt = $pdo->prepare("
                DELETE FROM statistics
                WHERE id = :id
                LIMIT 1
            ");

            $stmt->execute([
                ':id' => $id
            ]);

            redirectWithMessage(
                'success',
                'Statistic deleted successfully.'
            );
        }

        /* -----------------------------------------------
           TOGGLE STATUS
        ------------------------------------------------ */

        if ($action === 'toggle_status') {

            $id = (int)($_POST['id'] ?? 0);

            if ($id <= 0) {
                throw new Exception('Invalid statistic ID.');
            }

            $stmt = $pdo->prepare("
                UPDATE statistics
                SET status = CASE
                    WHEN status = 1 THEN 0
                    ELSE 1
                END
                WHERE id = :id
                LIMIT 1
            ");

            $stmt->execute([
                ':id' => $id
            ]);

            redirectWithMessage(
                'success',
                'Statistic status updated.'
            );
        }

        throw new Exception('Invalid action.');

    } catch (Throwable $e) {

        redirectWithMessage(
            'error',
            $e->getMessage()
        );
    }
}

/* -------------------------------------------------------
   MESSAGE
------------------------------------------------------- */

$message = $_GET['msg'] ?? '';
$messageType = $_GET['msg_type'] ?? '';

/* -------------------------------------------------------
   FILTERS
------------------------------------------------------- */

$search = trim($_GET['search'] ?? '');
$sectionFilter = trim($_GET['section'] ?? '');
$statusFilter = $_GET['status'] ?? '';

/* -------------------------------------------------------
   STATS
------------------------------------------------------- */

$totalStats = (int)$pdo
    ->query("SELECT COUNT(*) FROM statistics")
    ->fetchColumn();

$activeStats = (int)$pdo
    ->query("
        SELECT COUNT(*)
        FROM statistics
        WHERE status = 1
    ")
    ->fetchColumn();

$inactiveStats = (int)$pdo
    ->query("
        SELECT COUNT(*)
        FROM statistics
        WHERE status = 0
    ")
    ->fetchColumn();

$sectionCount = (int)$pdo
    ->query("
        SELECT COUNT(DISTINCT section_key)
        FROM statistics
        WHERE section_key IS NOT NULL
        AND section_key != ''
    ")
    ->fetchColumn();

/* -------------------------------------------------------
   SECTION LIST
------------------------------------------------------- */

$sectionStmt = $pdo->query("
    SELECT DISTINCT section_key
    FROM statistics
    WHERE section_key IS NOT NULL
    AND section_key != ''
    ORDER BY section_key ASC
");

$sections = $sectionStmt->fetchAll();

/* -------------------------------------------------------
   LIST QUERY
------------------------------------------------------- */

$sql = "
    SELECT
        id,
        label,
        value,
        suffix,
        prefix,
        description,
        section_key,
        sort_order,
        status
    FROM statistics
    WHERE 1 = 1
";

$params = [];

if ($search !== '') {

    $sql .= "
        AND (
            label LIKE :search
            OR value LIKE :search
            OR description LIKE :search
            OR section_key LIKE :search
        )
    ";

    $params[':search'] = '%' . $search . '%';
}

if ($sectionFilter !== '') {

    $sql .= "
        AND section_key = :section
    ";

    $params[':section'] = $sectionFilter;
}

if ($statusFilter !== '' && in_array($statusFilter, ['0', '1'], true)) {

    $sql .= "
        AND status = :status
    ";

    $params[':status'] = (int)$statusFilter;
}

$sql .= "
    ORDER BY sort_order ASC, id ASC
";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);

$statistics = $stmt->fetchAll();

/* -------------------------------------------------------
   EDIT RECORD
------------------------------------------------------- */

$editId = isset($_GET['edit'])
    ? (int)$_GET['edit']
    : 0;

$editStatistic = null;

if ($editId > 0) {

    $stmt = $pdo->prepare("
        SELECT
            id,
            label,
            value,
            suffix,
            prefix,
            description,
            section_key,
            sort_order,
            status
        FROM statistics
        WHERE id = :id
        LIMIT 1
    ");

    $stmt->execute([
        ':id' => $editId
    ]);

    $editStatistic = $stmt->fetch();

    if (!$editStatistic) {
        $editId = 0;
    }
}

?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>Statistics Management | Pure Chemical Admin</title>

    <meta
        name="description"
        content="Manage website statistics"
    >

    <link
        rel="preconnect"
        href="https://fonts.googleapis.com"
    >

    <link
        rel="preconnect"
        href="https://fonts.gstatic.com"
        crossorigin
    >

    <link
        href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap"
        rel="stylesheet"
    >

    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
    >

    <style>

        :root {
            --primary: #0f766e;
            --primary-dark: #115e59;
            --primary-soft: #ecfdf5;

            --dark: #0f172a;
            --muted: #64748b;
            --border: #e2e8f0;
            --surface: #ffffff;
            --bg: #f8fafc;

            --success: #15803d;
            --success-bg: #f0fdf4;

            --danger: #dc2626;
            --danger-bg: #fef2f2;

            --warning: #d97706;
            --warning-bg: #fffbeb;

            --shadow-sm:
                0 1px 2px rgba(15, 23, 42, .04);

            --shadow-md:
                0 10px 30px rgba(15, 23, 42, .07);

            --shadow-lg:
                0 20px 50px rgba(15, 23, 42, .12);

            --radius: 18px;
        }

        * {
            box-sizing: border-box;
        }

        html {
            scroll-behavior: smooth;
        }

        body {
            margin: 0;
            background:
                radial-gradient(
                    circle at top right,
                    rgba(20, 184, 166, .07),
                    transparent 30%
                ),
                var(--bg);

            color: var(--dark);
            font-family: 'Inter', sans-serif;
        }

        button,
        input,
        textarea,
        select {
            font: inherit;
        }

        a {
            color: inherit;
            text-decoration: none;
        }

        /* ------------------------------------------------
           MAIN
        ------------------------------------------------ */

        .page-wrapper {
            margin-left: 280px;
            min-height: 100vh;
        }

        .page-content {
            padding: 28px;
            max-width: 1700px;
            margin: 0 auto;
        }

        /* ------------------------------------------------
           TOPBAR
        ------------------------------------------------ */

        .topbar {
            position: sticky;
            top: 0;
            z-index: 50;

            display: flex;
            align-items: center;
            justify-content: space-between;

            gap: 20px;

            min-height: 76px;

            padding: 14px 28px;

            background: rgba(255, 255, 255, .88);

            border-bottom: 1px solid rgba(226, 232, 240, .8);

            backdrop-filter: blur(18px);
            -webkit-backdrop-filter: blur(18px);
        }

        .topbar-left {
            display: flex;
            align-items: center;
            gap: 14px;
        }

        .topbar-icon {
            width: 44px;
            height: 44px;

            border-radius: 14px;

            display: flex;
            align-items: center;
            justify-content: center;

            color: white;

            background:
                linear-gradient(
                    135deg,
                    var(--primary),
                    #14b8a6
                );

            box-shadow:
                0 8px 20px rgba(15, 118, 110, .22);
        }

        .topbar-title {
            margin: 0;

            font-size: 18px;
            font-weight: 800;

            letter-spacing: -.02em;
        }

        .topbar-subtitle {
            margin: 3px 0 0;

            color: var(--muted);

            font-size: 12px;
            font-weight: 500;
        }

        .topbar-right {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .admin-chip {
            display: flex;
            align-items: center;
            gap: 10px;

            padding: 8px 12px;

            border: 1px solid var(--border);
            border-radius: 14px;

            background: white;
        }

        .admin-avatar {
            width: 34px;
            height: 34px;

            border-radius: 10px;

            display: flex;
            align-items: center;
            justify-content: center;

            background: var(--primary-soft);
            color: var(--primary);

            font-size: 14px;
            font-weight: 800;
        }

        .admin-name {
            font-size: 13px;
            font-weight: 700;
        }

        /* ------------------------------------------------
           PAGE HEADER
        ------------------------------------------------ */

        .page-header {
            display: flex;
            align-items: flex-end;
            justify-content: space-between;

            gap: 20px;

            margin-bottom: 24px;
        }

        .eyebrow {
            display: inline-flex;
            align-items: center;
            gap: 7px;

            color: var(--primary);

            font-size: 11px;
            font-weight: 800;

            text-transform: uppercase;
            letter-spacing: .12em;

            margin-bottom: 8px;
        }

        .page-title {
            margin: 0;

            font-size: clamp(25px, 3vw, 34px);

            line-height: 1.1;

            letter-spacing: -.045em;

            font-weight: 800;
        }

        .page-description {
            margin: 9px 0 0;

            color: var(--muted);

            font-size: 14px;

            max-width: 700px;

            line-height: 1.6;
        }

        .btn {
            border: 0;

            min-height: 44px;

            padding: 0 16px;

            border-radius: 13px;

            display: inline-flex;
            align-items: center;
            justify-content: center;

            gap: 8px;

            cursor: pointer;

            font-size: 13px;
            font-weight: 700;

            transition:
                transform .2s ease,
                box-shadow .2s ease,
                background .2s ease;
        }

        .btn:hover {
            transform: translateY(-1px);
        }

        .btn-primary {
            color: white;

            background:
                linear-gradient(
                    135deg,
                    var(--primary),
                    #0d9488
                );

            box-shadow:
                0 8px 20px rgba(15, 118, 110, .2);
        }

        .btn-secondary {
            color: var(--dark);

            background: white;

            border: 1px solid var(--border);
        }

        .btn-danger {
            color: white;
            background: var(--danger);
        }

        /* ------------------------------------------------
           STATS CARDS
        ------------------------------------------------ */

        .stats-grid {
            display: grid;

            grid-template-columns:
                repeat(4, minmax(0, 1fr));

            gap: 16px;

            margin-bottom: 22px;
        }

        .stat-card {
            position: relative;

            overflow: hidden;

            padding: 20px;

            border: 1px solid var(--border);

            border-radius: var(--radius);

            background: var(--surface);

            box-shadow: var(--shadow-sm);

            transition:
                transform .2s ease,
                box-shadow .2s ease;
        }

        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }

        .stat-card::after {
            content: "";

            position: absolute;

            width: 90px;
            height: 90px;

            border-radius: 50%;

            right: -35px;
            top: -35px;

            background: rgba(20, 184, 166, .08);
        }

        .stat-icon {
            width: 42px;
            height: 42px;

            border-radius: 13px;

            display: flex;
            align-items: center;
            justify-content: center;

            color: var(--primary);

            background: var(--primary-soft);

            margin-bottom: 15px;
        }

        .stat-number {
            font-size: 27px;
            font-weight: 800;

            letter-spacing: -.04em;
        }

        .stat-label {
            color: var(--muted);

            margin-top: 5px;

            font-size: 12px;
            font-weight: 600;
        }

        /* ------------------------------------------------
           ALERT
        ------------------------------------------------ */

        .alert {
            display: flex;
            align-items: center;
            gap: 11px;

            margin-bottom: 20px;

            padding: 14px 16px;

            border-radius: 14px;

            font-size: 13px;
            font-weight: 600;
        }

        .alert-success {
            color: #166534;
            background: var(--success-bg);
            border: 1px solid #bbf7d0;
        }

        .alert-error {
            color: #991b1b;
            background: var(--danger-bg);
            border: 1px solid #fecaca;
        }

        /* ------------------------------------------------
           FILTER PANEL
        ------------------------------------------------ */

        .panel {
            border: 1px solid var(--border);

            border-radius: var(--radius);

            background: white;

            box-shadow: var(--shadow-sm);

            overflow: hidden;
        }

        .filter-panel {
            margin-bottom: 20px;

            padding: 18px;
        }

        .filter-form {
            display: grid;

            grid-template-columns:
                minmax(220px, 1.8fr)
                minmax(180px, 1fr)
                minmax(160px, .8fr)
                auto;

            gap: 12px;

            align-items: end;
        }

        .field {
            display: flex;
            flex-direction: column;
            gap: 7px;
        }

        .field label {
            font-size: 11px;

            color: #475569;

            font-weight: 800;

            text-transform: uppercase;

            letter-spacing: .07em;
        }

        .input,
        .select,
        .textarea {
            width: 100%;

            border: 1px solid var(--border);

            background: #fff;

            color: var(--dark);

            border-radius: 12px;

            outline: none;

            transition:
                border-color .2s ease,
                box-shadow .2s ease;
        }

        .input,
        .select {
            height: 44px;

            padding: 0 13px;
        }

        .textarea {
            min-height: 100px;

            resize: vertical;

            padding: 12px 13px;

            line-height: 1.6;
        }

        .input:focus,
        .select:focus,
        .textarea:focus {
            border-color: rgba(15, 118, 110, .55);

            box-shadow:
                0 0 0 4px rgba(15, 118, 110, .08);
        }

        .filter-actions {
            display: flex;
            gap: 8px;
        }

        /* ------------------------------------------------
           TABLE
        ------------------------------------------------ */

        .table-header {
            display: flex;
            align-items: center;
            justify-content: space-between;

            gap: 15px;

            padding: 18px 20px;

            border-bottom: 1px solid var(--border);
        }

        .table-title {
            margin: 0;

            font-size: 15px;
            font-weight: 800;
        }

        .table-count {
            color: var(--muted);

            font-size: 12px;
            font-weight: 600;
        }

        .table-wrap {
            overflow-x: auto;
        }

        table {
            width: 100%;

            border-collapse: collapse;

            min-width: 1050px;
        }

        th {
            padding: 13px 18px;

            background: #f8fafc;

            border-bottom: 1px solid var(--border);

            color: #64748b;

            text-align: left;

            font-size: 10px;

            text-transform: uppercase;

            letter-spacing: .09em;

            font-weight: 800;
        }

        td {
            padding: 16px 18px;

            border-bottom: 1px solid #eef2f7;

            vertical-align: middle;

            font-size: 13px;
        }

        tbody tr {
            transition: background .2s ease;
        }

        tbody tr:hover {
            background: #fbfefd;
        }

        tbody tr:last-child td {
            border-bottom: 0;
        }

        .drag-order {
            display: inline-flex;
            align-items: center;
            justify-content: center;

            width: 32px;
            height: 32px;

            border-radius: 10px;

            background: #f1f5f9;

            color: #475569;

            font-size: 12px;
            font-weight: 800;
        }

        .stat-main {
            display: flex;
            align-items: center;

            gap: 12px;
        }

        .stat-preview {
            min-width: 72px;

            padding: 8px 10px;

            border-radius: 10px;

            background: var(--primary-soft);

            color: var(--primary);

            text-align: center;

            font-size: 15px;
            font-weight: 800;
        }

        .stat-label-cell {
            font-weight: 750;
            color: var(--dark);
        }

        .description {
            max-width: 260px;

            color: var(--muted);

            font-size: 12px;

            line-height: 1.5;
        }

        .section-badge {
            display: inline-flex;

            align-items: center;

            padding: 7px 10px;

            border-radius: 9px;

            background: #f1f5f9;

            color: #475569;

            font-size: 11px;

            font-weight: 700;
        }

        .status-badge {
            display: inline-flex;

            align-items: center;

            gap: 6px;

            padding: 7px 10px;

            border-radius: 999px;

            font-size: 11px;

            font-weight: 800;
        }

        .status-badge.active {
            color: #166534;

            background: #dcfce7;
        }

        .status-badge.inactive {
            color: #991b1b;

            background: #fee2e2;
        }

        .status-dot {
            width: 6px;
            height: 6px;

            border-radius: 50%;

            background: currentColor;
        }

        .actions {
            display: flex;

            align-items: center;

            gap: 7px;
        }

        .icon-btn {
            width: 35px;
            height: 35px;

            border-radius: 10px;

            border: 1px solid var(--border);

            background: white;

            display: inline-flex;

            align-items: center;
            justify-content: center;

            cursor: pointer;

            color: #475569;

            transition: all .2s ease;
        }

        .icon-btn:hover {
            border-color: #cbd5e1;
            background: #f8fafc;

            transform: translateY(-1px);
        }

        .icon-btn.edit:hover {
            color: var(--primary);
            border-color: rgba(15, 118, 110, .25);
        }

        .icon-btn.delete:hover {
            color: var(--danger);
            border-color: rgba(220, 38, 38, .25);
        }

        .icon-btn.status:hover {
            color: var(--warning);
            border-color: rgba(217, 119, 6, .25);
        }

        .empty-state {
            padding: 70px 20px;

            text-align: center;
        }

        .empty-icon {
            width: 64px;
            height: 64px;

            margin: 0 auto 16px;

            border-radius: 18px;

            display: flex;
            align-items: center;
            justify-content: center;

            background: var(--primary-soft);

            color: var(--primary);

            font-size: 24px;
        }

        .empty-title {
            margin: 0;

            font-size: 16px;
            font-weight: 800;
        }

        .empty-text {
            margin: 7px auto 0;

            max-width: 450px;

            color: var(--muted);

            font-size: 13px;

            line-height: 1.6;
        }

        /* ------------------------------------------------
           MODAL
        ------------------------------------------------ */

        .modal {
            position: fixed;

            inset: 0;

            z-index: 200;

            display: none;

            align-items: center;
            justify-content: center;

            padding: 20px;

            background: rgba(15, 23, 42, .55);

            backdrop-filter: blur(7px);
        }

        .modal.show {
            display: flex;
        }

        .modal-card {
            width: min(720px, 100%);

            max-height: calc(100vh - 40px);

            overflow-y: auto;

            background: white;

            border-radius: 22px;

            box-shadow: var(--shadow-lg);

            animation: modalIn .2s ease;
        }

        @keyframes modalIn {
            from {
                opacity: 0;
                transform: translateY(10px) scale(.98);
            }

            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }

        .modal-header {
            display: flex;
            align-items: flex-start;
            justify-content: space-between;

            gap: 20px;

            padding: 22px 24px;

            border-bottom: 1px solid var(--border);
        }

        .modal-title {
            margin: 0;

            font-size: 18px;
            font-weight: 800;

            letter-spacing: -.02em;
        }

        .modal-subtitle {
            margin: 5px 0 0;

            color: var(--muted);

            font-size: 12px;
        }

        .modal-close {
            width: 36px;
            height: 36px;

            border: 1px solid var(--border);

            border-radius: 10px;

            background: white;

            color: var(--muted);

            cursor: pointer;
        }

        .modal-body {
            padding: 24px;
        }

        .form-grid {
            display: grid;

            grid-template-columns:
                repeat(2, minmax(0, 1fr));

            gap: 17px;
        }

        .full {
            grid-column: 1 / -1;
        }

        .helper {
            margin-top: 3px;

            color: #94a3b8;

            font-size: 11px;

            line-height: 1.5;
        }

        .switch-row {
            display: flex;

            align-items: center;
            justify-content: space-between;

            gap: 20px;

            padding: 13px 14px;

            border: 1px solid var(--border);

            border-radius: 13px;

            background: #fafafa;
        }

        .switch-info strong {
            display: block;

            font-size: 13px;
        }

        .switch-info span {
            display: block;

            margin-top: 3px;

            color: var(--muted);

            font-size: 11px;
        }

        .switch {
            position: relative;

            width: 48px;
            height: 27px;
        }

        .switch input {
            opacity: 0;

            width: 0;
            height: 0;
        }

        .slider {
            position: absolute;

            inset: 0;

            cursor: pointer;

            border-radius: 999px;

            background: #cbd5e1;

            transition: .2s;
        }

        .slider::before {
            content: "";

            position: absolute;

            width: 21px;
            height: 21px;

            left: 3px;
            top: 3px;

            border-radius: 50%;

            background: white;

            box-shadow: 0 2px 5px rgba(15, 23, 42, .15);

            transition: .2s;
        }

        .switch input:checked + .slider {
            background: var(--primary);
        }

        .switch input:checked + .slider::before {
            transform: translateX(21px);
        }

        .modal-footer {
            display: flex;

            align-items: center;
            justify-content: flex-end;

            gap: 10px;

            padding: 18px 24px;

            border-top: 1px solid var(--border);
        }

        .delete-modal-card {
            width: min(430px, 100%);
        }

        .delete-icon {
            width: 55px;
            height: 55px;

            margin-bottom: 15px;

            border-radius: 16px;

            display: flex;
            align-items: center;
            justify-content: center;

            color: var(--danger);

            background: var(--danger-bg);

            font-size: 20px;
        }

        /* ------------------------------------------------
           RESPONSIVE
        ------------------------------------------------ */

        @media (max-width: 1200px) {

            .stats-grid {
                grid-template-columns:
                    repeat(2, minmax(0, 1fr));
            }

            .filter-form {
                grid-template-columns:
                    repeat(2, minmax(0, 1fr));
            }

            .filter-actions {
                grid-column: 1 / -1;
            }

        }

        @media (max-width: 1000px) {

            .page-wrapper {
                margin-left: 0;
            }

        }

        @media (max-width: 700px) {

            .page-content {
                padding: 18px;
            }

            .topbar {
                padding: 12px 18px;
            }

            .admin-chip {
                display: none;
            }

            .page-header {
                align-items: flex-start;

                flex-direction: column;
            }

            .page-header .btn {
                width: 100%;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }

            .filter-form {
                grid-template-columns: 1fr;
            }

            .filter-actions {
                grid-column: auto;
            }

            .filter-actions .btn {
                flex: 1;
            }

            .form-grid {
                grid-template-columns: 1fr;
            }

            .full {
                grid-column: auto;
            }

            .modal-body {
                padding: 18px;
            }

            .modal-header {
                padding: 18px;
            }

            .modal-footer {
                padding: 16px 18px;
            }

        }

    </style>

</head>

<body>

<?php
/*
|--------------------------------------------------------------------------
| EXISTING ADMIN SIDEBAR
|--------------------------------------------------------------------------
*/
require_once __DIR__ . '/sidebar.php';
?>

<div class="page-wrapper">

    <!-- TOPBAR -->

    <header class="topbar">

        <div class="topbar-left">

            <div class="topbar-icon">
                <i class="fa-solid fa-chart-simple"></i>
            </div>

            <div>

                <h1 class="topbar-title">
                    Statistics
                </h1>

                <p class="topbar-subtitle">
                    Website performance highlights
                </p>

            </div>

        </div>

        <div class="topbar-right">

            <div class="admin-chip">

                <div class="admin-avatar">
                    <i class="fa-solid fa-user"></i>
                </div>

                <div class="admin-name">
                    <?= e($_SESSION['ADMIN_NAME'] ?? 'Administrator') ?>
                </div>

            </div>

        </div>

    </header>


    <main class="page-content">

        <!-- PAGE HEADER -->

        <section class="page-header">

            <div>

                <div class="eyebrow">
                    <i class="fa-solid fa-sparkles"></i>
                    Content Management
                </div>

                <h2 class="page-title">
                    Website Statistics
                </h2>

                <p class="page-description">
                    Manage the numerical highlights displayed across
                    your website. Update values, labels, sections and
                    display order from one place.
                </p>

            </div>

            <button
                type="button"
                class="btn btn-primary"
                onclick="openAddModal()"
            >
                <i class="fa-solid fa-plus"></i>
                Add Statistic
            </button>

        </section>


        <!-- ALERT -->

        <?php if ($message !== ''): ?>

            <div class="alert <?= $messageType === 'error'
                ? 'alert-error'
                : 'alert-success' ?>">

                <i class="fa-solid <?= $messageType === 'error'
                    ? 'fa-circle-exclamation'
                    : 'fa-circle-check' ?>"></i>

                <span>
                    <?= e($message) ?>
                </span>

            </div>

        <?php endif; ?>


        <!-- STAT CARDS -->

        <section class="stats-grid">

            <div class="stat-card">

                <div class="stat-icon">
                    <i class="fa-solid fa-chart-column"></i>
                </div>

                <div class="stat-number">
                    <?= number_format($totalStats) ?>
                </div>

                <div class="stat-label">
                    Total Statistics
                </div>

            </div>


            <div class="stat-card">

                <div class="stat-icon">
                    <i class="fa-solid fa-circle-check"></i>
                </div>

                <div class="stat-number">
                    <?= number_format($activeStats) ?>
                </div>

                <div class="stat-label">
                    Active Statistics
                </div>

            </div>


            <div class="stat-card">

                <div class="stat-icon">
                    <i class="fa-solid fa-circle-pause"></i>
                </div>

                <div class="stat-number">
                    <?= number_format($inactiveStats) ?>
                </div>

                <div class="stat-label">
                    Inactive Statistics
                </div>

            </div>


            <div class="stat-card">

                <div class="stat-icon">
                    <i class="fa-solid fa-layer-group"></i>
                </div>

                <div class="stat-number">
                    <?= number_format($sectionCount) ?>
                </div>

                <div class="stat-label">
                    Sections
                </div>

            </div>

        </section>


        <!-- FILTER -->

        <section class="panel filter-panel">

            <form
                method="GET"
                class="filter-form"
            >

                <div class="field">

                    <label for="search">
                        Search
                    </label>

                    <input
                        type="text"
                        id="search"
                        name="search"
                        class="input"
                        placeholder="Search label, value or section..."
                        value="<?= e($search) ?>"
                    >

                </div>


                <div class="field">

                    <label for="section">
                        Section
                    </label>

                    <select
                        id="section"
                        name="section"
                        class="select"
                    >

                        <option value="">
                            All Sections
                        </option>

                        <?php foreach ($sections as $section): ?>

                            <option
                                value="<?= e($section['section_key']) ?>"
                                <?= $sectionFilter === $section['section_key']
                                    ? 'selected'
                                    : '' ?>
                            >
                                <?= e($section['section_key']) ?>
                            </option>

                        <?php endforeach; ?>

                    </select>

                </div>


                <div class="field">

                    <label for="status">
                        Status
                    </label>

                    <select
                        id="status"
                        name="status"
                        class="select"
                    >

                        <option value="">
                            All Status
                        </option>

                        <option
                            value="1"
                            <?= $statusFilter === '1'
                                ? 'selected'
                                : '' ?>
                        >
                            Active
                        </option>

                        <option
                            value="0"
                            <?= $statusFilter === '0'
                                ? 'selected'
                                : '' ?>
                        >
                            Inactive
                        </option>

                    </select>

                </div>


                <div class="filter-actions">

                    <button
                        type="submit"
                        class="btn btn-primary"
                    >
                        <i class="fa-solid fa-filter"></i>
                        Apply
                    </button>

                    <a
                        href="<?= e(strtok($_SERVER['REQUEST_URI'], '?')) ?>"
                        class="btn btn-secondary"
                    >
                        <i class="fa-solid fa-rotate-left"></i>
                        Reset
                    </a>

                </div>

            </form>

        </section>


        <!-- TABLE -->

        <section class="panel">

            <div class="table-header">

                <div>

                    <h3 class="table-title">
                        Statistics List
                    </h3>

                    <div class="table-count">
                        <?= number_format(count($statistics)) ?>
                        result<?= count($statistics) !== 1 ? 's' : '' ?>
                    </div>

                </div>

            </div>


            <?php if (!empty($statistics)): ?>

                <div class="table-wrap">

                    <table>

                        <thead>

                            <tr>

                                <th>
                                    Order
                                </th>

                                <th>
                                    Statistic
                                </th>

                                <th>
                                    Description
                                </th>

                                <th>
                                    Section
                                </th>

                                <th>
                                    Status
                                </th>

                                <th>
                                    Actions
                                </th>

                            </tr>

                        </thead>

                        <tbody>

                        <?php foreach ($statistics as $row): ?>

                            <?php
                                $displayValue =
                                    ($row['prefix'] ?? '') .
                                    $row['value'] .
                                    ($row['suffix'] ?? '');
                            ?>

                            <tr>

                                <td>

                                    <span class="drag-order">
                                        <?= (int)$row['sort_order'] ?>
                                    </span>

                                </td>


                                <td>

                                    <div class="stat-main">

                                        <div class="stat-preview">
                                            <?= e($displayValue) ?>
                                        </div>

                                        <div>

                                            <div class="stat-label-cell">
                                                <?= e($row['label']) ?>
                                            </div>

                                            <?php if (!empty($row['value'])): ?>

                                                <div class="table-count">
                                                    Value:
                                                    <?= e($row['value']) ?>
                                                </div>

                                            <?php endif; ?>

                                        </div>

                                    </div>

                                </td>


                                <td>

                                    <div class="description">

                                        <?php if (!empty($row['description'])): ?>

                                            <?= e($row['description']) ?>

                                        <?php else: ?>

                                            <span style="opacity:.55;">
                                                No description
                                            </span>

                                        <?php endif; ?>

                                    </div>

                                </td>


                                <td>

                                    <span class="section-badge">

                                        <i
                                            class="fa-solid fa-layer-group"
                                            style="margin-right:6px;"
                                        ></i>

                                        <?= e($row['section_key']) ?>

                                    </span>

                                </td>


                                <td>

                                    <form
                                        method="POST"
                                        style="display:inline;"
                                    >

                                        <?= csrf_field() ?>

                                        <input
                                            type="hidden"
                                            name="action"
                                            value="toggle_status"
                                        >

                                        <input
                                            type="hidden"
                                            name="id"
                                            value="<?= (int)$row['id'] ?>"
                                        >

                                        <button
                                            type="submit"
                                            class="status-badge <?= (int)$row['status'] === 1
                                                ? 'active'
                                                : 'inactive' ?>"
                                            style="border:0;cursor:pointer;"
                                            title="Click to change status"
                                        >

                                            <span class="status-dot"></span>

                                            <?= (int)$row['status'] === 1
                                                ? 'Active'
                                                : 'Inactive' ?>

                                        </button>

                                    </form>

                                </td>


                                <td>

                                    <div class="actions">

                                        <a
                                            href="?edit=<?= (int)$row['id'] ?>"
                                            class="icon-btn edit"
                                            title="Edit statistic"
                                        >
                                            <i class="fa-solid fa-pen"></i>
                                        </a>


                                        <button
                                            type="button"
                                            class="icon-btn status"
                                            title="Change status"
                                            onclick="toggleStatus(<?= (int)$row['id'] ?>)"
                                        >
                                            <i class="fa-solid fa-power-off"></i>
                                        </button>


                                        <button
                                            type="button"
                                            class="icon-btn delete"
                                            title="Delete statistic"
                                            onclick="openDeleteModal(
                                                <?= (int)$row['id'] ?>,
                                                <?= htmlspecialchars(
                                                    json_encode(
                                                        $row['label'],
                                                        JSON_UNESCAPED_UNICODE
                                                    ),
                                                    ENT_QUOTES,
                                                    'UTF-8'
                                                ) ?>
                                            )"
                                        >
                                            <i class="fa-solid fa-trash"></i>
                                        </button>

                                    </div>

                                </td>

                            </tr>

                        <?php endforeach; ?>

                        </tbody>

                    </table>

                </div>

            <?php else: ?>

                <div class="empty-state">

                    <div class="empty-icon">
                        <i class="fa-solid fa-chart-simple"></i>
                    </div>

                    <h3 class="empty-title">
                        No statistics found
                    </h3>

                    <p class="empty-text">
                        There are no statistics matching your current
                        filters. Add your first statistic to display
                        website highlights.
                    </p>

                    <button
                        type="button"
                        class="btn btn-primary"
                        style="margin-top:18px;"
                        onclick="openAddModal()"
                    >
                        <i class="fa-solid fa-plus"></i>
                        Add Statistic
                    </button>

                </div>

            <?php endif; ?>

        </section>

    </main>

</div>


<!-- =====================================================
     ADD / EDIT MODAL
===================================================== -->

<div
    class="modal <?= $editStatistic ? 'show' : '' ?>"
    id="statisticModal"
>

    <div class="modal-card">

        <div class="modal-header">

            <div>

                <h3 class="modal-title">

                    <?= $editStatistic
                        ? 'Edit Statistic'
                        : 'Add New Statistic' ?>

                </h3>

                <p class="modal-subtitle">
                    <?= $editStatistic
                        ? 'Update the selected website statistic.'
                        : 'Create a new website statistic.' ?>
                </p>

            </div>

            <button
                type="button"
                class="modal-close"
                onclick="closeModal()"
            >
                <i class="fa-solid fa-xmark"></i>
            </button>

        </div>


        <form
            method="POST"
            action=""
        >

            <?= csrf_field() ?>

            <input
                type="hidden"
                name="action"
                value="save"
            >

            <input
                type="hidden"
                name="id"
                value="<?= $editStatistic
                    ? (int)$editStatistic['id']
                    : 0 ?>"
            >


            <div class="modal-body">

                <div class="form-grid">


                    <!-- LABEL -->

                    <div class="field">

                        <label for="label">
                            Label *
                        </label>

                        <input
                            type="text"
                            id="label"
                            name="label"
                            class="input"
                            maxlength="255"
                            required
                            placeholder="e.g. Happy Customers"
                            value="<?= $editStatistic
                                ? e($editStatistic['label'])
                                : '' ?>"
                        >

                        <div class="helper">
                            Main title displayed with the statistic.
                        </div>

                    </div>


                    <!-- VALUE -->

                    <div class="field">

                        <label for="value">
                            Value *
                        </label>

                        <input
                            type="text"
                            id="value"
                            name="value"
                            class="input"
                            maxlength="255"
                            required
                            placeholder="e.g. 13"
                            value="<?= $editStatistic
                                ? e($editStatistic['value'])
                                : '' ?>"
                        >

                        <div class="helper">
                            Numeric or text value such as 554, 13, 750.
                        </div>

                    </div>


                    <!-- PREFIX -->

                    <div class="field">

                        <label for="prefix">
                            Prefix
                        </label>

                        <input
                            type="text"
                            id="prefix"
                            name="prefix"
                            class="input"
                            maxlength="100"
                            placeholder="e.g. $"
                            value="<?= $editStatistic
                                ? e($editStatistic['prefix'])
                                : '' ?>"
                        >

                        <div class="helper">
                            Optional symbol shown before the value.
                        </div>

                    </div>


                    <!-- SUFFIX -->

                    <div class="field">

                        <label for="suffix">
                            Suffix
                        </label>

                        <input
                            type="text"
                            id="suffix"
                            name="suffix"
                            class="input"
                            maxlength="100"
                            placeholder="e.g. K+, M+, %"
                            value="<?= $editStatistic
                                ? e($editStatistic['suffix'])
                                : '' ?>"
                        >

                        <div class="helper">
                            Optional text/symbol shown after the value.
                        </div>

                    </div>


                    <!-- SECTION -->

                    <div class="field">

                        <label for="section_key">
                            Section Key
                        </label>

                        <input
                            type="text"
                            id="section_key"
                            name="section_key"
                            class="input"
                            maxlength="150"
                            placeholder="homepage_statistics"
                            value="<?= $editStatistic
                                ? e($editStatistic['section_key'])
                                : 'homepage_statistics' ?>"
                        >

                        <div class="helper">
                            Example:
                            <strong>homepage_statistics</strong>
                        </div>

                    </div>


                    <!-- SORT -->

                    <div class="field">

                        <label for="sort_order">
                            Sort Order
                        </label>

                        <input
                            type="number"
                            id="sort_order"
                            name="sort_order"
                            class="input"
                            min="0"
                            value="<?= $editStatistic
                                ? (int)$editStatistic['sort_order']
                                : 0 ?>"
                        >

                        <div class="helper">
                            Lower number appears first.
                        </div>

                    </div>


                    <!-- DESCRIPTION -->

                    <div class="field full">

                        <label for="description">
                            Description
                        </label>

                        <textarea
                            id="description"
                            name="description"
                            class="textarea"
                            maxlength="1000"
                            placeholder="Short explanation of this statistic..."
                        ><?= $editStatistic
                            ? e($editStatistic['description'])
                            : '' ?></textarea>

                        <div class="helper">
                            Optional internal/display description.
                        </div>

                    </div>


                    <!-- STATUS -->

                    <div class="field full">

                        <div class="switch-row">

                            <div class="switch-info">

                                <strong>
                                    Publish Statistic
                                </strong>

                                <span>
                                    Active statistics can be displayed
                                    on the frontend.
                                </span>

                            </div>


                            <label class="switch">

                                <input
                                    type="checkbox"
                                    name="status"
                                    value="1"
                                    <?= (!$editStatistic ||
                                        (int)$editStatistic['status'] === 1)
                                        ? 'checked'
                                        : '' ?>
                                >

                                <span class="slider"></span>

                            </label>

                        </div>

                    </div>

                </div>

            </div>


            <div class="modal-footer">

                <button
                    type="button"
                    class="btn btn-secondary"
                    onclick="closeModal()"
                >
                    Cancel
                </button>

                <button
                    type="submit"
                    class="btn btn-primary"
                >

                    <i class="fa-solid fa-check"></i>

                    <?= $editStatistic
                        ? 'Update Statistic'
                        : 'Save Statistic' ?>

                </button>

            </div>

        </form>

    </div>

</div>


<!-- =====================================================
     DELETE MODAL
===================================================== -->

<div
    class="modal"
    id="deleteModal"
>

    <div class="modal-card delete-modal-card">

        <div class="modal-body">

            <div class="delete-icon">
                <i class="fa-solid fa-trash"></i>
            </div>

            <h3 class="modal-title">
                Delete Statistic?
            </h3>

            <p
                style="
                    color:var(--muted);
                    font-size:13px;
                    line-height:1.6;
                    margin:8px 0 0;
                "
            >
                You are about to permanently delete
                <strong id="deleteStatisticName"></strong>.
                This action cannot be undone.
            </p>

        </div>


        <div class="modal-footer">

            <button
                type="button"
                class="btn btn-secondary"
                onclick="closeDeleteModal()"
            >
                Cancel
            </button>


            <form
                method="POST"
                style="display:inline;"
            >

                <?= csrf_field() ?>

                <input
                    type="hidden"
                    name="action"
                    value="delete"
                >

                <input
                    type="hidden"
                    name="id"
                    id="deleteStatisticId"
                    value=""
                >

                <button
                    type="submit"
                    class="btn btn-danger"
                >
                    <i class="fa-solid fa-trash"></i>
                    Delete
                </button>

            </form>

        </div>

    </div>

</div>


<!-- =====================================================
     HIDDEN STATUS FORM
===================================================== -->

<form
    method="POST"
    id="statusForm"
    style="display:none;"
>

    <?= csrf_field() ?>

    <input
        type="hidden"
        name="action"
        value="toggle_status"
    >

    <input
        type="hidden"
        name="id"
        id="statusStatisticId"
        value=""
    >

</form>


<script>

    const statisticModal =
        document.getElementById('statisticModal');

    const deleteModal =
        document.getElementById('deleteModal');


    /* -----------------------------------------------
       ADD
    ------------------------------------------------ */

    function openAddModal() {

        const url =
            new URL(window.location.href);

        url.searchParams.delete('edit');
        url.searchParams.delete('msg');
        url.searchParams.delete('msg_type');

        window.history.replaceState(
            {},
            '',
            url.toString()
        );

        statisticModal.classList.add('show');

        const form =
            statisticModal.querySelector('form');

        if (form) {

            const idInput =
                form.querySelector('input[name="id"]');

            if (idInput) {
                idInput.value = '0';
            }

            const label =
                form.querySelector('#label');

            const value =
                form.querySelector('#value');

            const prefix =
                form.querySelector('#prefix');

            const suffix =
                form.querySelector('#suffix');

            const section =
                form.querySelector('#section_key');

            const sort =
                form.querySelector('#sort_order');

            const description =
                form.querySelector('#description');

            const status =
                form.querySelector('input[name="status"]');

            if (label) label.value = '';
            if (value) value.value = '';
            if (prefix) prefix.value = '';
            if (suffix) suffix.value = '';

            if (section) {
                section.value =
                    'homepage_statistics';
            }

            if (sort) {
                sort.value = '0';
            }

            if (description) {
                description.value = '';
            }

            if (status) {
                status.checked = true;
            }
        }

        document.body.style.overflow = 'hidden';

        setTimeout(() => {

            const label =
                document.getElementById('label');

            if (label) {
                label.focus();
            }

        }, 100);

    }


    /* -----------------------------------------------
       CLOSE EDIT MODAL
    ------------------------------------------------ */

    function closeModal() {

        statisticModal.classList.remove('show');

        document.body.style.overflow = '';

        const url =
            new URL(window.location.href);

        url.searchParams.delete('edit');

        window.history.replaceState(
            {},
            '',
            url.toString()
        );
    }


    /* -----------------------------------------------
       DELETE
    ------------------------------------------------ */

    function openDeleteModal(id, name) {

        document.getElementById(
            'deleteStatisticId'
        ).value = id;

        document.getElementById(
            'deleteStatisticName'
        ).textContent = name;

        deleteModal.classList.add('show');

        document.body.style.overflow = 'hidden';
    }


    function closeDeleteModal() {

        deleteModal.classList.remove('show');

        document.body.style.overflow = '';

    }


    /* -----------------------------------------------
       TOGGLE STATUS
    ------------------------------------------------ */

    function toggleStatus(id) {

        if (!id) {
            return;
        }

        const form =
            document.getElementById('statusForm');

        document.getElementById(
            'statusStatisticId'
        ).value = id;

        form.submit();

    }


    /* -----------------------------------------------
       CLICK OUTSIDE
    ------------------------------------------------ */

    statisticModal.addEventListener(
        'click',
        function (event) {

            if (event.target === statisticModal) {
                closeModal();
            }

        }
    );


    deleteModal.addEventListener(
        'click',
        function (event) {

            if (event.target === deleteModal) {
                closeDeleteModal();
            }

        }
    );


    /* -----------------------------------------------
       ESC KEY
    ------------------------------------------------ */

    document.addEventListener(
        'keydown',
        function (event) {

            if (event.key !== 'Escape') {
                return;
            }

            if (
                statisticModal.classList.contains('show')
            ) {
                closeModal();
            }

            if (
                deleteModal.classList.contains('show')
            ) {
                closeDeleteModal();
            }

        }
    );

</script>

</body>
</html>