<?php
/**
 * Pure Chemical Admin
 * Social Links Management
 *
 * Existing table:
 * social_links
 *
 * Columns:
 * id
 * platform
 * label
 * url
 * icon
 * sort_order
 * status
 * created_at
 * updated_at
 */

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/includes/db.php';

if (file_exists(__DIR__ . '/includes/auth.php')) {
    require_once __DIR__ . '/includes/auth.php';
}

if (function_exists('requireAdmin')) {
    requireAdmin();
}

if (file_exists(__DIR__ . '/includes/csrf.php')) {
    require_once __DIR__ . '/includes/csrf.php';
}


/* =========================================================
   HELPERS
========================================================= */

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}


if (!function_exists('admin_csrf_token')) {
    function admin_csrf_token()
    {
        if (function_exists('csrf_token')) {
            return csrf_token();
        }

        if (empty($_SESSION['social_links_csrf'])) {
            $_SESSION['social_links_csrf'] = bin2hex(random_bytes(32));
        }

        return $_SESSION['social_links_csrf'];
    }
}


if (!function_exists('admin_csrf_field')) {
    function admin_csrf_field()
    {
        return '<input type="hidden" name="csrf_token" value="' .
            e(admin_csrf_token()) .
            '">';
    }
}


if (!function_exists('admin_verify_csrf')) {
    function admin_verify_csrf()
    {
        if (function_exists('csrf_verify')) {
            return csrf_verify();
        }

        $token = $_POST['csrf_token'] ?? '';

        if (
            empty($token) ||
            empty($_SESSION['social_links_csrf']) ||
            !hash_equals(
                $_SESSION['social_links_csrf'],
                $token
            )
        ) {
            return false;
        }

        return true;
    }
}


function redirectWithMessage($type, $message)
{
    $_SESSION['social_links_flash'] = [
        'type' => $type,
        'message' => $message
    ];

    header('Location: social_links.php');
    exit;
}


/* =========================================================
   FLASH
========================================================= */

$flash = $_SESSION['social_links_flash'] ?? null;
unset($_SESSION['social_links_flash']);


/* =========================================================
   POST ACTIONS
========================================================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!admin_verify_csrf()) {
        redirectWithMessage(
            'error',
            'Security verification failed. Please refresh the page and try again.'
        );
    }

    $formAction = $_POST['form_action'] ?? '';


    /* =====================================================
       SAVE
    ===================================================== */

    if ($formAction === 'save') {

        $id = (int)($_POST['id'] ?? 0);

        $platform = trim($_POST['platform'] ?? '');
        $label = trim($_POST['label'] ?? '');
        $url = trim($_POST['url'] ?? '');
        $icon = trim($_POST['icon'] ?? '');

        $sortOrder = (int)($_POST['sort_order'] ?? 0);
        $status = isset($_POST['status']) ? 1 : 0;


        /* -----------------------------------------------
           Validation
        ------------------------------------------------ */

        if ($platform === '') {
            redirectWithMessage(
                'error',
                'Platform name is required.'
            );
        }

        if (mb_strlen($platform) > 100) {
            redirectWithMessage(
                'error',
                'Platform name cannot exceed 100 characters.'
            );
        }


        if ($url === '') {
            redirectWithMessage(
                'error',
                'Social profile URL is required.'
            );
        }

        if (mb_strlen($url) > 1000) {
            redirectWithMessage(
                'error',
                'URL cannot exceed 1000 characters.'
            );
        }


        /*
         * Validate URL.
         *
         * http / https are accepted.
         * This avoids allowing arbitrary protocols such as
         * javascript: inside the admin URL field.
         */

        if (
            !filter_var($url, FILTER_VALIDATE_URL) ||
            !preg_match(
                '/^https?:\/\//i',
                $url
            )
        ) {
            redirectWithMessage(
                'error',
                'Please enter a valid HTTP or HTTPS URL.'
            );
        }


        if ($label !== '' && mb_strlen($label) > 150) {
            redirectWithMessage(
                'error',
                'Label cannot exceed 150 characters.'
            );
        }


        if ($icon !== '' && mb_strlen($icon) > 150) {
            redirectWithMessage(
                'error',
                'Icon class cannot exceed 150 characters.'
            );
        }


        /*
         * Duplicate platform check.
         *
         * Multiple records for the exact same platform are
         * usually unnecessary, so we prevent duplicates.
         */

        if ($id > 0) {

            $stmt = $pdo->prepare("
                SELECT id
                FROM social_links
                WHERE LOWER(platform) = LOWER(:platform)
                  AND id != :id
                LIMIT 1
            ");

            $stmt->execute([
                ':platform' => $platform,
                ':id' => $id
            ]);

        } else {

            $stmt = $pdo->prepare("
                SELECT id
                FROM social_links
                WHERE LOWER(platform) = LOWER(:platform)
                LIMIT 1
            ");

            $stmt->execute([
                ':platform' => $platform
            ]);
        }


        if ($stmt->fetch()) {
            redirectWithMessage(
                'error',
                'A social link for this platform already exists.'
            );
        }


        /* -----------------------------------------------
           Update
        ------------------------------------------------ */

        if ($id > 0) {

            $stmt = $pdo->prepare("
                UPDATE social_links
                SET
                    platform = :platform,
                    label = :label,
                    url = :url,
                    icon = :icon,
                    sort_order = :sort_order,
                    status = :status
                WHERE id = :id
                LIMIT 1
            ");

            $stmt->execute([
                ':platform' => $platform,
                ':label' => $label !== '' ? $label : null,
                ':url' => $url,
                ':icon' => $icon !== '' ? $icon : null,
                ':sort_order' => $sortOrder,
                ':status' => $status,
                ':id' => $id
            ]);

            redirectWithMessage(
                'success',
                'Social link updated successfully.'
            );
        }


        /* -----------------------------------------------
           Insert
        ------------------------------------------------ */

        $stmt = $pdo->prepare("
            INSERT INTO social_links
            (
                platform,
                label,
                url,
                icon,
                sort_order,
                status
            )
            VALUES
            (
                :platform,
                :label,
                :url,
                :icon,
                :sort_order,
                :status
            )
        ");

        $stmt->execute([
            ':platform' => $platform,
            ':label' => $label !== '' ? $label : null,
            ':url' => $url,
            ':icon' => $icon !== '' ? $icon : null,
            ':sort_order' => $sortOrder,
            ':status' => $status
        ]);

        redirectWithMessage(
            'success',
            'Social link created successfully.'
        );
    }


    /* =====================================================
       DELETE
    ===================================================== */

    if ($formAction === 'delete') {

        $id = (int)($_POST['id'] ?? 0);

        if ($id <= 0) {
            redirectWithMessage(
                'error',
                'Invalid social link selected.'
            );
        }


        $stmt = $pdo->prepare("
            DELETE FROM social_links
            WHERE id = :id
            LIMIT 1
        ");

        $stmt->execute([
            ':id' => $id
        ]);


        if ($stmt->rowCount() > 0) {

            redirectWithMessage(
                'success',
                'Social link deleted successfully.'
            );
        }


        redirectWithMessage(
            'error',
            'Social link could not be deleted.'
        );
    }


    /* =====================================================
       TOGGLE STATUS
    ===================================================== */

    if ($formAction === 'toggle_status') {

        $id = (int)($_POST['id'] ?? 0);

        if ($id <= 0) {
            redirectWithMessage(
                'error',
                'Invalid social link selected.'
            );
        }


        $stmt = $pdo->prepare("
            UPDATE social_links
            SET status = IF(status = 1, 0, 1)
            WHERE id = :id
            LIMIT 1
        ");

        $stmt->execute([
            ':id' => $id
        ]);


        redirectWithMessage(
            'success',
            'Social link status updated.'
        );
    }
}


/* =========================================================
   SEARCH
========================================================= */

$search = trim($_GET['search'] ?? '');

$where = [];
$params = [];


if ($search !== '') {

    $where[] = "
        (
            platform LIKE :search
            OR label LIKE :search
            OR url LIKE :search
            OR icon LIKE :search
        )
    ";

    $params[':search'] = '%' . $search . '%';
}


$whereSql = '';

if (!empty($where)) {
    $whereSql = 'WHERE ' . implode(' AND ', $where);
}


/* =========================================================
   STATISTICS
========================================================= */

$totalLinks = (int)$pdo
    ->query("
        SELECT COUNT(*)
        FROM social_links
    ")
    ->fetchColumn();


$activeLinks = (int)$pdo
    ->query("
        SELECT COUNT(*)
        FROM social_links
        WHERE status = 1
    ")
    ->fetchColumn();


$inactiveLinks = $totalLinks - $activeLinks;


$latestLinks = (int)$pdo
    ->query("
        SELECT COUNT(*)
        FROM social_links
        WHERE created_at >= DATE_SUB(
            NOW(),
            INTERVAL 30 DAY
        )
    ")
    ->fetchColumn();


/* =========================================================
   LIST
========================================================= */

$sql = "
    SELECT
        id,
        platform,
        label,
        url,
        icon,
        sort_order,
        status,
        created_at,
        updated_at
    FROM social_links
    {$whereSql}
    ORDER BY
        sort_order ASC,
        id DESC
";


$stmt = $pdo->prepare($sql);
$stmt->execute($params);

$links = $stmt->fetchAll();


/* =========================================================
   EDIT RECORD
========================================================= */

$editId = isset($_GET['edit'])
    ? (int)$_GET['edit']
    : 0;

$editLink = null;


if ($editId > 0) {

    $stmt = $pdo->prepare("
        SELECT
            id,
            platform,
            label,
            url,
            icon,
            sort_order,
            status
        FROM social_links
        WHERE id = :id
        LIMIT 1
    ");

    $stmt->execute([
        ':id' => $editId
    ]);

    $editLink = $stmt->fetch();


    if (!$editLink) {

        redirectWithMessage(
            'error',
            'Requested social link was not found.'
        );
    }
}


$isEdit = !empty($editLink);


$formPlatform = $editLink['platform'] ?? '';
$formLabel = $editLink['label'] ?? '';
$formUrl = $editLink['url'] ?? '';
$formIcon = $editLink['icon'] ?? '';
$formSortOrder = $editLink['sort_order'] ?? 0;

$formStatus = isset($editLink['status'])
    ? (int)$editLink['status']
    : 1;

?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>
        Social Links | Pure Chemical Admin
    </title>

    <meta
        name="theme-color"
        content="#0f766e"
    >

    <link
        rel="preconnect"
        href="https://fonts.googleapis.com"
    >

    <link
        rel="preconnect"
        href="https://fonts.gstatic.com"
        crossorigin
    >

    <link
        href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap"
        rel="stylesheet"
    >

    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
    >


    <style>

        :root {

            --pc-primary: #0f766e;
            --pc-primary-dark: #0b5f59;
            --pc-primary-soft: #e7f6f3;

            --pc-bg: #f5f7fb;
            --pc-card: #ffffff;

            --pc-text: #172033;
            --pc-muted: #6b7280;
            --pc-border: #e5e7eb;

            --pc-success: #15803d;
            --pc-success-bg: #ecfdf3;

            --pc-danger: #dc2626;
            --pc-danger-bg: #fef2f2;

            --pc-warning: #d97706;
            --pc-warning-bg: #fff7ed;

            --sidebar-width: 280px;

            --shadow-sm:
                0 1px 2px rgba(15, 23, 42, .04);

            --shadow-lg:
                0 20px 60px rgba(15, 23, 42, .13);

            --radius-lg: 18px;
            --radius-md: 12px;
        }


        * {
            box-sizing: border-box;
        }


        html {
            scroll-behavior: smooth;
        }


        body {

            margin: 0;
            padding: 0;

            background: var(--pc-bg);

            color: var(--pc-text);

            font-family:
                Inter,
                Arial,
                sans-serif;

            font-size: 14px;
        }


        button,
        input {
            font-family: inherit;
        }


        a {
            color: inherit;
            text-decoration: none;
        }


        /* =================================================
           LAYOUT
        ================================================= */

        .pc-main {

            min-height: 100vh;

            margin-left:
                var(--sidebar-width);
        }


        .pc-page {

            width: 100%;
            max-width: 1700px;

            margin: 0 auto;

            padding: 28px;
        }


        /* =================================================
           TOPBAR
        ================================================= */

        .pc-topbar {

            position: sticky;
            top: 0;

            z-index: 100;

            min-height: 76px;

            display: flex;
            align-items: center;
            justify-content: space-between;

            gap: 20px;

            padding:
                14px 28px;

            background:
                rgba(255, 255, 255, .88);

            border-bottom:
                1px solid rgba(226, 232, 240, .85);

            backdrop-filter:
                blur(18px);

            -webkit-backdrop-filter:
                blur(18px);
        }


        .topbar-left {

            display: flex;
            align-items: center;

            gap: 14px;

            min-width: 0;
        }


        .topbar-icon {

            width: 44px;
            height: 44px;

            flex: 0 0 auto;

            display: grid;
            place-items: center;

            color:
                var(--pc-primary);

            background:
                var(--pc-primary-soft);

            border:
                1px solid #ccece7;

            border-radius: 13px;

            font-size: 18px;
        }


        .topbar-eyebrow {

            margin-bottom: 3px;

            color:
                var(--pc-primary);

            font-size: 11px;

            font-weight: 800;

            text-transform:
                uppercase;

            letter-spacing:
                .11em;
        }


        .topbar-title {

            margin: 0;

            font-size: 20px;

            line-height: 1.2;

            font-weight: 800;
        }


        .topbar-subtitle {

            margin-top: 3px;

            color:
                var(--pc-muted);

            font-size: 12px;
        }


        .topbar-actions {

            display: flex;
            align-items: center;

            gap: 10px;
        }


        /* =================================================
           BUTTONS
        ================================================= */

        .btn {

            min-height: 42px;

            display: inline-flex;
            align-items: center;
            justify-content: center;

            gap: 8px;

            padding:
                0 15px;

            border:
                1px solid transparent;

            border-radius: 11px;

            font-size: 13px;

            font-weight: 700;

            cursor: pointer;

            transition:
                transform .18s ease,
                box-shadow .18s ease,
                background .18s ease;
        }


        .btn:hover {
            transform:
                translateY(-1px);
        }


        .btn-primary {

            color: #fff;

            background:
                linear-gradient(
                    135deg,
                    var(--pc-primary),
                    var(--pc-primary-dark)
                );

            box-shadow:
                0 8px 18px
                rgba(15, 118, 110, .22);
        }


        .btn-primary:hover {

            box-shadow:
                0 12px 24px
                rgba(15, 118, 110, .28);
        }


        .btn-light {

            color: #374151;

            background: #fff;

            border-color:
                var(--pc-border);
        }


        .btn-light:hover {
            background: #f8fafc;
        }


        .btn-danger {

            color:
                var(--pc-danger);

            background:
                var(--pc-danger-bg);

            border-color:
                #fecaca;
        }


        /* =================================================
           HERO
        ================================================= */

        .page-hero {

            position: relative;

            overflow: hidden;

            display: flex;
            align-items: flex-start;
            justify-content: space-between;

            gap: 24px;

            margin-bottom: 22px;

            padding: 25px;

            background:

                radial-gradient(
                    circle at 90% 10%,
                    rgba(15, 118, 110, .13),
                    transparent 30%
                ),

                #fff;

            border:
                1px solid var(--pc-border);

            border-radius:
                var(--radius-lg);

            box-shadow:
                var(--shadow-sm);
        }


        .hero-kicker {

            display: inline-flex;
            align-items: center;

            gap: 7px;

            margin-bottom: 9px;

            color:
                var(--pc-primary);

            font-size: 11px;

            font-weight: 800;

            text-transform:
                uppercase;

            letter-spacing:
                .1em;
        }


        .hero-title {

            margin: 0;

            font-size:
                clamp(24px, 3vw, 32px);

            line-height: 1.15;

            font-weight: 800;

            letter-spacing:
                -.035em;
        }


        .hero-description {

            max-width: 720px;

            margin:
                9px 0 0;

            color:
                var(--pc-muted);

            line-height: 1.7;
        }


        /* =================================================
           STATS
        ================================================= */

        .stats-grid {

            display: grid;

            grid-template-columns:
                repeat(4, minmax(0, 1fr));

            gap: 15px;

            margin-bottom: 22px;
        }


        .stat-card {

            display: flex;
            align-items: center;

            gap: 13px;

            padding: 17px;

            background: #fff;

            border:
                1px solid var(--pc-border);

            border-radius: 15px;

            box-shadow:
                var(--shadow-sm);
        }


        .stat-icon {

            width: 43px;
            height: 43px;

            flex: 0 0 auto;

            display: grid;
            place-items: center;

            color:
                var(--pc-primary);

            background:
                var(--pc-primary-soft);

            border-radius: 12px;
        }


        .stat-card:nth-child(2)
        .stat-icon {

            color:
                var(--pc-success);

            background:
                var(--pc-success-bg);
        }


        .stat-card:nth-child(3)
        .stat-icon {

            color:
                var(--pc-warning);

            background:
                var(--pc-warning-bg);
        }


        .stat-card:nth-child(4)
        .stat-icon {

            color:
                #4f46e5;

            background:
                #eef2ff;
        }


        .stat-label {

            margin-bottom: 4px;

            color:
                var(--pc-muted);

            font-size: 11px;

            font-weight: 700;

            text-transform:
                uppercase;

            letter-spacing:
                .06em;
        }


        .stat-value {

            font-size: 23px;

            line-height: 1;

            font-weight: 800;
        }


        /* =================================================
           CONTENT CARD
        ================================================= */

        .content-card {

            background: #fff;

            border:
                1px solid var(--pc-border);

            border-radius:
                var(--radius-lg);

            box-shadow:
                var(--shadow-sm);
        }


        .toolbar {

            display: flex;
            align-items: center;
            justify-content: space-between;

            gap: 15px;

            padding:
                17px 18px;

            border-bottom:
                1px solid var(--pc-border);
        }


        .search-form {

            display: flex;
            align-items: center;

            gap: 9px;

            flex: 1;

            max-width: 620px;
        }


        .search-box {

            position: relative;

            flex: 1;
        }


        .search-box i {

            position: absolute;

            left: 13px;
            top: 50%;

            transform:
                translateY(-50%);

            color:
                #9ca3af;
        }


        .form-control {

            width: 100%;

            min-height: 43px;

            padding:
                0 13px;

            color:
                var(--pc-text);

            background: #fff;

            border:
                1px solid #dbe1e8;

            border-radius: 11px;

            outline: none;

            transition:
                border-color .18s ease,
                box-shadow .18s ease;
        }


        .search-box .form-control {
            padding-left: 39px;
        }


        .form-control:focus {

            border-color:
                rgba(15, 118, 110, .65);

            box-shadow:
                0 0 0 4px
                rgba(15, 118, 110, .09);
        }


        /* =================================================
           TABLE
        ================================================= */

        .table-wrap {
            overflow-x: auto;
        }


        .social-table {

            width: 100%;

            min-width: 1000px;

            border-collapse:
                collapse;
        }


        .social-table th {

            padding:
                13px 18px;

            color:
                #64748b;

            background:
                #f8fafc;

            border-bottom:
                1px solid var(--pc-border);

            font-size: 11px;

            font-weight: 800;

            text-align: left;

            text-transform:
                uppercase;

            letter-spacing:
                .07em;

            white-space:
                nowrap;
        }


        .social-table td {

            padding:
                15px 18px;

            border-bottom:
                1px solid #edf0f3;

            vertical-align:
                middle;
        }


        .social-table tbody tr {

            transition:
                background .15s ease;
        }


        .social-table tbody tr:hover {
            background:
                #fbfdfd;
        }


        /* =================================================
           PLATFORM
        ================================================= */

        .platform-main {

            display: flex;
            align-items: center;

            gap: 12px;
        }


        .platform-icon {

            width: 44px;
            height: 44px;

            flex: 0 0 auto;

            display: grid;
            place-items: center;

            color:
                var(--pc-primary);

            background:
                linear-gradient(
                    145deg,
                    #ecfdf9,
                    #e0f2f1
                );

            border:
                1px solid #cdeae6;

            border-radius: 13px;

            font-size: 17px;
        }


        .platform-name {

            font-weight: 800;

            color:
                var(--pc-text);
        }


        .platform-id {

            margin-top: 3px;

            color:
                #9ca3af;

            font-size: 11px;
        }


        .label-text {

            color:
                #475569;

            font-weight: 600;
        }


        .url-box {

            display: inline-flex;
            align-items: center;

            gap: 7px;

            max-width: 330px;

            padding:
                7px 9px;

            color:
                #475569;

            background:
                #f8fafc;

            border:
                1px solid #e2e8f0;

            border-radius: 8px;

            font-size: 12px;
        }


        .url-box span {

            overflow: hidden;

            text-overflow:
                ellipsis;

            white-space:
                nowrap;
        }


        .url-box:hover {

            color:
                var(--pc-primary);

            border-color:
                #b9dfda;

            background:
                #f0fdfa;
        }


        .icon-code {

            display: inline-block;

            padding:
                6px 9px;

            color:
                #475569;

            background:
                #f8fafc;

            border:
                1px solid #e2e8f0;

            border-radius: 8px;

            font-family:
                Consolas,
                Monaco,
                monospace;

            font-size: 11px;

            max-width: 190px;

            overflow: hidden;

            text-overflow:
                ellipsis;

            white-space:
                nowrap;
        }


        /* =================================================
           STATUS
        ================================================= */

        .status-badge {

            display: inline-flex;
            align-items: center;

            gap: 6px;

            padding:
                6px 9px;

            border-radius:
                999px;

            font-size: 11px;

            font-weight: 800;
        }


        .status-badge::before {

            content: "";

            width: 6px;
            height: 6px;

            border-radius:
                50%;
        }


        .status-active {

            color:
                var(--pc-success);

            background:
                var(--pc-success-bg);
        }


        .status-active::before {
            background:
                var(--pc-success);
        }


        .status-inactive {

            color:
                #64748b;

            background:
                #f1f5f9;
        }


        .status-inactive::before {
            background:
                #94a3b8;
        }


        /* =================================================
           ACTIONS
        ================================================= */

        .row-actions {

            display: flex;
            align-items: center;
            justify-content: flex-end;

            gap: 7px;
        }


        .action-btn {

            width: 36px;
            height: 36px;

            display: grid;
            place-items: center;

            color:
                #64748b;

            background: #fff;

            border:
                1px solid #e2e8f0;

            border-radius: 9px;

            cursor: pointer;

            transition:
                all .17s ease;
        }


        .action-btn:hover {

            color:
                var(--pc-primary);

            border-color:
                #b9dfda;

            background:
                #f0fdfa;
        }


        .action-btn.danger:hover {

            color:
                var(--pc-danger);

            border-color:
                #fecaca;

            background:
                var(--pc-danger-bg);
        }


        .inline-form {
            display: inline;
            margin: 0;
        }


        /* =================================================
           EMPTY
        ================================================= */

        .empty-state {

            padding:
                65px 25px;

            text-align:
                center;
        }


        .empty-icon {

            width: 64px;
            height: 64px;

            margin:
                0 auto 15px;

            display: grid;
            place-items: center;

            color:
                var(--pc-primary);

            background:
                var(--pc-primary-soft);

            border-radius:
                18px;

            font-size: 25px;
        }


        .empty-title {

            margin: 0;

            font-size: 18px;

            font-weight: 800;
        }


        .empty-text {

            max-width: 480px;

            margin:
                7px auto 18px;

            color:
                var(--pc-muted);

            line-height: 1.6;
        }


        /* =================================================
           FOOTER
        ================================================= */

        .table-footer {

            display: flex;
            align-items: center;
            justify-content: space-between;

            gap: 15px;

            padding:
                15px 18px;

            color:
                var(--pc-muted);

            font-size: 12px;
        }


        /* =================================================
           FLASH
        ================================================= */

        .flash {

            position: fixed;

            top: 92px;
            right: 25px;

            z-index: 1000;

            width:
                min(
                    430px,
                    calc(100vw - 30px)
                );

            display: flex;
            align-items: flex-start;

            gap: 11px;

            padding:
                14px 15px;

            background: #fff;

            border:
                1px solid var(--pc-border);

            border-radius:
                13px;

            box-shadow:
                var(--shadow-lg);

            animation:
                flashIn .28s ease;
        }


        .flash.success {
            border-left:
                4px solid var(--pc-success);
        }


        .flash.error {
            border-left:
                4px solid var(--pc-danger);
        }


        .flash-icon {

            width: 31px;
            height: 31px;

            flex: 0 0 auto;

            display: grid;
            place-items: center;

            border-radius:
                9px;
        }


        .flash.success .flash-icon {

            color:
                var(--pc-success);

            background:
                var(--pc-success-bg);
        }


        .flash.error .flash-icon {

            color:
                var(--pc-danger);

            background:
                var(--pc-danger-bg);
        }


        .flash-message {

            flex: 1;

            color:
                #334155;

            font-size: 13px;

            line-height: 1.55;
        }


        .flash-close {

            padding: 4px;

            color:
                #94a3b8;

            background:
                transparent;

            border: 0;

            cursor: pointer;
        }


        @keyframes flashIn {

            from {
                opacity: 0;
                transform:
                    translateY(-8px);
            }

            to {
                opacity: 1;
                transform:
                    translateY(0);
            }
        }


        /* =================================================
           MODAL
        ================================================= */

        .modal-backdrop {

            position: fixed;

            inset: 0;

            z-index: 900;

            display: none;

            align-items: center;
            justify-content: center;

            padding: 20px;

            background:
                rgba(15, 23, 42, .55);

            backdrop-filter:
                blur(6px);

            -webkit-backdrop-filter:
                blur(6px);
        }


        .modal-backdrop.active {
            display: flex;
        }


        .modal {

            width:
                min(650px, 100%);

            max-height:
                calc(100vh - 40px);

            overflow-y:
                auto;

            background: #fff;

            border-radius:
                20px;

            box-shadow:
                var(--shadow-lg);

            animation:
                modalIn .2s ease;
        }


        @keyframes modalIn {

            from {
                opacity: 0;
                transform:
                    translateY(12px)
                    scale(.98);
            }

            to {
                opacity: 1;
                transform:
                    translateY(0)
                    scale(1);
            }
        }


        .modal-head {

            display: flex;
            align-items: flex-start;
            justify-content: space-between;

            gap: 15px;

            padding:
                20px 21px;

            border-bottom:
                1px solid var(--pc-border);
        }


        .modal-title {

            margin: 0;

            font-size: 18px;

            font-weight: 800;
        }


        .modal-description {

            margin:
                5px 0 0;

            color:
                var(--pc-muted);

            font-size: 12px;

            line-height: 1.5;
        }


        .modal-close {

            width: 34px;
            height: 34px;

            display: grid;
            place-items: center;

            color:
                #64748b;

            background:
                #f8fafc;

            border:
                1px solid #e2e8f0;

            border-radius:
                9px;

            cursor: pointer;
        }


        .modal-body {
            padding: 21px;
        }


        .modal-footer {

            display: flex;
            justify-content: flex-end;

            gap: 9px;

            padding:
                15px 21px;

            border-top:
                1px solid var(--pc-border);

            background:
                #fafafa;
        }


        /* =================================================
           FORM
        ================================================= */

        .form-group {
            margin-bottom: 17px;
        }


        .form-group:last-child {
            margin-bottom: 0;
        }


        .form-label {

            display: block;

            margin-bottom: 7px;

            color:
                #334155;

            font-size: 12px;

            font-weight: 800;
        }


        .required {
            color:
                var(--pc-danger);
        }


        .form-help {

            margin-top: 6px;

            color:
                #94a3b8;

            font-size: 11px;

            line-height: 1.5;
        }


        .form-row {

            display: grid;

            grid-template-columns:
                minmax(0, 1fr)
                minmax(0, 1fr);

            gap: 13px;
        }


        .icon-preview-wrap {

            display: flex;
            align-items: center;

            gap: 10px;
        }


        .icon-preview {

            width: 43px;
            height: 43px;

            flex: 0 0 auto;

            display: grid;
            place-items: center;

            color:
                var(--pc-primary);

            background:
                var(--pc-primary-soft);

            border:
                1px solid #ccece7;

            border-radius:
                11px;

            font-size: 17px;
        }


        .checkbox-wrap {

            display: flex;
            align-items: center;

            gap: 10px;

            min-height: 43px;

            padding:
                0 12px;

            background:
                #f8fafc;

            border:
                1px solid #e2e8f0;

            border-radius:
                11px;
        }


        .checkbox-wrap input {

            width: 17px;
            height: 17px;

            accent-color:
                var(--pc-primary);
        }


        .checkbox-label {

            color:
                #475569;

            font-size: 13px;

            font-weight: 600;
        }


        /* =================================================
           DELETE MODAL
        ================================================= */

        .delete-modal {
            width:
                min(440px, 100%);
        }


        .delete-content {

            padding:
                28px 24px;

            text-align:
                center;
        }


        .delete-icon {

            width: 54px;
            height: 54px;

            margin:
                0 auto 14px;

            display: grid;
            place-items: center;

            color:
                var(--pc-danger);

            background:
                var(--pc-danger-bg);

            border-radius:
                16px;

            font-size: 21px;
        }


        .delete-title {

            margin: 0;

            font-size: 19px;

            font-weight: 800;
        }


        .delete-text {

            margin:
                8px auto 0;

            color:
                var(--pc-muted);

            line-height: 1.6;
        }


        /* =================================================
           RESPONSIVE
        ================================================= */

        @media (max-width: 1200px) {

            .stats-grid {

                grid-template-columns:
                    repeat(2, minmax(0, 1fr));
            }

        }


        @media (max-width: 1100px) {

            .pc-main {
                margin-left: 0;
            }

        }


        @media (max-width: 760px) {

            .pc-page {
                padding: 17px;
            }


            .pc-topbar {
                padding:
                    12px 17px;
            }


            .topbar-subtitle {
                display: none;
            }


            .topbar-actions .btn-light {
                display: none;
            }


            .page-hero {
                padding: 20px;
            }


            .stats-grid {

                grid-template-columns:
                    1fr 1fr;

                gap: 10px;
            }


            .stat-card {
                padding: 13px;
            }


            .stat-icon {

                width: 38px;
                height: 38px;
            }


            .stat-value {
                font-size: 19px;
            }


            .toolbar {

                align-items: stretch;

                flex-direction: column;
            }


            .search-form {
                max-width: none;
            }


            .form-row {
                grid-template-columns: 1fr;
            }

        }


        @media (max-width: 480px) {

            .topbar-title {
                font-size: 17px;
            }


            .topbar-icon {

                width: 38px;
                height: 38px;
            }


            .topbar-actions .btn-primary {

                width: 42px;

                padding: 0;

                font-size: 0;
            }


            .topbar-actions
            .btn-primary i {
                font-size: 14px;
            }


            .stats-grid {
                grid-template-columns:
                    1fr 1fr;
            }


            .stat-card {

                gap: 9px;
            }


            .stat-label {
                font-size: 9px;
            }


            .table-footer {

                align-items: flex-start;

                flex-direction: column;
            }

        }

    </style>

</head>


<body>


<?php
/*
|--------------------------------------------------------------------------
| Sidebar
|--------------------------------------------------------------------------
| Existing admin/sidebar.php is included separately.
| No admin/header.php is included here.
|--------------------------------------------------------------------------
*/

require_once __DIR__ . '/sidebar.php';
?>


<main class="pc-main">


    <!-- =====================================================
         TOPBAR
    ====================================================== -->

    <header class="pc-topbar">

        <div class="topbar-left">

            <div class="topbar-icon">
                <i class="fa-solid fa-share-nodes"></i>
            </div>

            <div>

                <div class="topbar-eyebrow">
                    Website Configuration
                </div>

                <h1 class="topbar-title">
                    Social Links
                </h1>

                <div class="topbar-subtitle">
                    Manage website social media profiles and links.
                </div>

            </div>

        </div>


        <div class="topbar-actions">

            <a
                href="social_links.php"
                class="btn btn-light"
            >
                <i class="fa-solid fa-rotate"></i>
                Refresh
            </a>


            <button
                type="button"
                class="btn btn-primary"
                onclick="openSocialModal()"
            >
                <i class="fa-solid fa-plus"></i>
                Add Social Link
            </button>

        </div>

    </header>


    <div class="pc-page">


        <!-- =================================================
             HERO
        ================================================== -->

        <section class="page-hero">

            <div>

                <div class="hero-kicker">
                    <i class="fa-solid fa-share-nodes"></i>
                    Social Presence
                </div>


                <h2 class="hero-title">
                    Manage Social Links
                </h2>


                <p class="hero-description">
                    Keep all official social media profiles in one
                    place. These links can be consumed directly by
                    your website header, footer or social sections.
                </p>

            </div>

        </section>


        <!-- =================================================
             STATS
        ================================================== -->

        <section class="stats-grid">


            <div class="stat-card">

                <div class="stat-icon">
                    <i class="fa-solid fa-share-nodes"></i>
                </div>

                <div>

                    <div class="stat-label">
                        Total Links
                    </div>

                    <div class="stat-value">
                        <?= number_format($totalLinks) ?>
                    </div>

                </div>

            </div>


            <div class="stat-card">

                <div class="stat-icon">
                    <i class="fa-solid fa-circle-check"></i>
                </div>

                <div>

                    <div class="stat-label">
                        Active
                    </div>

                    <div class="stat-value">
                        <?= number_format($activeLinks) ?>
                    </div>

                </div>

            </div>


            <div class="stat-card">

                <div class="stat-icon">
                    <i class="fa-solid fa-circle-pause"></i>
                </div>

                <div>

                    <div class="stat-label">
                        Inactive
                    </div>

                    <div class="stat-value">
                        <?= number_format($inactiveLinks) ?>
                    </div>

                </div>

            </div>


            <div class="stat-card">

                <div class="stat-icon">
                    <i class="fa-solid fa-calendar-plus"></i>
                </div>

                <div>

                    <div class="stat-label">
                        Added 30 Days
                    </div>

                    <div class="stat-value">
                        <?= number_format($latestLinks) ?>
                    </div>

                </div>

            </div>


        </section>


        <!-- =================================================
             CONTENT
        ================================================== -->

        <section class="content-card">


            <div class="toolbar">


                <form
                    method="get"
                    action="social_links.php"
                    class="search-form"
                >

                    <div class="search-box">

                        <i class="fa-solid fa-magnifying-glass"></i>

                        <input
                            type="search"
                            name="search"
                            class="form-control"
                            value="<?= e($search) ?>"
                            placeholder="Search platform, label, URL or icon..."
                        >

                    </div>


                    <button
                        type="submit"
                        class="btn btn-light"
                    >
                        Search
                    </button>


                    <?php if ($search !== ''): ?>

                        <a
                            href="social_links.php"
                            class="btn btn-light"
                            title="Clear search"
                        >
                            <i class="fa-solid fa-xmark"></i>
                        </a>

                    <?php endif; ?>


                </form>


                <button
                    type="button"
                    class="btn btn-primary"
                    onclick="openSocialModal()"
                >
                    <i class="fa-solid fa-plus"></i>
                    New Link
                </button>


            </div>


            <?php if (!empty($links)): ?>


                <div class="table-wrap">

                    <table class="social-table">

                        <thead>

                            <tr>

                                <th>
                                    Platform
                                </th>

                                <th>
                                    Label
                                </th>

                                <th>
                                    URL
                                </th>

                                <th>
                                    Icon
                                </th>

                                <th>
                                    Order
                                </th>

                                <th>
                                    Status
                                </th>

                                <th style="text-align:right;">
                                    Actions
                                </th>

                            </tr>

                        </thead>


                        <tbody>


                        <?php foreach ($links as $link): ?>


                            <tr>


                                <!-- PLATFORM -->

                                <td>

                                    <div class="platform-main">

                                        <div class="platform-icon">

                                            <?php if (!empty($link['icon'])): ?>

                                                <i
                                                    class="<?= e($link['icon']) ?>"
                                                ></i>

                                            <?php else: ?>

                                                <i class="fa-solid fa-share-nodes"></i>

                                            <?php endif; ?>

                                        </div>


                                        <div>

                                            <div class="platform-name">
                                                <?= e($link['platform']) ?>
                                            </div>

                                            <div class="platform-id">
                                                ID #<?= (int)$link['id'] ?>
                                            </div>

                                        </div>

                                    </div>

                                </td>


                                <!-- LABEL -->

                                <td>

                                    <?php if (!empty($link['label'])): ?>

                                        <span class="label-text">
                                            <?= e($link['label']) ?>
                                        </span>

                                    <?php else: ?>

                                        <span style="color:#9ca3af;">
                                            —
                                        </span>

                                    <?php endif; ?>

                                </td>


                                <!-- URL -->

                                <td>

                                    <a
                                        href="<?= e($link['url']) ?>"
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        class="url-box"
                                        title="<?= e($link['url']) ?>"
                                    >

                                        <i class="fa-solid fa-arrow-up-right-from-square"></i>

                                        <span>
                                            <?= e($link['url']) ?>
                                        </span>

                                    </a>

                                </td>


                                <!-- ICON -->

                                <td>

                                    <?php if (!empty($link['icon'])): ?>

                                        <span class="icon-code">
                                            <?= e($link['icon']) ?>
                                        </span>

                                    <?php else: ?>

                                        <span style="color:#9ca3af;">
                                            —
                                        </span>

                                    <?php endif; ?>

                                </td>


                                <!-- ORDER -->

                                <td>

                                    <strong>
                                        <?= (int)$link['sort_order'] ?>
                                    </strong>

                                </td>


                                <!-- STATUS -->

                                <td>

                                    <?php if ((int)$link['status'] === 1): ?>

                                        <span class="status-badge status-active">
                                            Active
                                        </span>

                                    <?php else: ?>

                                        <span class="status-badge status-inactive">
                                            Inactive
                                        </span>

                                    <?php endif; ?>

                                </td>


                                <!-- ACTIONS -->

                                <td>

                                    <div class="row-actions">


                                        <!-- EDIT -->

                                        <a
                                            href="social_links.php?edit=<?= (int)$link['id'] ?>"
                                            class="action-btn"
                                            title="Edit"
                                        >

                                            <i class="fa-solid fa-pen"></i>

                                        </a>


                                        <!-- STATUS -->

                                        <form
                                            method="post"
                                            class="inline-form"
                                        >

                                            <?= admin_csrf_field() ?>

                                            <input
                                                type="hidden"
                                                name="form_action"
                                                value="toggle_status"
                                            >

                                            <input
                                                type="hidden"
                                                name="id"
                                                value="<?= (int)$link['id'] ?>"
                                            >


                                            <button
                                                type="submit"
                                                class="action-btn"
                                                title="Toggle status"
                                            >

                                                <?php if ((int)$link['status'] === 1): ?>

                                                    <i class="fa-solid fa-toggle-on"></i>

                                                <?php else: ?>

                                                    <i class="fa-solid fa-toggle-off"></i>

                                                <?php endif; ?>

                                            </button>

                                        </form>


                                        <!-- DELETE -->

                                        <button
                                            type="button"
                                            class="action-btn danger"
                                            title="Delete"
                                            onclick="openDeleteModal(
                                                <?= (int)$link['id'] ?>,
                                                <?= htmlspecialchars(
                                                    json_encode($link['platform']),
                                                    ENT_QUOTES,
                                                    'UTF-8'
                                                ) ?>
                                            )"
                                        >

                                            <i class="fa-solid fa-trash"></i>

                                        </button>


                                    </div>

                                </td>


                            </tr>


                        <?php endforeach; ?>


                        </tbody>

                    </table>

                </div>


                <div class="table-footer">

                    <div>

                        Showing
                        <strong>
                            <?= count($links) ?>
                        </strong>

                        social link<?= count($links) !== 1 ? 's' : '' ?>

                        <?php if ($search !== ''): ?>

                            for

                            <strong>
                                "<?= e($search) ?>"
                            </strong>

                        <?php endif; ?>

                    </div>


                    <div>
                        Sorted by
                        <strong>Sort Order</strong>
                    </div>

                </div>


            <?php else: ?>


                <div class="empty-state">

                    <div class="empty-icon">
                        <i class="fa-solid fa-share-nodes"></i>
                    </div>


                    <h3 class="empty-title">
                        No Social Links Found
                    </h3>


                    <p class="empty-text">

                        <?php if ($search !== ''): ?>

                            No social link matches
                            <strong>
                                "<?= e($search) ?>"
                            </strong>.
                            Try another search.

                        <?php else: ?>

                            No social media profiles have been
                            added yet. Add your first social link
                            to make it available across the website.

                        <?php endif; ?>

                    </p>


                    <?php if ($search !== ''): ?>

                        <a
                            href="social_links.php"
                            class="btn btn-light"
                        >
                            <i class="fa-solid fa-arrow-left"></i>
                            Clear Search
                        </a>

                    <?php else: ?>

                        <button
                            type="button"
                            class="btn btn-primary"
                            onclick="openSocialModal()"
                        >
                            <i class="fa-solid fa-plus"></i>
                            Add First Social Link
                        </button>

                    <?php endif; ?>


                </div>


            <?php endif; ?>


        </section>


    </div>

</main>


<!-- =========================================================
     ADD / EDIT MODAL
========================================================== -->

<div
    class="modal-backdrop <?= $isEdit ? 'active' : '' ?>"
    id="socialModal"
>


    <div
        class="modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="socialModalTitle"
    >


        <form
            method="post"
            action="social_links.php"
        >

            <?= admin_csrf_field() ?>


            <input
                type="hidden"
                name="form_action"
                value="save"
            >


            <input
                type="hidden"
                name="id"
                value="<?= $isEdit ? (int)$editLink['id'] : 0 ?>"
            >


            <div class="modal-head">

                <div>

                    <h3
                        class="modal-title"
                        id="socialModalTitle"
                    >
                        <?= $isEdit
                            ? 'Edit Social Link'
                            : 'Add Social Link'
                        ?>
                    </h3>


                    <p class="modal-description">

                        <?= $isEdit
                            ? 'Update the selected social media profile.'
                            : 'Add a social media profile to your website.'
                        ?>

                    </p>

                </div>


                <button
                    type="button"
                    class="modal-close"
                    onclick="closeSocialModal()"
                    aria-label="Close"
                >

                    <i class="fa-solid fa-xmark"></i>

                </button>

            </div>


            <div class="modal-body">


                <!-- PLATFORM + LABEL -->

                <div class="form-row">


                    <div class="form-group">

                        <label class="form-label">

                            Platform
                            <span class="required">*</span>

                        </label>


                        <input
                            type="text"
                            name="platform"
                            id="platformInput"
                            class="form-control"
                            maxlength="100"
                            value="<?= e($formPlatform) ?>"
                            placeholder="e.g. Facebook"
                            required
                        >


                        <div class="form-help">
                            Example: Facebook, Instagram, LinkedIn,
                            YouTube, X.
                        </div>

                    </div>


                    <div class="form-group">

                        <label class="form-label">
                            Label
                        </label>


                        <input
                            type="text"
                            name="label"
                            class="form-control"
                            maxlength="150"
                            value="<?= e($formLabel) ?>"
                            placeholder="e.g. Follow us on Facebook"
                        >


                        <div class="form-help">
                            Optional text displayed beside the social icon.
                        </div>

                    </div>


                </div>


                <!-- URL -->

                <div class="form-group">

                    <label class="form-label">

                        Profile URL
                        <span class="required">*</span>

                    </label>


                    <input
                        type="url"
                        name="url"
                        class="form-control"
                        maxlength="1000"
                        value="<?= e($formUrl) ?>"
                        placeholder="https://www.example.com/your-profile"
                        required
                    >


                    <div class="form-help">
                        Use the complete HTTP or HTTPS profile URL.
                    </div>

                </div>


                <!-- ICON -->

                <div class="form-group">

                    <label class="form-label">
                        Font Awesome Icon Class
                    </label>


                    <div class="icon-preview-wrap">

                        <div
                            class="icon-preview"
                            id="iconPreview"
                        >

                            <?php if ($formIcon !== ''): ?>

                                <i
                                    id="previewIcon"
                                    class="<?= e($formIcon) ?>"
                                ></i>

                            <?php else: ?>

                                <i
                                    id="previewIcon"
                                    class="fa-solid fa-share-nodes"
                                ></i>

                            <?php endif; ?>

                        </div>


                        <input
                            type="text"
                            name="icon"
                            id="iconInput"
                            class="form-control"
                            maxlength="150"
                            value="<?= e($formIcon) ?>"
                            placeholder="fa-brands fa-facebook"
                        >

                    </div>


                    <div class="form-help">
                        Example:
                        <strong>fa-brands fa-facebook</strong>
                        or
                        <strong>fa-brands fa-linkedin</strong>.
                    </div>

                </div>


                <!-- ORDER + STATUS -->

                <div class="form-row">


                    <div class="form-group">

                        <label class="form-label">
                            Sort Order
                        </label>


                        <input
                            type="number"
                            name="sort_order"
                            class="form-control"
                            min="0"
                            step="1"
                            value="<?= (int)$formSortOrder ?>"
                        >


                        <div class="form-help">
                            Lower numbers appear first.
                        </div>

                    </div>


                    <div class="form-group">

                        <label class="form-label">
                            Status
                        </label>


                        <label class="checkbox-wrap">

                            <input
                                type="checkbox"
                                name="status"
                                value="1"
                                <?= $formStatus === 1 ? 'checked' : '' ?>
                            >


                            <span class="checkbox-label">
                                Active social link
                            </span>

                        </label>


                        <div class="form-help">
                            Only active links should normally be displayed
                            on the frontend.
                        </div>

                    </div>


                </div>


            </div>


            <div class="modal-footer">


                <button
                    type="button"
                    class="btn btn-light"
                    onclick="closeSocialModal()"
                >
                    Cancel
                </button>


                <button
                    type="submit"
                    class="btn btn-primary"
                >

                    <i class="fa-solid fa-check"></i>

                    <?= $isEdit
                        ? 'Update Social Link'
                        : 'Create Social Link'
                    ?>

                </button>


            </div>


        </form>


    </div>

</div>


<!-- =========================================================
     DELETE MODAL
========================================================== -->

<div
    class="modal-backdrop"
    id="deleteModal"
>


    <div class="modal delete-modal">


        <div class="delete-content">


            <div class="delete-icon">

                <i class="fa-solid fa-trash"></i>

            </div>


            <h3 class="delete-title">
                Delete Social Link?
            </h3>


            <p class="delete-text">

                You are about to delete
                <strong id="deleteLinkName"></strong>.

                This action cannot be undone.

            </p>


        </div>


        <form
            method="post"
            action="social_links.php"
        >

            <?= admin_csrf_field() ?>


            <input
                type="hidden"
                name="form_action"
                value="delete"
            >


            <input
                type="hidden"
                name="id"
                id="deleteLinkId"
                value=""
            >


            <div class="modal-footer">


                <button
                    type="button"
                    class="btn btn-light"
                    onclick="closeDeleteModal()"
                >
                    Cancel
                </button>


                <button
                    type="submit"
                    class="btn btn-danger"
                >

                    <i class="fa-solid fa-trash"></i>

                    Delete Link

                </button>


            </div>


        </form>


    </div>

</div>


<!-- =========================================================
     FLASH MESSAGE
========================================================== -->

<?php if ($flash): ?>


    <div
        class="flash <?= $flash['type'] === 'success'
            ? 'success'
            : 'error' ?>"
        id="flashMessage"
    >


        <div class="flash-icon">

            <?php if ($flash['type'] === 'success'): ?>

                <i class="fa-solid fa-check"></i>

            <?php else: ?>

                <i class="fa-solid fa-triangle-exclamation"></i>

            <?php endif; ?>

        </div>


        <div class="flash-message">

            <?= e($flash['message']) ?>

        </div>


        <button
            type="button"
            class="flash-close"
            onclick="closeFlash()"
        >

            <i class="fa-solid fa-xmark"></i>

        </button>


    </div>


<?php endif; ?>


<script>

    /* ========================================================
       ELEMENTS
    ======================================================== */

    const socialModal =
        document.getElementById('socialModal');

    const deleteModal =
        document.getElementById('deleteModal');


    /* ========================================================
       OPEN ADD / EDIT
    ======================================================== */

    function openSocialModal() {

        if (!socialModal) {
            return;
        }


        socialModal.classList.add('active');

        document.body.style.overflow = 'hidden';


        setTimeout(function () {

            const platform =
                document.getElementById('platformInput');

            if (platform) {
                platform.focus();
            }

        }, 100);

    }


    /* ========================================================
       CLOSE ADD / EDIT
    ======================================================== */

    function closeSocialModal() {

        if (!socialModal) {
            return;
        }


        socialModal.classList.remove('active');

        document.body.style.overflow = '';


        <?php if ($isEdit): ?>

        setTimeout(function () {

            window.location.href =
                'social_links.php';

        }, 120);

        <?php endif; ?>

    }


    /* ========================================================
       DELETE
    ======================================================== */

    function openDeleteModal(id, name) {

        if (!deleteModal) {
            return;
        }


        const idInput =
            document.getElementById('deleteLinkId');

        const nameElement =
            document.getElementById('deleteLinkName');


        if (idInput) {
            idInput.value = id;
        }


        if (nameElement) {
            nameElement.textContent = name;
        }


        deleteModal.classList.add('active');

        document.body.style.overflow = 'hidden';

    }


    function closeDeleteModal() {

        if (!deleteModal) {
            return;
        }


        deleteModal.classList.remove('active');

        document.body.style.overflow = '';

    }


    /* ========================================================
       ICON PREVIEW
    ======================================================== */

    const iconInput =
        document.getElementById('iconInput');

    const previewIcon =
        document.getElementById('previewIcon');


    if (iconInput && previewIcon) {

        iconInput.addEventListener(
            'input',
            function () {

                const value =
                    this.value.trim();


                if (value === '') {

                    previewIcon.className =
                        'fa-solid fa-share-nodes';

                    return;
                }


                previewIcon.className =
                    value;

            }
        );

    }


    /* ========================================================
       ESCAPE
    ======================================================== */

    document.addEventListener(
        'keydown',
        function (event) {

            if (event.key !== 'Escape') {
                return;
            }


            if (
                socialModal &&
                socialModal.classList.contains('active')
            ) {

                closeSocialModal();

            }


            if (
                deleteModal &&
                deleteModal.classList.contains('active')
            ) {

                closeDeleteModal();

            }

        }
    );


    /* ========================================================
       OUTSIDE CLICK
    ======================================================== */

    if (socialModal) {

        socialModal.addEventListener(
            'click',
            function (event) {

                if (event.target === socialModal) {
                    closeSocialModal();
                }

            }
        );

    }


    if (deleteModal) {

        deleteModal.addEventListener(
            'click',
            function (event) {

                if (event.target === deleteModal) {
                    closeDeleteModal();
                }

            }
        );

    }


    /* ========================================================
       FLASH
    ======================================================== */

    function closeFlash() {

        const flash =
            document.getElementById('flashMessage');


        if (!flash) {
            return;
        }


        flash.style.opacity = '0';

        flash.style.transform =
            'translateY(-8px)';


        setTimeout(function () {

            flash.remove();

        }, 200);

    }


    <?php if ($flash && $flash['type'] === 'success'): ?>

    setTimeout(function () {

        closeFlash();

    }, 4500);

    <?php endif; ?>


    /* ========================================================
       BODY OVERFLOW SAFETY
    ======================================================== */

    window.addEventListener(
        'beforeunload',
        function () {

            document.body.style.overflow = '';

        }
    );

</script>


</body>
</html>