<?php
/**
 * Pure Chemical Admin
 * File: admin/pages.php
 *
 * Existing table:
 * pages
 *
 * No new table is created.
 */

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/includes/db.php';

if (file_exists(__DIR__ . '/includes/auth.php')) {
    require_once __DIR__ . '/includes/auth.php';
}

if (file_exists(__DIR__ . '/includes/csrf.php')) {
    require_once __DIR__ . '/includes/csrf.php';
}

if (file_exists(__DIR__ . '/includes/functions.php')) {
    require_once __DIR__ . '/includes/functions.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_field')) {
    function csrf_field()
    {
        if (function_exists('csrf_token')) {
            $token = csrf_token();
        } elseif (function_exists('generateCsrfToken')) {
            $token = generateCsrfToken();
        } else {
            if (empty($_SESSION['_csrf_token'])) {
                $_SESSION['_csrf_token'] = bin2hex(random_bytes(32));
            }

            $token = $_SESSION['_csrf_token'];
        }

        return '<input type="hidden" name="csrf_token" value="' . e($token) . '">';
    }
}

if (!function_exists('verify_local_csrf')) {
    function verify_local_csrf()
    {
        if (function_exists('csrf_verify')) {
            csrf_verify();
            return;
        }

        if (function_exists('verifyCsrfToken')) {
            verifyCsrfToken();
            return;
        }

        $sessionToken = $_SESSION['_csrf_token'] ?? '';
        $postedToken  = $_POST['csrf_token'] ?? '';

        if (
            !$sessionToken ||
            !$postedToken ||
            !hash_equals($sessionToken, $postedToken)
        ) {
            http_response_code(419);
            exit('Invalid CSRF token.');
        }
    }
}

if (!function_exists('page_slugify')) {
    function page_slugify($text)
    {
        $text = trim((string)$text);

        if ($text === '') {
            return '';
        }

        if (function_exists('iconv')) {
            $converted = @iconv(
                'UTF-8',
                'ASCII//TRANSLIT//IGNORE',
                $text
            );

            if ($converted !== false) {
                $text = $converted;
            }
        }

        $text = strtolower($text);

        $text = preg_replace('/[^a-z0-9]+/', '-', $text);
        $text = trim($text, '-');

        return $text ?: 'page';
    }
}

if (!function_exists('redirect_pages')) {
    function redirect_pages($params = [])
    {
        $url = basename($_SERVER['PHP_SELF']);

        if (!empty($params)) {
            $url .= '?' . http_build_query($params);
        }

        header('Location: ' . $url);
        exit;
    }
}

if (!function_exists('format_page_date')) {
    function format_page_date($date)
    {
        if (!$date) {
            return '—';
        }

        $time = strtotime($date);

        if (!$time) {
            return e($date);
        }

        return date('d M Y, h:i A', $time);
    }
}

/* =========================================================
   FLASH
========================================================= */

$flashSuccess = $_SESSION['pages_success'] ?? '';
$flashError   = $_SESSION['pages_error'] ?? '';

unset(
    $_SESSION['pages_success'],
    $_SESSION['pages_error']
);

/* =========================================================
   POST ACTIONS
========================================================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    verify_local_csrf();

    $action = $_POST['action'] ?? '';

    /* =====================================================
       SAVE PAGE
    ===================================================== */

    if ($action === 'save') {

        $id = (int)($_POST['id'] ?? 0);

        $title = trim($_POST['title'] ?? '');
        $slug  = trim($_POST['slug'] ?? '');

        $parentId = isset($_POST['parent_id']) &&
                    $_POST['parent_id'] !== ''
            ? (int)$_POST['parent_id']
            : null;

        $pageType = trim($_POST['page_type'] ?? 'standard');
        $template = trim($_POST['template'] ?? 'default');

        $excerpt = trim($_POST['excerpt'] ?? '');
        $content = $_POST['content'] ?? '';

        $featuredMediaId =
            isset($_POST['featured_media_id']) &&
            $_POST['featured_media_id'] !== ''
                ? (int)$_POST['featured_media_id']
                : null;

        $status = $_POST['status'] ?? 'draft';

        $sortOrder = (int)($_POST['sort_order'] ?? 0);

        $publishedAt = trim($_POST['published_at'] ?? '');

        if ($title === '') {
            $_SESSION['pages_error'] = 'Page title is required.';
            redirect_pages($id > 0 ? ['edit' => $id] : []);
        }

        if ($slug === '') {
            $slug = page_slugify($title);
        } else {
            $slug = page_slugify($slug);
        }

        if ($slug === '') {
            $_SESSION['pages_error'] = 'Please provide a valid page slug.';
            redirect_pages($id > 0 ? ['edit' => $id] : []);
        }

        if ($pageType === '') {
            $pageType = 'standard';
        }

        if ($template === '') {
            $template = 'default';
        }

        $allowedStatuses = [
            'draft',
            'published',
            'inactive'
        ];

        if (!in_array($status, $allowedStatuses, true)) {
            $status = 'draft';
        }

        if ($sortOrder < 0) {
            $sortOrder = 0;
        }

        /* -------------------------------------------------
           Parent validation
        ------------------------------------------------- */

        if ($parentId !== null) {

            if ($id > 0 && $parentId === $id) {

                $_SESSION['pages_error'] =
                    'A page cannot be its own parent.';

                redirect_pages(['edit' => $id]);
            }

            $stmt = $pdo->prepare("
                SELECT id
                FROM pages
                WHERE id = ?
                LIMIT 1
            ");

            $stmt->execute([$parentId]);

            if (!$stmt->fetchColumn()) {
                $parentId = null;
            }
        }

        /* -------------------------------------------------
           Circular hierarchy prevention
        ------------------------------------------------- */

        if ($id > 0 && $parentId !== null) {

            $checkParent = $parentId;
            $visited = [];
            $circular = false;

            while ($checkParent !== null) {

                if (isset($visited[$checkParent])) {
                    break;
                }

                $visited[$checkParent] = true;

                if ($checkParent === $id) {
                    $circular = true;
                    break;
                }

                $stmt = $pdo->prepare("
                    SELECT parent_id
                    FROM pages
                    WHERE id = ?
                    LIMIT 1
                ");

                $stmt->execute([$checkParent]);

                $nextParent = $stmt->fetchColumn();

                if ($nextParent === false || $nextParent === null) {
                    break;
                }

                $checkParent = (int)$nextParent;
            }

            if ($circular) {

                $_SESSION['pages_error'] =
                    'Invalid parent page. Circular hierarchy is not allowed.';

                redirect_pages(['edit' => $id]);
            }
        }

        /* -------------------------------------------------
           Featured media validation
        ------------------------------------------------- */

        if ($featuredMediaId !== null) {

            $mediaTableExists = false;

            try {
                $checkTable = $pdo->query("
                    SHOW TABLES LIKE 'media'
                ");

                $mediaTableExists = (bool)$checkTable->fetchColumn();
            } catch (Throwable $e) {
                $mediaTableExists = false;
            }

            if ($mediaTableExists) {

                try {

                    $stmt = $pdo->prepare("
                        SELECT id
                        FROM media
                        WHERE id = ?
                        LIMIT 1
                    ");

                    $stmt->execute([$featuredMediaId]);

                    if (!$stmt->fetchColumn()) {
                        $featuredMediaId = null;
                    }

                } catch (Throwable $e) {
                    $featuredMediaId = null;
                }
            } else {
                $featuredMediaId = null;
            }
        }

        /* -------------------------------------------------
           Published date
        ------------------------------------------------- */

        if ($status === 'published') {

            if ($publishedAt === '') {
                $publishedAt = date('Y-m-d H:i:s');
            } else {

                $timestamp = strtotime($publishedAt);

                if ($timestamp !== false) {
                    $publishedAt = date(
                        'Y-m-d H:i:s',
                        $timestamp
                    );
                } else {
                    $publishedAt = date('Y-m-d H:i:s');
                }
            }

        } else {

            if ($publishedAt !== '') {

                $timestamp = strtotime($publishedAt);

                if ($timestamp !== false) {
                    $publishedAt = date(
                        'Y-m-d H:i:s',
                        $timestamp
                    );
                } else {
                    $publishedAt = null;
                }

            } else {
                $publishedAt = null;
            }
        }

        /* -------------------------------------------------
           Unique slug
        ------------------------------------------------- */

        $slugSql = "
            SELECT id
            FROM pages
            WHERE slug = ?
        ";

        $slugParams = [$slug];

        if ($id > 0) {
            $slugSql .= " AND id != ?";
            $slugParams[] = $id;
        }

        $slugSql .= " LIMIT 1";

        $stmt = $pdo->prepare($slugSql);
        $stmt->execute($slugParams);

        if ($stmt->fetchColumn()) {

            $baseSlug = $slug;
            $counter = 2;

            while (true) {

                $newSlug = $baseSlug . '-' . $counter;

                $checkSql = "
                    SELECT id
                    FROM pages
                    WHERE slug = ?
                ";

                $checkParams = [$newSlug];

                if ($id > 0) {
                    $checkSql .= " AND id != ?";
                    $checkParams[] = $id;
                }

                $checkSql .= " LIMIT 1";

                $checkStmt = $pdo->prepare($checkSql);
                $checkStmt->execute($checkParams);

                if (!$checkStmt->fetchColumn()) {
                    $slug = $newSlug;
                    break;
                }

                $counter++;

                if ($counter > 9999) {

                    $_SESSION['pages_error'] =
                        'Unable to generate a unique slug.';

                    redirect_pages(
                        $id > 0
                            ? ['edit' => $id]
                            : []
                    );
                }
            }
        }

        /* -------------------------------------------------
           Current admin/user
        ------------------------------------------------- */

        /*
         * pages.created_by / updated_by point to users.id in this project.
         * Admin IDs are not assumed to be valid users IDs. Validate before
         * inserting to prevent foreign-key errors; NULL is allowed by schema.
         */
        $currentUserId = null;
        $sessionUserCandidates = [
            $_SESSION['USER_ID'] ?? null,
            $_SESSION['user_id'] ?? null,
            $_SESSION['ADMIN_ID'] ?? null,
            $_SESSION['admin_id'] ?? null,
        ];

        try {
            $usersTableCheck = $pdo->query("SHOW TABLES LIKE 'users'");
            if ($usersTableCheck && $usersTableCheck->fetchColumn()) {
                $userLookup = $pdo->prepare('SELECT id FROM users WHERE id = ? LIMIT 1');
                foreach ($sessionUserCandidates as $candidate) {
                    if ($candidate === null || $candidate === '' || !is_numeric($candidate) || (int)$candidate < 1) {
                        continue;
                    }
                    $userLookup->execute([(int)$candidate]);
                    $validUserId = $userLookup->fetchColumn();
                    if ($validUserId !== false) {
                        $currentUserId = (int)$validUserId;
                        break;
                    }
                }
            }
        } catch (Throwable $userLookupError) {
            // Schema permits NULL; keep the page save independent of session-table differences.
            $currentUserId = null;
        }

        /* -------------------------------------------------
           OPTIONAL FEATURED IMAGE UPLOAD
           Uploads are registered in the existing media table.
        ------------------------------------------------- */

        if (isset($_FILES['featured_upload']) &&
            is_array($_FILES['featured_upload']) &&
            (int)($_FILES['featured_upload']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {

            $upload = $_FILES['featured_upload'];
            $uploadError = (int)($upload['error'] ?? UPLOAD_ERR_NO_FILE);

            if ($uploadError !== UPLOAD_ERR_OK) {
                $_SESSION['pages_error'] = 'Image upload failed. Please choose the image again.';
                redirect_pages($id > 0 ? ['edit' => $id] : []);
            }

            if (empty($upload['tmp_name']) || !is_uploaded_file($upload['tmp_name'])) {
                $_SESSION['pages_error'] = 'Invalid image upload.';
                redirect_pages($id > 0 ? ['edit' => $id] : []);
            }

            $maxUploadBytes = 8 * 1024 * 1024;
            if ((int)($upload['size'] ?? 0) > $maxUploadBytes) {
                $_SESSION['pages_error'] = 'Image size must be 8 MB or less.';
                redirect_pages($id > 0 ? ['edit' => $id] : []);
            }

            $finfo = new finfo(FILEINFO_MIME_TYPE);
            $detectedMime = $finfo->file($upload['tmp_name']);
            $allowedImages = [
                'image/jpeg' => 'jpg',
                'image/png'  => 'png',
                'image/gif'  => 'gif',
                'image/webp' => 'webp',
            ];

            if (!isset($allowedImages[$detectedMime])) {
                $_SESSION['pages_error'] = 'Only JPG, PNG, GIF, and WEBP images are allowed.';
                redirect_pages($id > 0 ? ['edit' => $id] : []);
            }

            try {
                $mediaTableCheck = $pdo->query("SHOW TABLES LIKE 'media'");
                if (!$mediaTableCheck->fetchColumn()) {
                    throw new RuntimeException('The media table was not found.');
                }

                $uploadDirectory = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'media';
                if (!is_dir($uploadDirectory) && !mkdir($uploadDirectory, 0775, true) && !is_dir($uploadDirectory)) {
                    throw new RuntimeException('Could not create the uploads/media directory.');
                }

                $extension = $allowedImages[$detectedMime];
                $safeFileName = 'page_' . date('Ymd_His') . '_' . bin2hex(random_bytes(6)) . '.' . $extension;
                $absolutePath = $uploadDirectory . DIRECTORY_SEPARATOR . $safeFileName;
                $relativePath = 'uploads/media/' . $safeFileName;

                if (!move_uploaded_file($upload['tmp_name'], $absolutePath)) {
                    throw new RuntimeException('Could not move the uploaded image. Check folder permissions.');
                }

                $originalName = basename((string)($upload['name'] ?? $safeFileName));
                $imageSize = @getimagesize($absolutePath);
                $imageWidth = is_array($imageSize) ? (int)$imageSize[0] : null;
                $imageHeight = is_array($imageSize) ? (int)$imageSize[1] : null;

                try {
                    $mediaInsert = $pdo->prepare("
                        INSERT INTO media
                        (original_name, file_name, file_path, mime_type, file_type, extension, file_size, width, height, uploaded_by, status)
                        VALUES
                        (:original_name, :file_name, :file_path, :mime_type, 'image', :extension, :file_size, :width, :height, NULL, 1)
                    ");
                    $mediaInsert->execute([
                        ':original_name' => function_exists('mb_substr') ? mb_substr($originalName, 0, 255, 'UTF-8') : substr($originalName, 0, 255),
                        ':file_name' => $safeFileName,
                        ':file_path' => $relativePath,
                        ':mime_type' => $detectedMime,
                        ':extension' => $extension,
                        ':file_size' => (int)filesize($absolutePath),
                        ':width' => $imageWidth,
                        ':height' => $imageHeight,
                    ]);
                    $featuredMediaId = (int)$pdo->lastInsertId();
                } catch (Throwable $mediaInsertError) {
                    @unlink($absolutePath);
                    throw $mediaInsertError;
                }
            } catch (Throwable $uploadException) {
                $_SESSION['pages_error'] = 'Image could not be saved to the media library: ' . $uploadException->getMessage();
                redirect_pages($id > 0 ? ['edit' => $id] : []);
            }
        }

        /* -------------------------------------------------
           INSERT
        ------------------------------------------------- */

        if ($id <= 0) {

            $stmt = $pdo->prepare("
                INSERT INTO pages
                (
                    parent_id,
                    title,
                    slug,
                    page_type,
                    template,
                    excerpt,
                    content,
                    featured_media_id,
                    status,
                    sort_order,
                    published_at,
                    created_by,
                    updated_by
                )
                VALUES
                (
                    :parent_id,
                    :title,
                    :slug,
                    :page_type,
                    :template,
                    :excerpt,
                    :content,
                    :featured_media_id,
                    :status,
                    :sort_order,
                    :published_at,
                    :created_by,
                    :updated_by
                )
            ");

            $stmt->execute([
                ':parent_id'         => $parentId,
                ':title'             => $title,
                ':slug'              => $slug,
                ':page_type'         => $pageType,
                ':template'          => $template,
                ':excerpt'           => $excerpt !== ''
                    ? $excerpt
                    : null,
                ':content'           => $content !== ''
                    ? $content
                    : null,
                ':featured_media_id' => $featuredMediaId,
                ':status'            => $status,
                ':sort_order'        => $sortOrder,
                ':published_at'      => $publishedAt ?: null,
                ':created_by'        => $currentUserId,
                ':updated_by'        => $currentUserId
            ]);

            $_SESSION['pages_success'] =
                'Page created successfully.';

            redirect_pages();
        }

        /* -------------------------------------------------
           UPDATE
        ------------------------------------------------- */

        $stmt = $pdo->prepare("
            UPDATE pages
            SET
                parent_id = :parent_id,
                title = :title,
                slug = :slug,
                page_type = :page_type,
                template = :template,
                excerpt = :excerpt,
                content = :content,
                featured_media_id = :featured_media_id,
                status = :status,
                sort_order = :sort_order,
                published_at = :published_at,
                updated_by = :updated_by
            WHERE id = :id
            LIMIT 1
        ");

        $stmt->execute([
            ':parent_id'         => $parentId,
            ':title'             => $title,
            ':slug'              => $slug,
            ':page_type'         => $pageType,
            ':template'          => $template,
            ':excerpt'           => $excerpt !== ''
                ? $excerpt
                : null,
            ':content'           => $content !== ''
                ? $content
                : null,
            ':featured_media_id' => $featuredMediaId,
            ':status'            => $status,
            ':sort_order'        => $sortOrder,
            ':published_at'      => $publishedAt ?: null,
            ':updated_by'        => $currentUserId,
            ':id'                => $id
        ]);

        $_SESSION['pages_success'] =
            'Page updated successfully.';

        redirect_pages();
    }

    /* =====================================================
       DELETE
    ===================================================== */

    if ($action === 'delete') {

        $id = (int)($_POST['id'] ?? 0);

        if ($id <= 0) {
            $_SESSION['pages_error'] = 'Invalid page selected.';
            redirect_pages();
        }

        /* Check child pages */

        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM pages
            WHERE parent_id = ?
        ");

        $stmt->execute([$id]);

        $childCount = (int)$stmt->fetchColumn();

        if ($childCount > 0) {

            $_SESSION['pages_error'] =
                'This page contains child pages. Move or delete them first.';

            redirect_pages();
        }

        $stmt = $pdo->prepare("
            DELETE FROM pages
            WHERE id = ?
            LIMIT 1
        ");

        $stmt->execute([$id]);

        $_SESSION['pages_success'] =
            'Page deleted successfully.';

        redirect_pages();
    }

    /* =====================================================
       QUICK STATUS
    ===================================================== */

    if ($action === 'change_status') {

        $id = (int)($_POST['id'] ?? 0);
        $newStatus = $_POST['new_status'] ?? '';

        $allowedStatuses = [
            'draft',
            'published',
            'inactive'
        ];

        if (
            $id <= 0 ||
            !in_array($newStatus, $allowedStatuses, true)
        ) {
            $_SESSION['pages_error'] =
                'Invalid page status request.';

            redirect_pages();
        }

        $publishedAt = null;

        if ($newStatus === 'published') {
            $publishedAt = date('Y-m-d H:i:s');
        }

        $stmt = $pdo->prepare("
            UPDATE pages
            SET
                status = :status,
                published_at =
                    CASE
                        WHEN :status2 = 'published'
                            THEN COALESCE(published_at, :published_at)
                        ELSE published_at
                    END
            WHERE id = :id
            LIMIT 1
        ");

        $stmt->execute([
            ':status'       => $newStatus,
            ':status2'      => $newStatus,
            ':published_at' => $publishedAt,
            ':id'           => $id
        ]);

        $_SESSION['pages_success'] =
            'Page status updated successfully.';

        redirect_pages();
    }
}

/* =========================================================
   EDIT PAGE
========================================================= */

$editId = isset($_GET['edit'])
    ? (int)$_GET['edit']
    : 0;

$editPage = null;

if ($editId > 0) {

    $stmt = $pdo->prepare("
        SELECT
            id,
            parent_id,
            title,
            slug,
            page_type,
            template,
            excerpt,
            content,
            featured_media_id,
            status,
            sort_order,
            published_at,
            created_by,
            updated_by,
            created_at,
            updated_at
        FROM pages
        WHERE id = ?
        LIMIT 1
    ");

    $stmt->execute([$editId]);

    $editPage = $stmt->fetch();

    if (!$editPage) {
        $editId = 0;
    }
}

/* =========================================================
   PAGE PARENTS
========================================================= */

$parentStmt = $pdo->query("
    SELECT
        id,
        parent_id,
        title,
        slug,
        status
    FROM pages
    ORDER BY
        sort_order ASC,
        title ASC,
        id ASC
");

$allPages = $parentStmt->fetchAll();

$pageMap = [];

$childrenMap = [];

foreach ($allPages as $page) {

    $pageMap[(int)$page['id']] = $page;

    $pid = $page['parent_id'] !== null
        ? (int)$page['parent_id']
        : 0;

    if (!isset($childrenMap[$pid])) {
        $childrenMap[$pid] = [];
    }

    $childrenMap[$pid][] = $page;
}

if (!function_exists('render_page_options')) {

    function render_page_options(
        $childrenMap,
        $parentId = 0,
        $level = 0,
        $excludeId = 0
    ) {
        if (empty($childrenMap[$parentId])) {
            return;
        }

        foreach ($childrenMap[$parentId] as $page) {

            $pageId = (int)$page['id'];

            if ($pageId === $excludeId) {
                continue;
            }

            $prefix = str_repeat('— ', $level);

            echo '<option value="' .
                $pageId .
                '">' .
                e($prefix . $page['title']) .
                '</option>';

            render_page_options(
                $childrenMap,
                $pageId,
                $level + 1,
                $excludeId
            );
        }
    }
}

/* =========================================================
   MEDIA LIST
========================================================= */

$mediaItems = [];

try {

    $mediaTableCheck = $pdo->query("
        SHOW TABLES LIKE 'media'
    ");

    if ($mediaTableCheck->fetchColumn()) {

        /*
         * Only id is required here.
         * Other media columns are not assumed.
         */
        $mediaStmt = $pdo->query("
            SELECT id, original_name, file_name, file_type, mime_type, status
            FROM media
            ORDER BY id DESC
            LIMIT 500
        ");

        $mediaItems = $mediaStmt->fetchAll();
    }

} catch (Throwable $e) {
    $mediaItems = [];
}

/* =========================================================
   FILTERS
========================================================= */

$search = trim($_GET['q'] ?? '');

$statusFilter = $_GET['status'] ?? '';

$typeFilter = trim($_GET['page_type'] ?? '');

$parentFilter =
    isset($_GET['parent']) &&
    $_GET['parent'] !== ''
        ? (int)$_GET['parent']
        : null;

/* =========================================================
   PAGE LIST
========================================================= */

$where = [];
$params = [];

if ($search !== '') {

    $where[] = "
        (
            p.title LIKE :search
            OR p.slug LIKE :search
            OR p.excerpt LIKE :search
        )
    ";

    $params[':search'] = '%' . $search . '%';
}

if (
    $statusFilter !== '' &&
    in_array(
        $statusFilter,
        ['draft', 'published', 'inactive'],
        true
    )
) {

    $where[] = "p.status = :status";

    $params[':status'] = $statusFilter;
}

if ($typeFilter !== '') {

    $where[] = "p.page_type = :page_type";

    $params[':page_type'] = $typeFilter;
}

if ($parentFilter !== null) {

    if ($parentFilter === 0) {

        $where[] = "p.parent_id IS NULL";

    } else {

        $where[] = "p.parent_id = :parent_filter";

        $params[':parent_filter'] = $parentFilter;
    }
}

$listSql = "
    SELECT
        p.id,
        p.parent_id,
        p.title,
        p.slug,
        p.page_type,
        p.template,
        p.excerpt,
        p.featured_media_id,
        p.status,
        p.sort_order,
        p.published_at,
        p.created_by,
        p.updated_by,
        p.created_at,
        p.updated_at,
        parent.title AS parent_title,
        (
            SELECT COUNT(*)
            FROM pages child
            WHERE child.parent_id = p.id
        ) AS child_count
    FROM pages p
    LEFT JOIN pages parent
        ON parent.id = p.parent_id
";

if ($where) {
    $listSql .= " WHERE " . implode(' AND ', $where);
}

$listSql .= "
    ORDER BY
        p.sort_order ASC,
        p.title ASC,
        p.id DESC
";

$stmt = $pdo->prepare($listSql);
$stmt->execute($params);

$pages = $stmt->fetchAll();

/* =========================================================
   STATS
========================================================= */

$totalPages = (int)$pdo->query("
    SELECT COUNT(*)
    FROM pages
")->fetchColumn();

$publishedPages = (int)$pdo->query("
    SELECT COUNT(*)
    FROM pages
    WHERE status = 'published'
")->fetchColumn();

$draftPages = (int)$pdo->query("
    SELECT COUNT(*)
    FROM pages
    WHERE status = 'draft'
")->fetchColumn();

$inactivePages = (int)$pdo->query("
    SELECT COUNT(*)
    FROM pages
    WHERE status = 'inactive'
")->fetchColumn();

$rootPages = (int)$pdo->query("
    SELECT COUNT(*)
    FROM pages
    WHERE parent_id IS NULL
")->fetchColumn();

$childPages = $totalPages - $rootPages;

/* =========================================================
   PAGE TYPES
========================================================= */

$typeStmt = $pdo->query("
    SELECT DISTINCT page_type
    FROM pages
    WHERE page_type IS NOT NULL
      AND page_type != ''
    ORDER BY page_type ASC
");

$pageTypes = $typeStmt->fetchAll();

/* =========================================================
   FORM VALUES
========================================================= */

$formId = $editPage['id'] ?? 0;

$formParentId =
    $editPage['parent_id'] ?? null;

$formTitle =
    $editPage['title'] ?? '';

$formSlug =
    $editPage['slug'] ?? '';

$formPageType =
    $editPage['page_type'] ?? 'standard';

$formTemplate =
    $editPage['template'] ?? 'default';

$formExcerpt =
    $editPage['excerpt'] ?? '';

$formContent =
    $editPage['content'] ?? '';

$formFeaturedMediaId =
    $editPage['featured_media_id'] ?? null;

$formStatus =
    $editPage['status'] ?? 'draft';

$formSortOrder =
    $editPage['sort_order'] ?? 0;

$formPublishedAt =
    $editPage['published_at'] ?? '';

if ($formPublishedAt) {

    $publishedTimestamp = strtotime($formPublishedAt);

    if ($publishedTimestamp !== false) {
        $formPublishedAt =
            date(
                'Y-m-d\TH:i',
                $publishedTimestamp
            );
    }
}

?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>
        Pages | Pure Chemical Admin
    </title>

    <meta
        name="theme-color"
        content="#07111f"
    >

    <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: #10b981;
            --primary-dark: #059669;
            --primary-soft: #ecfdf5;

            --blue: #2563eb;
            --blue-soft: #eff6ff;

            --orange: #ea580c;
            --orange-soft: #fff7ed;

            --purple: #7c3aed;
            --purple-soft: #f5f3ff;

            --red: #dc2626;
            --red-soft: #fef2f2;

            --dark: #07111f;
            --text: #172033;
            --muted: #718096;

            --bg: #f4f7fb;
            --card: #ffffff;
            --border: #e6ebf2;

            --radius: 18px;

            --shadow:
                0 16px 45px rgba(
                    15,
                    23,
                    42,
                    .07
                );
        }

        * {
            box-sizing: border-box;
        }

        html {
            scroll-behavior: smooth;
        }

        body {

            margin: 0;

            background: var(--bg);

            color: var(--text);

            font-family: "Inter", sans-serif;

            font-size: 14px;
        }

        button,
        input,
        select,
        textarea {
            font-family: inherit;
        }

        a {
            text-decoration: none;
        }

        /* =================================================
           MAIN
        ================================================= */

        .pc-main {

            margin-left: 280px;

            min-height: 100vh;
        }

        /* =================================================
           TOPBAR
        ================================================= */

        .pc-topbar {

            position: sticky;

            top: 0;

            z-index: 1000;

            min-height: 76px;

            padding: 14px 30px;

            background:
                rgba(
                    255,
                    255,
                    255,
                    .88
                );

            backdrop-filter: blur(18px);

            border-bottom:
                1px solid
                rgba(
                    226,
                    232,
                    240,
                    .85
                );

            display: flex;

            align-items: center;

            justify-content: space-between;

            gap: 20px;
        }

        .pc-breadcrumb {

            display: flex;

            align-items: center;

            gap: 8px;

            color: var(--muted);

            font-size: 12px;

            margin-bottom: 5px;
        }

        .pc-breadcrumb i {
            font-size: 9px;
        }

        .pc-title {

            margin: 0;

            color: var(--dark);

            font-size: 22px;

            font-weight: 800;

            letter-spacing: -.5px;
        }

        .pc-top-actions {

            display: flex;

            align-items: center;

            gap: 9px;
        }

        .pc-top-btn {

            min-height: 42px;

            padding: 0 15px;

            border:
                1px solid
                var(--border);

            border-radius: 11px;

            background: #fff;

            color: #475569;

            display: inline-flex;

            align-items: center;

            justify-content: center;

            gap: 8px;

            font-size: 12px;

            font-weight: 800;

            transition: .2s ease;
        }

        .pc-top-btn:hover {

            border-color:
                rgba(
                    16,
                    185,
                    129,
                    .35
                );

            color: var(--primary-dark);

            transform:
                translateY(-1px);
        }

        .pc-top-btn.primary {

            color: #fff;

            border-color: transparent;

            background:
                linear-gradient(
                    135deg,
                    var(--primary),
                    var(--primary-dark)
                );

            box-shadow:
                0 9px 22px
                rgba(
                    16,
                    185,
                    129,
                    .20
                );
        }

        /* =================================================
           CONTENT
        ================================================= */

        .pc-content {
            padding: 30px;
        }

        /* =================================================
           ALERTS
        ================================================= */

        .pc-alert {

            display: flex;

            align-items: flex-start;

            gap: 11px;

            padding: 14px 16px;

            border-radius: 14px;

            margin-bottom: 22px;

            font-size: 13px;

            font-weight: 600;
        }

        .pc-alert.success {

            color: #047857;

            background: #ecfdf5;

            border:
                1px solid
                #a7f3d0;
        }

        .pc-alert.error {

            color: #b91c1c;

            background: #fef2f2;

            border:
                1px solid
                #fecaca;
        }

        /* =================================================
           HERO
        ================================================= */

        .pc-hero {

            position: relative;

            overflow: hidden;

            padding: 30px;

            margin-bottom: 23px;

            border-radius: 24px;

            color: #fff;

            background:
                radial-gradient(
                    circle at 90% 15%,
                    rgba(
                        16,
                        185,
                        129,
                        .20
                    ),
                    transparent 35%
                ),
                linear-gradient(
                    135deg,
                    #07111f,
                    #0d1b2d 65%,
                    #10263a
                );

            box-shadow: var(--shadow);
        }

        .pc-hero-inner {

            position: relative;

            z-index: 2;

            display: flex;

            align-items: center;

            justify-content: space-between;

            gap: 25px;
        }

        .pc-eyebrow {

            display: inline-flex;

            align-items: center;

            gap: 7px;

            padding: 7px 11px;

            border-radius: 999px;

            color: #a7f3d0;

            background:
                rgba(
                    16,
                    185,
                    129,
                    .13
                );

            border:
                1px solid
                rgba(
                    52,
                    211,
                    153,
                    .22
                );

            font-size: 10px;

            font-weight: 800;

            letter-spacing: .5px;

            text-transform: uppercase;
        }

        .pc-hero h2 {

            margin: 14px 0 8px;

            font-size: 28px;

            line-height: 1.2;

            letter-spacing: -.8px;
        }

        .pc-hero p {

            max-width: 720px;

            margin: 0;

            color:
                rgba(
                    255,
                    255,
                    255,
                    .68
                );

            line-height: 1.7;
        }

        .pc-hero-icon {

            width: 82px;

            height: 82px;

            flex: 0 0 82px;

            display: flex;

            align-items: center;

            justify-content: center;

            border-radius: 23px;

            color: #6ee7b7;

            background:
                rgba(
                    255,
                    255,
                    255,
                    .07
                );

            border:
                1px solid
                rgba(
                    255,
                    255,
                    255,
                    .10
                );

            font-size: 32px;
        }

        /* =================================================
           STATS
        ================================================= */

        .pc-stats {

            display: grid;

            grid-template-columns:
                repeat(
                    4,
                    minmax(
                        0,
                        1fr
                    )
                );

            gap: 15px;

            margin-bottom: 23px;
        }

        .pc-stat {

            display: flex;

            align-items: center;

            gap: 13px;

            padding: 18px;

            background: var(--card);

            border:
                1px solid
                var(--border);

            border-radius: var(--radius);

            box-shadow:
                0 8px 30px
                rgba(
                    15,
                    23,
                    42,
                    .04
                );
        }

        .pc-stat-icon {

            width: 45px;

            height: 45px;

            flex: 0 0 45px;

            display: flex;

            align-items: center;

            justify-content: center;

            border-radius: 13px;

            font-size: 18px;
        }

        .pc-stat:nth-child(1)
        .pc-stat-icon {

            color: #059669;

            background:
                var(--primary-soft);
        }

        .pc-stat:nth-child(2)
        .pc-stat-icon {

            color: #2563eb;

            background:
                var(--blue-soft);
        }

        .pc-stat:nth-child(3)
        .pc-stat-icon {

            color: #ea580c;

            background:
                var(--orange-soft);
        }

        .pc-stat:nth-child(4)
        .pc-stat-icon {

            color: #7c3aed;

            background:
                var(--purple-soft);
        }

        .pc-stat-label {

            margin-bottom: 3px;

            color: var(--muted);

            font-size: 11px;

            font-weight: 600;
        }

        .pc-stat-value {

            color: var(--dark);

            font-size: 22px;

            line-height: 1.1;

            font-weight: 800;
        }

        /* =================================================
           GRID
        ================================================= */

        .pc-grid {

            display: grid;

            grid-template-columns:
                minmax(
                    380px,
                    .9fr
                )
                minmax(
                    0,
                    1.8fr
                );

            gap: 22px;

            align-items: start;
        }

        .pc-card {

            overflow: hidden;

            background: var(--card);

            border:
                1px solid
                var(--border);

            border-radius: var(--radius);

            box-shadow: var(--shadow);
        }

        .pc-card-head {

            display: flex;

            align-items: center;

            justify-content: space-between;

            gap: 15px;

            padding: 20px 22px;

            border-bottom:
                1px solid
                var(--border);
        }

        .pc-card-title {

            margin: 0;

            color: var(--dark);

            font-size: 16px;

            font-weight: 800;
        }

        .pc-card-subtitle {

            margin: 4px 0 0;

            color: var(--muted);

            font-size: 11px;

            line-height: 1.5;
        }

        .pc-card-body {
            padding: 22px;
        }

        /* =================================================
           FORM
        ================================================= */

        .pc-form-group {
            margin-bottom: 16px;
        }

        .pc-label {

            display: block;

            margin-bottom: 7px;

            color: #334155;

            font-size: 11px;

            font-weight: 800;
        }

        .pc-label span {
            color: #ef4444;
        }

        .pc-input,
        .pc-select,
        .pc-textarea {

            width: 100%;

            border:
                1px solid
                #dfe5ed;

            border-radius: 11px;

            outline: none;

            color: var(--text);

            background: #fff;

            transition: .2s ease;
        }

        .pc-input,
        .pc-select {

            height: 45px;

            padding: 0 12px;
        }

        .pc-textarea {

            min-height: 110px;

            padding: 12px;

            resize: vertical;

            line-height: 1.6;
        }

        .pc-input:focus,
        .pc-select:focus,
        .pc-textarea:focus {

            border-color:
                rgba(
                    16,
                    185,
                    129,
                    .60
                );

            box-shadow:
                0 0 0 4px
                rgba(
                    16,
                    185,
                    129,
                    .09
                );
        }

        .pc-help {

            margin-top: 5px;

            color: #94a3b8;

            font-size: 10px;

            line-height: 1.5;
        }

        .pc-row {

            display: grid;

            grid-template-columns:
                1fr
                1fr;

            gap: 12px;
        }

        .pc-status-wrap {

            display: grid;

            grid-template-columns:
                repeat(
                    3,
                    1fr
                );

            gap: 7px;
        }

        .pc-status-option {

            position: relative;
        }

        .pc-status-option input {

            position: absolute;

            opacity: 0;

            pointer-events: none;
        }

        .pc-status-option label {

            min-height: 43px;

            padding: 0 8px;

            display: flex;

            align-items: center;

            justify-content: center;

            gap: 6px;

            cursor: pointer;

            border:
                1px solid
                #e2e8f0;

            border-radius: 10px;

            color: #64748b;

            background: #fff;

            font-size: 10px;

            font-weight: 800;

            transition: .2s ease;
        }

        .pc-status-option input:checked + label {

            color: #047857;

            border-color:
                #a7f3d0;

            background:
                #ecfdf5;
        }

        .pc-status-option.inactive
        input:checked + label {

            color: #b91c1c;

            border-color:
                #fecaca;

            background:
                #fef2f2;
        }

        .pc-status-option.published
        input:checked + label {

            color: #1d4ed8;

            border-color:
                #bfdbfe;

            background:
                #eff6ff;
        }

        .pc-form-actions {

            display: flex;

            align-items: center;

            gap: 8px;

            margin-top: 21px;
        }

        .pc-btn {

            min-height: 42px;

            padding: 0 14px;

            display: inline-flex;

            align-items: center;

            justify-content: center;

            gap: 7px;

            border-radius: 10px;

            border:
                1px solid
                transparent;

            cursor: pointer;

            font-size: 11px;

            font-weight: 800;

            transition: .2s ease;
        }

        .pc-btn-primary {

            color: #fff;

            background:
                linear-gradient(
                    135deg,
                    var(--primary),
                    var(--primary-dark)
                );

            box-shadow:
                0 8px 18px
                rgba(
                    16,
                    185,
                    129,
                    .18
                );
        }

        .pc-btn-primary:hover {

            transform:
                translateY(-1px);

            box-shadow:
                0 11px 22px
                rgba(
                    16,
                    185,
                    129,
                    .25
                );
        }

        .pc-btn-light {

            color: #475569;

            background: #fff;

            border-color:
                var(--border);
        }

        .pc-btn-light:hover {

            background: #f8fafc;

            border-color:
                #cbd5e1;
        }

        /* =================================================
           TOOLBAR
        ================================================= */

        .pc-toolbar {

            display: flex;

            align-items: center;

            flex-wrap: wrap;

            gap: 8px;

            padding: 14px 17px;

            background: #fbfcfe;

            border-bottom:
                1px solid
                var(--border);
        }

        .pc-search {

            position: relative;

            flex: 1 1 230px;
        }

        .pc-search i {

            position: absolute;

            left: 13px;

            top: 50%;

            transform:
                translateY(-50%);

            color: #94a3b8;

            font-size: 12px;
        }

        .pc-search input {

            width: 100%;

            height: 41px;

            padding:
                0 12px 0 35px;

            border:
                1px solid
                #dfe5ed;

            border-radius: 10px;

            outline: none;
        }

        .pc-filter {

            height: 41px;

            min-width: 125px;

            padding: 0 10px;

            border:
                1px solid
                #dfe5ed;

            border-radius: 10px;

            background: #fff;

            color: #475569;

            outline: none;

            font-size: 11px;

            font-weight: 700;
        }

        /* =================================================
           TABLE
        ================================================= */

        .pc-table-wrap {

            width: 100%;

            overflow-x: auto;
        }

        .pc-table {

            width: 100%;

            min-width: 950px;

            border-collapse: collapse;
        }

        .pc-table th {

            padding: 12px 16px;

            text-align: left;

            background: #fbfcfe;

            border-bottom:
                1px solid
                var(--border);

            color: #64748b;

            font-size: 9px;

            font-weight: 800;

            text-transform: uppercase;

            letter-spacing: .55px;

            white-space: nowrap;
        }

        .pc-table td {

            padding: 14px 16px;

            border-bottom:
                1px solid
                #edf1f5;

            vertical-align: middle;
        }

        .pc-table tbody tr {

            transition: .15s ease;
        }

        .pc-table tbody tr:hover {

            background:
                #fbfffd;
        }

        .pc-page {

            display: flex;

            align-items: center;

            gap: 11px;

            min-width: 230px;
        }

        .pc-page-icon {

            width: 40px;

            height: 40px;

            flex: 0 0 40px;

            display: flex;

            align-items: center;

            justify-content: center;

            border-radius: 11px;

            color: #2563eb;

            background:
                #eff6ff;
        }

        .pc-page-title-text {

            color: #1e293b;

            font-size: 12px;

            font-weight: 800;

            line-height: 1.4;
        }

        .pc-page-slug {

            margin-top: 3px;

            color: #94a3b8;

            font-size: 9px;

            word-break: break-all;
        }

        .pc-parent {

            display: inline-flex;

            align-items: center;

            gap: 5px;

            padding: 6px 9px;

            border-radius: 8px;

            color: #64748b;

            background:
                #f8fafc;

            font-size: 10px;

            font-weight: 700;
        }

        .pc-root {

            color: #2563eb;

            background:
                #eff6ff;
        }

        .pc-type {

            display: inline-flex;

            padding: 6px 8px;

            border-radius: 7px;

            color: #7c3aed;

            background:
                #f5f3ff;

            font-size: 9px;

            font-weight: 800;
        }

        .pc-template {

            color: #64748b;

            font-size: 10px;

            font-weight: 700;
        }

        .pc-order {

            display: inline-flex;

            align-items: center;

            justify-content: center;

            min-width: 29px;

            height: 27px;

            padding: 0 7px;

            border-radius: 7px;

            color: #475569;

            background:
                #f8fafc;

            font-size: 10px;

            font-weight: 800;
        }

        .pc-badge {

            display: inline-flex;

            align-items: center;

            gap: 5px;

            padding: 6px 9px;

            border-radius: 999px;

            font-size: 9px;

            font-weight: 800;
        }

        .pc-badge.draft {

            color: #92400e;

            background:
                #fffbeb;
        }

        .pc-badge.published {

            color: #047857;

            background:
                #ecfdf5;
        }

        .pc-badge.inactive {

            color: #b91c1c;

            background:
                #fef2f2;
        }

        .pc-actions {

            display: flex;

            align-items: center;

            justify-content: flex-end;

            gap: 5px;
        }

        .pc-action {

            width: 33px;

            height: 33px;

            display: inline-flex;

            align-items: center;

            justify-content: center;

            border-radius: 9px;

            border:
                1px solid
                #e2e8f0;

            color: #64748b;

            background: #fff;

            cursor: pointer;

            transition: .18s ease;
        }

        .pc-action:hover {

            transform:
                translateY(-1px);
        }

        .pc-action.edit:hover {

            color: #2563eb;

            border-color:
                #bfdbfe;

            background:
                #eff6ff;
        }

        .pc-action.publish:hover {

            color: #059669;

            border-color:
                #a7f3d0;

            background:
                #ecfdf5;
        }

        .pc-action.delete:hover {

            color: #dc2626;

            border-color:
                #fecaca;

            background:
                #fef2f2;
        }

        .pc-child-count {

            color: #64748b;

            font-size: 10px;

            font-weight: 700;
        }

        /* =================================================
           EMPTY
        ================================================= */

        .pc-empty {

            padding: 55px 20px;

            text-align: center;
        }

        .pc-empty-icon {

            width: 64px;

            height: 64px;

            margin: 0 auto 14px;

            display: flex;

            align-items: center;

            justify-content: center;

            border-radius: 18px;

            color: #2563eb;

            background:
                #eff6ff;

            font-size: 24px;
        }

        .pc-empty h3 {

            margin: 0 0 6px;

            color: #1e293b;

            font-size: 15px;
        }

        .pc-empty p {

            margin: 0;

            color: #94a3b8;

            font-size: 11px;
        }

        /* =================================================
           EDIT NOTE
        ================================================= */

        .pc-edit-note {

            display: flex;

            align-items: center;

            gap: 8px;

            margin-bottom: 16px;

            padding: 10px 12px;

            border:
                1px solid
                #bfdbfe;

            border-radius: 10px;

            color: #1d4ed8;

            background:
                #eff6ff;

            font-size: 10px;

            font-weight: 700;
        }

        /* =================================================
           RESPONSIVE
        ================================================= */

        @media (max-width: 1250px) {

            .pc-grid {

                grid-template-columns: 1fr;
            }

            .pc-stats {

                grid-template-columns:
                    repeat(
                        2,
                        minmax(
                            0,
                            1fr
                        )
                    );
            }
        }

        @media (max-width: 1100px) {

            .pc-main {
                margin-left: 0;
            }

            .pc-content {
                padding: 22px;
            }

            .pc-topbar {
                padding: 13px 22px;
            }
        }

        @media (max-width: 700px) {

            .pc-content {
                padding: 15px;
            }

            .pc-topbar {
                padding:
                    12px 15px;
            }

            .pc-title {
                font-size: 18px;
            }

            .pc-breadcrumb {
                display: none;
            }

            .pc-top-btn span {
                display: none;
            }

            .pc-top-btn {

                width: 40px;

                padding: 0;
            }

            .pc-hero {

                padding: 22px;

                border-radius: 19px;
            }

            .pc-hero h2 {
                font-size: 22px;
            }

            .pc-hero-icon {
                display: none;
            }

            .pc-stats {

                grid-template-columns:
                    1fr 1fr;

                gap: 10px;
            }

            .pc-stat {
                padding: 13px;
            }

            .pc-stat-value {
                font-size: 18px;
            }

            .pc-card-head,
            .pc-card-body {
                padding: 17px;
            }

            .pc-row {
                grid-template-columns: 1fr;
            }

            .pc-status-wrap {
                grid-template-columns:
                    1fr;
            }
        }

        @media (max-width: 470px) {

            .pc-stats {
                grid-template-columns: 1fr;
            }

            .pc-form-actions {

                flex-direction: column;

                align-items: stretch;
            }

            .pc-form-actions .pc-btn {
                width: 100%;
            }
        }

    </style>

</head>

<body>

<?php
/*
|--------------------------------------------------------------------------
| Existing Sidebar
|--------------------------------------------------------------------------
|
| Sidebar is included separately as requested.
| admin/header.php is NOT included.
|
*/
require_once __DIR__ . '/sidebar.php';
?>

<div class="pc-main">

    <!-- =====================================================
         TOPBAR
    ====================================================== -->

    <header class="pc-topbar">

        <div>

            <div class="pc-breadcrumb">

                <span>Admin</span>

                <i class="fa-solid fa-chevron-right"></i>

                <span>Website</span>

                <i class="fa-solid fa-chevron-right"></i>

                <span>Pages</span>

            </div>

            <h1 class="pc-title">
                Pages
            </h1>

        </div>


        <div class="pc-top-actions">

            <?php if ($editId > 0): ?>

                <a
                    href="pages.php"
                    class="pc-top-btn"
                >
                    <i class="fa-solid fa-arrow-left"></i>
                    <span>Back</span>
                </a>

            <?php endif; ?>

            <a
                href="media.php"
                class="pc-top-btn"
            >
                <i class="fa-solid fa-photo-film"></i>
                <span>Media</span>
            </a>

        </div>

    </header>


    <main class="pc-content">


        <!-- =================================================
             ALERT
        ================================================== -->

        <?php if ($flashSuccess): ?>

            <div class="pc-alert success">

                <i class="fa-solid fa-circle-check"></i>

                <div>
                    <?= e($flashSuccess) ?>
                </div>

            </div>

        <?php endif; ?>


        <?php if ($flashError): ?>

            <div class="pc-alert error">

                <i class="fa-solid fa-circle-exclamation"></i>

                <div>
                    <?= e($flashError) ?>
                </div>

            </div>

        <?php endif; ?>


        <!-- =================================================
             HERO
        ================================================== -->

        <section class="pc-hero">

            <div class="pc-hero-inner">

                <div>

                    <span class="pc-eyebrow">

                        <i class="fa-solid fa-file-lines"></i>

                        Website Content

                    </span>

                    <h2>
                        Manage website pages
                    </h2>

                    <p>
                        Create and manage standard website pages,
                        nested pages, page content, templates,
                        publication status and featured media from
                        one centralized dashboard.
                    </p>

                </div>


                <div class="pc-hero-icon">

                    <i class="fa-solid fa-file-lines"></i>

                </div>

            </div>

        </section>


        <!-- =================================================
             STATS
        ================================================== -->

        <section class="pc-stats">


            <div class="pc-stat">

                <div class="pc-stat-icon">

                    <i class="fa-solid fa-file"></i>

                </div>

                <div>

                    <div class="pc-stat-label">
                        Total Pages
                    </div>

                    <div class="pc-stat-value">
                        <?= number_format($totalPages) ?>
                    </div>

                </div>

            </div>


            <div class="pc-stat">

                <div class="pc-stat-icon">

                    <i class="fa-solid fa-circle-check"></i>

                </div>

                <div>

                    <div class="pc-stat-label">
                        Published
                    </div>

                    <div class="pc-stat-value">
                        <?= number_format($publishedPages) ?>
                    </div>

                </div>

            </div>


            <div class="pc-stat">

                <div class="pc-stat-icon">

                    <i class="fa-solid fa-pen-ruler"></i>

                </div>

                <div>

                    <div class="pc-stat-label">
                        Draft
                    </div>

                    <div class="pc-stat-value">
                        <?= number_format($draftPages) ?>
                    </div>

                </div>

            </div>


            <div class="pc-stat">

                <div class="pc-stat-icon">

                    <i class="fa-solid fa-sitemap"></i>

                </div>

                <div>

                    <div class="pc-stat-label">
                        Root / Child
                    </div>

                    <div class="pc-stat-value">
                        <?= number_format($rootPages) ?>
                        /
                        <?= number_format($childPages) ?>
                    </div>

                </div>

            </div>

        </section>


        <!-- =================================================
             MAIN GRID
        ================================================== -->

        <section class="pc-grid">


            <!-- =================================================
                 FORM
            ================================================== -->

            <div class="pc-card">

                <div class="pc-card-head">

                    <div>

                        <h2 class="pc-card-title">

                            <?= $editId > 0
                                ? 'Edit Page'
                                : 'Create Page'
                            ?>

                        </h2>

                        <p class="pc-card-subtitle">

                            <?= $editId > 0
                                ? 'Update the selected website page.'
                                : 'Create a new dynamic website page.'
                            ?>

                        </p>

                    </div>

                    <i
                        class="fa-solid <?= $editId > 0
                            ? 'fa-pen-to-square'
                            : 'fa-file-circle-plus'
                        ?>"
                        style="
                            color:#10b981;
                            font-size:20px;
                        "
                    ></i>

                </div>


                <div class="pc-card-body">


                    <?php if ($editId > 0): ?>

                        <div class="pc-edit-note">

                            <i class="fa-solid fa-pen"></i>

                            Editing:

                            <strong>
                                <?= e($formTitle) ?>
                            </strong>

                        </div>

                    <?php endif; ?>


                    <form
                        method="POST"
                        action="pages.php"
                        enctype="multipart/form-data"
                        autocomplete="off"
                    >

                        <?= csrf_field() ?>

                        <input
                            type="hidden"
                            name="action"
                            value="save"
                        >

                        <input
                            type="hidden"
                            name="id"
                            value="<?= (int)$formId ?>"
                        >


                        <!-- TITLE -->

                        <div class="pc-form-group">

                            <label class="pc-label">

                                Page Title

                                <span>*</span>

                            </label>

                            <input
                                type="text"
                                name="title"
                                id="pageTitleInput"
                                class="pc-input"
                                value="<?= e($formTitle) ?>"
                                maxlength="255"
                                placeholder="e.g. About Us"
                                required
                            >

                        </div>


                        <!-- SLUG -->

                        <div class="pc-form-group">

                            <label class="pc-label">

                                Slug

                                <span>*</span>

                            </label>

                            <input
                                type="text"
                                name="slug"
                                id="pageSlugInput"
                                class="pc-input"
                                value="<?= e($formSlug) ?>"
                                maxlength="255"
                                placeholder="about-us"
                                required
                            >

                            <div class="pc-help">
                                URL-friendly slug. Duplicate slugs are automatically made unique.
                            </div>

                        </div>


                        <!-- PAGE TYPE / TEMPLATE -->

                        <div class="pc-row">

                            <div class="pc-form-group">

                                <label class="pc-label">
                                    Page Type
                                </label>

                                <input
                                    type="text"
                                    name="page_type"
                                    class="pc-input"
                                    value="<?= e($formPageType) ?>"
                                    maxlength="100"
                                    placeholder="standard"
                                >

                                <div class="pc-help">
                                    Example: standard, landing, legal, contact.
                                </div>

                            </div>


                            <div class="pc-form-group">

                                <label class="pc-label">
                                    Template
                                </label>

                                <input
                                    type="text"
                                    name="template"
                                    class="pc-input"
                                    value="<?= e($formTemplate) ?>"
                                    maxlength="150"
                                    placeholder="default"
                                >

                            </div>

                        </div>


                        <!-- PARENT -->

                        <div class="pc-form-group">

                            <label class="pc-label">
                                Parent Page
                            </label>

                            <select
                                name="parent_id"
                                class="pc-select"
                            >

                                <option value="">
                                    — Root Page —
                                </option>

                                <?php

                                ob_start();

                                render_page_options(
                                    $childrenMap,
                                    0,
                                    0,
                                    $editId
                                );

                                $parentOptions =
                                    ob_get_clean();

                                if ($formParentId !== null) {

                                    $parentOptions =
                                        str_replace(
                                            'value="' .
                                            (int)$formParentId .
                                            '"',
                                            'value="' .
                                            (int)$formParentId .
                                            '" selected',
                                            $parentOptions
                                        );
                                }

                                echo $parentOptions;

                                ?>

                            </select>

                            <div class="pc-help">
                                Select a parent to create a nested page.
                            </div>

                        </div>


                        <!-- EXCERPT -->

                        <div class="pc-form-group">

                            <label class="pc-label">
                                Excerpt
                            </label>

                            <textarea
                                name="excerpt"
                                class="pc-textarea"
                                maxlength="65535"
                                placeholder="Short description of this page..."
                            ><?= e($formExcerpt) ?></textarea>

                        </div>


                        <!-- CONTENT -->

                        <div class="pc-form-group">

                            <label class="pc-label">
                                Content
                            </label>

                            <textarea
                                name="content"
                                class="pc-textarea"
                                style="min-height:190px;"
                                placeholder="Enter page content..."
                            ><?= e($formContent) ?></textarea>

                            <div class="pc-help">
                                The content is stored directly in the existing
                                <strong>pages.content</strong> column.
                            </div>

                        </div>


                        <!-- MEDIA -->

                        <div class="pc-form-group">

                            <label class="pc-label">
                                Featured Media
                            </label>

                            <select
                                name="featured_media_id"
                                class="pc-select"
                            >

                                <option value="">
                                    — No Featured Media —
                                </option>

                                <?php foreach ($mediaItems as $media): ?>

                                    <option
                                        value="<?= (int)$media['id'] ?>"
                                        <?= $formFeaturedMediaId !== null &&
                                            (int)$formFeaturedMediaId ===
                                            (int)$media['id']
                                                ? 'selected'
                                                : ''
                                        ?>
                                    >
                                        <?php
                                            $mediaLabel = trim((string)($media['original_name'] ?? ''));
                                            if ($mediaLabel === '') {
                                                $mediaLabel = trim((string)($media['file_name'] ?? ''));
                                            }
                                            if ($mediaLabel === '') {
                                                $mediaLabel = 'Media file';
                                            }
                                        ?>
                                        <?= e($mediaLabel) ?> — #<?= (int)$media['id'] ?>
                                        (<?= e($media['file_type'] ?? 'other') ?>)
                                    </option>

                                <?php endforeach; ?>

                            </select>

                            <div class="pc-help">
                                Choose an existing media item above, or upload a new featured image below.
                                The new image will be saved to the media library and linked to this page.
                            </div>

                            <label class="pc-label" style="margin-top:14px;">
                                Upload Featured Image <span style="font-weight:400;color:#64748b;">(optional, max 8 MB)</span>
                            </label>
                            <input
                                type="file"
                                name="featured_upload"
                                class="pc-input"
                                accept=".jpg,.jpeg,.png,.gif,.webp,image/jpeg,image/png,image/gif,image/webp"
                            >
                            <div class="pc-help">Allowed formats: JPG, PNG, GIF, WEBP. If you upload a new image, it will replace the selected featured media for this page.</div>

                        </div>


                        <!-- STATUS -->

                        <div class="pc-form-group">

                            <label class="pc-label">
                                Status
                            </label>

                            <div class="pc-status-wrap">


                                <div class="pc-status-option">

                                    <input
                                        type="radio"
                                        id="statusDraft"
                                        name="status"
                                        value="draft"
                                        <?= $formStatus === 'draft'
                                            ? 'checked'
                                            : ''
                                        ?>
                                    >

                                    <label for="statusDraft">

                                        <i class="fa-solid fa-pen-ruler"></i>

                                        Draft

                                    </label>

                                </div>


                                <div class="pc-status-option published">

                                    <input
                                        type="radio"
                                        id="statusPublished"
                                        name="status"
                                        value="published"
                                        <?= $formStatus === 'published'
                                            ? 'checked'
                                            : ''
                                        ?>
                                    >

                                    <label for="statusPublished">

                                        <i class="fa-solid fa-circle-check"></i>

                                        Published

                                    </label>

                                </div>


                                <div class="pc-status-option inactive">

                                    <input
                                        type="radio"
                                        id="statusInactive"
                                        name="status"
                                        value="inactive"
                                        <?= $formStatus === 'inactive'
                                            ? 'checked'
                                            : ''
                                        ?>
                                    >

                                    <label for="statusInactive">

                                        <i class="fa-solid fa-ban"></i>

                                        Inactive

                                    </label>

                                </div>


                            </div>

                        </div>


                        <!-- SORT + DATE -->

                        <div class="pc-row">


                            <div class="pc-form-group">

                                <label class="pc-label">
                                    Sort Order
                                </label>

                                <input
                                    type="number"
                                    name="sort_order"
                                    class="pc-input"
                                    value="<?= (int)$formSortOrder ?>"
                                    min="0"
                                    step="1"
                                >

                            </div>


                            <div class="pc-form-group">

                                <label class="pc-label">
                                    Published At
                                </label>

                                <input
                                    type="datetime-local"
                                    name="published_at"
                                    id="publishedAt"
                                    class="pc-input"
                                    value="<?= e($formPublishedAt) ?>"
                                >

                                <div class="pc-help">
                                    For published pages, blank date automatically uses current time.
                                </div>

                            </div>


                        </div>


                        <!-- ACTION -->

                        <div class="pc-form-actions">

                            <button
                                type="submit"
                                class="pc-btn pc-btn-primary"
                            >

                                <i
                                    class="fa-solid <?= $editId > 0
                                        ? 'fa-floppy-disk'
                                        : 'fa-plus'
                                    ?>"
                                ></i>

                                <?= $editId > 0
                                    ? 'Update Page'
                                    : 'Create Page'
                                ?>

                            </button>


                            <?php if ($editId > 0): ?>

                                <a
                                    href="pages.php"
                                    class="pc-btn pc-btn-light"
                                >

                                    <i class="fa-solid fa-xmark"></i>

                                    Cancel

                                </a>

                            <?php else: ?>

                                <button
                                    type="reset"
                                    class="pc-btn pc-btn-light"
                                >

                                    <i class="fa-solid fa-rotate-left"></i>

                                    Reset

                                </button>

                            <?php endif; ?>

                        </div>

                    </form>

                </div>

            </div>


            <!-- =================================================
                 LIST
            ================================================== -->

            <div class="pc-card">

                <div class="pc-card-head">

                    <div>

                        <h2 class="pc-card-title">
                            Website Pages
                        </h2>

                        <p class="pc-card-subtitle">
                            Manage all pages and their hierarchy.
                        </p>

                    </div>

                    <span
                        style="
                            display:inline-flex;
                            align-items:center;
                            gap:6px;
                            padding:7px 10px;
                            background:#eff6ff;
                            color:#2563eb;
                            border-radius:999px;
                            font-size:10px;
                            font-weight:800;
                        "
                    >

                        <i class="fa-solid fa-file-lines"></i>

                        <?= number_format(count($pages)) ?>

                    </span>

                </div>


                <!-- FILTER -->

                <form
                    method="GET"
                    action="pages.php"
                    class="pc-toolbar"
                >

                    <div class="pc-search">

                        <i
                            class="fa-solid fa-magnifying-glass"
                        ></i>

                        <input
                            type="text"
                            name="q"
                            value="<?= e($search) ?>"
                            placeholder="Search title, slug or excerpt..."
                        >

                    </div>


                    <select
                        name="page_type"
                        class="pc-filter"
                    >

                        <option value="">
                            All Types
                        </option>

                        <?php foreach ($pageTypes as $type): ?>

                            <option
                                value="<?= e($type['page_type']) ?>"
                                <?= $typeFilter === $type['page_type']
                                    ? 'selected'
                                    : ''
                                ?>
                            >
                                <?= e($type['page_type']) ?>
                            </option>

                        <?php endforeach; ?>

                    </select>


                    <select
                        name="status"
                        class="pc-filter"
                    >

                        <option value="">
                            All Status
                        </option>

                        <option
                            value="published"
                            <?= $statusFilter === 'published'
                                ? 'selected'
                                : ''
                            ?>
                        >
                            Published
                        </option>

                        <option
                            value="draft"
                            <?= $statusFilter === 'draft'
                                ? 'selected'
                                : ''
                            ?>
                        >
                            Draft
                        </option>

                        <option
                            value="inactive"
                            <?= $statusFilter === 'inactive'
                                ? 'selected'
                                : ''
                            ?>
                        >
                            Inactive
                        </option>

                    </select>


                    <select
                        name="parent"
                        class="pc-filter"
                    >

                        <option value="">
                            All Parents
                        </option>

                        <option
                            value="0"
                            <?= $parentFilter === 0
                                ? 'selected'
                                : ''
                            ?>
                        >
                            Root Pages
                        </option>

                        <?php foreach ($allPages as $parentPage): ?>

                            <?php
                            if (
                                $editId > 0 &&
                                (int)$parentPage['id'] === $editId
                            ) {
                                continue;
                            }
                            ?>

                            <option
                                value="<?= (int)$parentPage['id'] ?>"
                                <?= $parentFilter ===
                                    (int)$parentPage['id']
                                        ? 'selected'
                                        : ''
                                ?>
                            >
                                <?= e($parentPage['title']) ?>
                            </option>

                        <?php endforeach; ?>

                    </select>


                    <button
                        type="submit"
                        class="pc-btn pc-btn-primary"
                        style="min-height:41px;"
                    >

                        <i class="fa-solid fa-filter"></i>

                        Filter

                    </button>


                    <?php if (
                        $search !== '' ||
                        $statusFilter !== '' ||
                        $typeFilter !== '' ||
                        $parentFilter !== null
                    ): ?>

                        <a
                            href="pages.php"
                            class="pc-btn pc-btn-light"
                            style="min-height:41px;"
                            title="Clear filters"
                        >

                            <i class="fa-solid fa-xmark"></i>

                        </a>

                    <?php endif; ?>

                </form>


                <!-- TABLE -->

                <?php if (!empty($pages)): ?>

                    <div class="pc-table-wrap">

                        <table class="pc-table">

                            <thead>

                                <tr>

                                    <th>
                                        Page
                                    </th>

                                    <th>
                                        Parent
                                    </th>

                                    <th>
                                        Type
                                    </th>

                                    <th>
                                        Template
                                    </th>

                                    <th>
                                        Children
                                    </th>

                                    <th>
                                        Status
                                    </th>

                                    <th>
                                        Updated
                                    </th>

                                    <th style="text-align:right;">
                                        Actions
                                    </th>

                                </tr>

                            </thead>


                            <tbody>

                                <?php foreach ($pages as $page): ?>

                                    <tr>


                                        <!-- PAGE -->

                                        <td>

                                            <div class="pc-page">

                                                <div class="pc-page-icon">

                                                    <i
                                                        class="fa-solid fa-file-lines"
                                                    ></i>

                                                </div>

                                                <div>

                                                    <div class="pc-page-title-text">

                                                        <?= e(
                                                            $page['title']
                                                        ) ?>

                                                    </div>

                                                    <div class="pc-page-slug">

                                                        /<?= e(
                                                            $page['slug']
                                                        ) ?>

                                                    </div>

                                                </div>

                                            </div>

                                        </td>


                                        <!-- PARENT -->

                                        <td>

                                            <?php if (
                                                $page['parent_id'] !== null
                                            ): ?>

                                                <span class="pc-parent">

                                                    <i
                                                        class="fa-solid fa-sitemap"
                                                    ></i>

                                                    <?= e(
                                                        $page['parent_title']
                                                        ?: 'Unknown'
                                                    ) ?>

                                                </span>

                                            <?php else: ?>

                                                <span class="pc-parent pc-root">

                                                    <i
                                                        class="fa-solid fa-house"
                                                    ></i>

                                                    Root

                                                </span>

                                            <?php endif; ?>

                                        </td>


                                        <!-- TYPE -->

                                        <td>

                                            <span class="pc-type">

                                                <?= e(
                                                    $page['page_type']
                                                ) ?>

                                            </span>

                                        </td>


                                        <!-- TEMPLATE -->

                                        <td>

                                            <span class="pc-template">

                                                <?= e(
                                                    $page['template']
                                                ) ?>

                                            </span>

                                        </td>


                                        <!-- CHILDREN -->

                                        <td>

                                            <span class="pc-child-count">

                                                <i
                                                    class="fa-solid fa-code-branch"
                                                    style="margin-right:4px;"
                                                ></i>

                                                <?= number_format(
                                                    (int)$page['child_count']
                                                ) ?>

                                            </span>

                                        </td>


                                        <!-- STATUS -->

                                        <td>

                                            <?php if (
                                                $page['status'] ===
                                                'published'
                                            ): ?>

                                                <span
                                                    class="pc-badge published"
                                                >

                                                    <i
                                                        class="fa-solid fa-circle-check"
                                                    ></i>

                                                    Published

                                                </span>

                                            <?php elseif (
                                                $page['status'] ===
                                                'inactive'
                                            ): ?>

                                                <span
                                                    class="pc-badge inactive"
                                                >

                                                    <i
                                                        class="fa-solid fa-ban"
                                                    ></i>

                                                    Inactive

                                                </span>

                                            <?php else: ?>

                                                <span
                                                    class="pc-badge draft"
                                                >

                                                    <i
                                                        class="fa-solid fa-pen-ruler"
                                                    ></i>

                                                    Draft

                                                </span>

                                            <?php endif; ?>

                                        </td>


                                        <!-- UPDATED -->

                                        <td>

                                            <span
                                                style="
                                                    color:#64748b;
                                                    font-size:9px;
                                                    font-weight:600;
                                                    white-space:nowrap;
                                                "
                                            >

                                                <?= format_page_date(
                                                    $page['updated_at']
                                                ) ?>

                                            </span>

                                        </td>


                                        <!-- ACTIONS -->

                                        <td>

                                            <div class="pc-actions">


                                                <!-- EDIT -->

                                                <a
                                                    href="pages.php?edit=<?= (int)$page['id'] ?>"
                                                    class="pc-action edit"
                                                    title="Edit page"
                                                >

                                                    <i
                                                        class="fa-solid fa-pen"
                                                    ></i>

                                                </a>


                                                <!-- STATUS -->

                                                <?php
                                                $nextStatus =
                                                    $page['status'] === 'published'
                                                        ? 'draft'
                                                        : 'published';
                                                ?>

                                                <form
                                                    method="POST"
                                                    action="pages.php"
                                                    style="display:inline;"
                                                >

                                                    <?= csrf_field() ?>

                                                    <input
                                                        type="hidden"
                                                        name="action"
                                                        value="change_status"
                                                    >

                                                    <input
                                                        type="hidden"
                                                        name="id"
                                                        value="<?= (int)$page['id'] ?>"
                                                    >

                                                    <input
                                                        type="hidden"
                                                        name="new_status"
                                                        value="<?= e($nextStatus) ?>"
                                                    >

                                                    <button
                                                        type="submit"
                                                        class="pc-action publish"
                                                        title="<?= $nextStatus === 'published'
                                                            ? 'Publish'
                                                            : 'Move to Draft'
                                                        ?>"
                                                    >

                                                        <i
                                                            class="fa-solid <?= $nextStatus === 'published'
                                                                ? 'fa-eye'
                                                                : 'fa-eye-slash'
                                                            ?>"
                                                        ></i>

                                                    </button>

                                                </form>


                                                <!-- DELETE -->

                                                <form
                                                    method="POST"
                                                    action="pages.php"
                                                    style="display:inline;"
                                                    onsubmit="return confirmDeletePage(this);"
                                                >

                                                    <?= csrf_field() ?>

                                                    <input
                                                        type="hidden"
                                                        name="action"
                                                        value="delete"
                                                    >

                                                    <input
                                                        type="hidden"
                                                        name="id"
                                                        value="<?= (int)$page['id'] ?>"
                                                    >

                                                    <button
                                                        type="submit"
                                                        class="pc-action delete"
                                                        title="Delete page"
                                                    >

                                                        <i
                                                            class="fa-solid fa-trash"
                                                        ></i>

                                                    </button>

                                                </form>


                                            </div>

                                        </td>

                                    </tr>

                                <?php endforeach; ?>

                            </tbody>

                        </table>

                    </div>

                <?php else: ?>

                    <div class="pc-empty">

                        <div class="pc-empty-icon">

                            <i
                                class="fa-solid fa-file-circle-xmark"
                            ></i>

                        </div>

                        <h3>
                            No pages found
                        </h3>

                        <p>

                            <?php if (
                                $search !== '' ||
                                $statusFilter !== '' ||
                                $typeFilter !== '' ||
                                $parentFilter !== null
                            ): ?>

                                Try changing your filters or search term.

                            <?php else: ?>

                                Create your first website page
                                using the form.

                            <?php endif; ?>

                        </p>

                    </div>

                <?php endif; ?>


            </div>

        </section>

    </main>

</div>


<script>

/* =========================================================
   SLUG GENERATOR
========================================================= */

(function () {

    const titleInput =
        document.getElementById(
            'pageTitleInput'
        );

    const slugInput =
        document.getElementById(
            'pageSlugInput'
        );

    if (!titleInput || !slugInput) {
        return;
    }

    let slugTouched =
        <?= $editId > 0 ? 'true' : 'false' ?>;

    slugInput.addEventListener(
        'input',
        function () {

            slugTouched = true;

        }
    );

    titleInput.addEventListener(
        'input',
        function () {

            if (slugTouched) {
                return;
            }

            let value =
                this.value
                    .toLowerCase()
                    .trim();

            value =
                value
                    .normalize('NFD')
                    .replace(
                        /[\u0300-\u036f]/g,
                        ''
                    );

            value =
                value
                    .replace(
                        /[^a-z0-9]+/g,
                        '-'
                    )
                    .replace(
                        /^-+|-+$/g,
                        ''
                    );

            slugInput.value = value;

        }
    );

})();


/* =========================================================
   DELETE CONFIRM
========================================================= */

function confirmDeletePage(form) {

    const row =
        form.closest('tr');

    if (!row) {
        return confirm(
            'Are you sure you want to delete this page?'
        );
    }

    const titleElement =
        row.querySelector(
            '.pc-page-title-text'
        );

    const title =
        titleElement
            ? titleElement.textContent.trim()
            : 'this page';

    return confirm(
        'Delete "' +
        title +
        '"?\n\n' +
        'This action cannot be undone.\n' +
        'Pages containing child pages cannot be deleted.'
    );
}


/* =========================================================
   AUTO PUBLISHED DATE
========================================================= */

const publishedRadio =
    document.getElementById(
        'statusPublished'
    );

const publishedAt =
    document.getElementById(
        'publishedAt'
    );

if (publishedRadio && publishedAt) {

    publishedRadio.addEventListener(
        'change',
        function () {

            if (
                this.checked &&
                !publishedAt.value
            ) {

                const now =
                    new Date();

                const year =
                    now.getFullYear();

                const month =
                    String(
                        now.getMonth() + 1
                    ).padStart(
                        2,
                        '0'
                    );

                const day =
                    String(
                        now.getDate()
                    ).padStart(
                        2,
                        '0'
                    );

                const hours =
                    String(
                        now.getHours()
                    ).padStart(
                        2,
                        '0'
                    );

                const minutes =
                    String(
                        now.getMinutes()
                    ).padStart(
                        2,
                        '0'
                    );

                publishedAt.value =
                    year +
                    '-' +
                    month +
                    '-' +
                    day +
                    'T' +
                    hours +
                    ':' +
                    minutes;
            }

        }
    );

}


/* =========================================================
   ALERT AUTO HIDE
========================================================= */

setTimeout(
    function () {

        document
            .querySelectorAll(
                '.pc-alert'
            )
            .forEach(
                function (alert) {

                    alert.style.transition =
                        'opacity .3s ease, transform .3s ease';

                    alert.style.opacity =
                        '0';

                    alert.style.transform =
                        'translateY(-5px)';

                    setTimeout(
                        function () {
                            alert.remove();
                        },
                        350
                    );

                }
            );

    },
    4500
);

</script>

</body>

</html>