<?php
/**
 * Pure Chemical Admin
 * File: admin/seo.php
 *
 * Existing table used:
 * seo_meta
 *
 * No new table required.
 */

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/includes/db.php';

if (file_exists(__DIR__ . '/includes/auth.php')) {
    require_once __DIR__ . '/includes/auth.php';
}

if (function_exists('requireAdmin')) {
    requireAdmin();
}

/* ============================================================
   HELPERS
============================================================ */

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('csrf_token')) {
    function csrf_token()
    {
        if (empty($_SESSION['_csrf_token'])) {
            $_SESSION['_csrf_token'] = bin2hex(random_bytes(32));
        }

        return $_SESSION['_csrf_token'];
    }
}

if (!function_exists('csrf_field')) {
    function csrf_field()
    {
        return '<input type="hidden" name="_csrf_token" value="' .
            e(csrf_token()) .
            '">';
    }
}

if (!function_exists('csrf_verify')) {
    function csrf_verify($token = null)
    {
        $token = $token ?? ($_POST['_csrf_token'] ?? '');

        return !empty($_SESSION['_csrf_token'])
            && !empty($token)
            && hash_equals($_SESSION['_csrf_token'], $token);
    }
}

function seoRedirect($type, $message)
{
    header(
        'Location: seo.php?' .
        http_build_query([
            'msg'  => $type,
            'text' => $message
        ])
    );

    exit;
}

function cleanNullable($value)
{
    $value = trim((string)$value);

    return $value === '' ? null : $value;
}

function validUrlOrEmpty($url)
{
    $url = trim((string)$url);

    if ($url === '') {
        return true;
    }

    return filter_var($url, FILTER_VALIDATE_URL) !== false;
}

function validateJsonOrEmpty($json)
{
    $json = trim((string)$json);

    if ($json === '') {
        return true;
    }

    json_decode($json, true);

    return json_last_error() === JSON_ERROR_NONE;
}


/**
 * Save an uploaded social image into the existing media library.
 * uploaded_by is intentionally NULL to respect the optional users FK.
 */
function uploadSeoImage(PDO $pdo, string $fieldName): ?int
{
    if (
        !isset($_FILES[$fieldName]) ||
        !is_array($_FILES[$fieldName]) ||
        ($_FILES[$fieldName]['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE
    ) {
        return null;
    }

    $file = $_FILES[$fieldName];

    if (($file['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) {
        seoRedirect('error', 'Image upload failed. Please check PHP upload limits and try again.');
    }

    if ((int)($file['size'] ?? 0) <= 0 || (int)$file['size'] > 8 * 1024 * 1024) {
        seoRedirect('error', 'SEO images must be smaller than 8 MB.');
    }

    if (!is_uploaded_file($file['tmp_name'] ?? '')) {
        seoRedirect('error', 'Invalid uploaded image.');
    }

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = $finfo->file($file['tmp_name']);
    $allowed = [
        'image/jpeg' => 'jpg',
        'image/png'  => 'png',
        'image/webp' => 'webp',
        'image/gif'  => 'gif',
    ];

    if (!isset($allowed[$mime])) {
        seoRedirect('error', 'Only JPG, PNG, WEBP and GIF images are allowed.');
    }

    $uploadDir = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'seo';
    if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true) && !is_dir($uploadDir)) {
        seoRedirect('error', 'Could not create uploads/seo folder. Check folder permissions.');
    }

    $extension = $allowed[$mime];
    $storedName = 'seo_' . bin2hex(random_bytes(16)) . '.' . $extension;
    $absolutePath = $uploadDir . DIRECTORY_SEPARATOR . $storedName;
    $relativePath = 'uploads/seo/' . $storedName;

    if (!move_uploaded_file($file['tmp_name'], $absolutePath)) {
        seoRedirect('error', 'Image could not be saved. Check uploads folder permissions.');
    }

    $dimensions = @getimagesize($absolutePath);
    $width = is_array($dimensions) ? (int)$dimensions[0] : null;
    $height = is_array($dimensions) ? (int)$dimensions[1] : null;
    $originalName = basename((string)($file['name'] ?? $storedName));
    $originalName = mb_substr($originalName, 0, 255);

    try {
        $stmt = $pdo->prepare("
            INSERT INTO media
                (original_name, file_name, file_path, mime_type, file_type, extension,
                 file_size, width, height, alt_text, title, uploaded_by, status)
            VALUES
                (:original_name, :file_name, :file_path, :mime_type, 'image', :extension,
                 :file_size, :width, :height, NULL, :title, NULL, 1)
        ");
        $stmt->execute([
            ':original_name' => $originalName,
            ':file_name' => $storedName,
            ':file_path' => $relativePath,
            ':mime_type' => $mime,
            ':extension' => $extension,
            ':file_size' => (int)$file['size'],
            ':width' => $width,
            ':height' => $height,
            ':title' => mb_substr(pathinfo($originalName, PATHINFO_FILENAME), 0, 255),
        ]);
        return (int)$pdo->lastInsertId();
    } catch (Throwable $ex) {
        if (is_file($absolutePath)) {
            @unlink($absolutePath);
        }
        seoRedirect('error', 'Image upload failed while saving to the media library. Verify the media table columns and database permissions.');
    }
}

function seoImageExists(PDO $pdo, int $mediaId): bool
{
    if ($mediaId <= 0) {
        return true;
    }

    $stmt = $pdo->prepare("
        SELECT id FROM media
        WHERE id = :id AND file_type = 'image' AND status = 1
        LIMIT 1
    ");
    $stmt->execute([':id' => $mediaId]);
    return (bool)$stmt->fetchColumn();
}

/* ============================================================
   DEFAULTS
============================================================ */

$defaultSeo = [
    'id'                  => 0,
    'entity_type'         => '',
    'entity_id'           => '',
    'meta_title'          => '',
    'meta_description'    => '',
    'meta_keywords'       => '',
    'canonical_url'       => '',
    'robots'              => 'index,follow',
    'og_title'            => '',
    'og_description'      => '',
    'og_image_id'         => '',
    'twitter_title'       => '',
    'twitter_description' => '',
    'twitter_image_id'    => '',
    'schema_json'          => ''
];

/* ============================================================
   POST ACTIONS
============================================================ */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!csrf_verify()) {
        seoRedirect(
            'error',
            'Security token expired. Please refresh the page and try again.'
        );
    }

    $action = $_POST['action'] ?? '';

    /* ========================================================
       SAVE SEO
    ======================================================== */

    if ($action === 'save') {

        $id = (int)($_POST['id'] ?? 0);

        $entityType = trim($_POST['entity_type'] ?? '');
        $entityId   = (int)($_POST['entity_id'] ?? 0);

        $metaTitle = cleanNullable(
            $_POST['meta_title'] ?? ''
        );

        $metaDescription = cleanNullable(
            $_POST['meta_description'] ?? ''
        );

        $metaKeywords = cleanNullable(
            $_POST['meta_keywords'] ?? ''
        );

        $canonicalUrl = cleanNullable(
            $_POST['canonical_url'] ?? ''
        );

        $robots = trim(
            $_POST['robots'] ?? 'index,follow'
        );

        $ogTitle = cleanNullable(
            $_POST['og_title'] ?? ''
        );

        $ogDescription = cleanNullable(
            $_POST['og_description'] ?? ''
        );

        $ogImageId = (int)(
            $_POST['og_image_id'] ?? 0
        );

        $twitterTitle = cleanNullable(
            $_POST['twitter_title'] ?? ''
        );

        $twitterDescription = cleanNullable(
            $_POST['twitter_description'] ?? ''
        );

        $twitterImageId = (int)(
            $_POST['twitter_image_id'] ?? 0
        );

        $schemaJson = cleanNullable(
            $_POST['schema_json'] ?? ''
        );

        /* ----------------------------------------------------
           Validation
        ---------------------------------------------------- */

        if ($entityType === '') {
            seoRedirect(
                'error',
                'Entity type is required.'
            );
        }

        if (strlen($entityType) > 100) {
            seoRedirect(
                'error',
                'Entity type cannot exceed 100 characters.'
            );
        }

        if ($entityId <= 0) {
            seoRedirect(
                'error',
                'Please enter a valid entity ID.'
            );
        }

        if ($metaTitle !== null && mb_strlen($metaTitle) > 255) {
            seoRedirect(
                'error',
                'Meta title cannot exceed 255 characters.'
            );
        }

        if (
            $canonicalUrl !== null &&
            !validUrlOrEmpty($canonicalUrl)
        ) {
            seoRedirect(
                'error',
                'Please enter a valid canonical URL.'
            );
        }

        if (
            $canonicalUrl !== null &&
            strlen($canonicalUrl) > 1000
        ) {
            seoRedirect(
                'error',
                'Canonical URL cannot exceed 1000 characters.'
            );
        }

        if (strlen($robots) > 100) {
            seoRedirect(
                'error',
                'Robots value cannot exceed 100 characters.'
            );
        }

        if (
            $ogImageId < 0 ||
            $twitterImageId < 0
        ) {
            seoRedirect(
                'error',
                'Invalid image ID.'
            );
        }

        if (
            $schemaJson !== null &&
            !validateJsonOrEmpty($schemaJson)
        ) {
            seoRedirect(
                'error',
                'Schema JSON contains invalid JSON.'
            );
        }

        /* ----------------------------------------------------
           Duplicate entity check
        ---------------------------------------------------- */

        $stmt = $pdo->prepare("
            SELECT id
            FROM seo_meta
            WHERE entity_type = :entity_type
              AND entity_id = :entity_id
              AND id != :id
            LIMIT 1
        ");

        $stmt->execute([
            ':entity_type' => $entityType,
            ':entity_id'   => $entityId,
            ':id'          => $id
        ]);

        if ($stmt->fetch()) {
            seoRedirect(
                'error',
                'SEO data already exists for this entity type and entity ID.'
            );
        }

        // Validate selected media IDs unless a replacement upload was supplied.
        $hasOgUpload = isset($_FILES['og_image_upload'])
            && ($_FILES['og_image_upload']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE;
        $hasTwitterUpload = isset($_FILES['twitter_image_upload'])
            && ($_FILES['twitter_image_upload']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE;

        if ((!$hasOgUpload && !seoImageExists($pdo, $ogImageId))
            || (!$hasTwitterUpload && !seoImageExists($pdo, $twitterImageId))) {
            seoRedirect('error', 'Selected social image was not found in the active image media library.');
        }

        // A newly uploaded image takes precedence over the selected media item.
        $uploadedOgImage = uploadSeoImage($pdo, 'og_image_upload');
        $uploadedTwitterImage = uploadSeoImage($pdo, 'twitter_image_upload');
        if ($uploadedOgImage !== null) {
            $ogImageId = $uploadedOgImage;
        }
        if ($uploadedTwitterImage !== null) {
            $twitterImageId = $uploadedTwitterImage;
        }

        /* ----------------------------------------------------
           Insert
        ---------------------------------------------------- */

        if ($id <= 0) {

            $stmt = $pdo->prepare("
                INSERT INTO seo_meta
                (
                    entity_type,
                    entity_id,
                    meta_title,
                    meta_description,
                    meta_keywords,
                    canonical_url,
                    robots,
                    og_title,
                    og_description,
                    og_image_id,
                    twitter_title,
                    twitter_description,
                    twitter_image_id,
                    schema_json
                )
                VALUES
                (
                    :entity_type,
                    :entity_id,
                    :meta_title,
                    :meta_description,
                    :meta_keywords,
                    :canonical_url,
                    :robots,
                    :og_title,
                    :og_description,
                    :og_image_id,
                    :twitter_title,
                    :twitter_description,
                    :twitter_image_id,
                    :schema_json
                )
            ");

            $stmt->execute([
                ':entity_type'         => $entityType,
                ':entity_id'           => $entityId,
                ':meta_title'          => $metaTitle,
                ':meta_description'    => $metaDescription,
                ':meta_keywords'       => $metaKeywords,
                ':canonical_url'       => $canonicalUrl,
                ':robots'              => $robots ?: 'index,follow',
                ':og_title'            => $ogTitle,
                ':og_description'      => $ogDescription,
                ':og_image_id'         => $ogImageId > 0 ? $ogImageId : null,
                ':twitter_title'       => $twitterTitle,
                ':twitter_description' => $twitterDescription,
                ':twitter_image_id'    => $twitterImageId > 0
                    ? $twitterImageId
                    : null,
                ':schema_json'         => $schemaJson
            ]);

            seoRedirect(
                'success',
                'SEO record created successfully.'
            );
        }

        /* ----------------------------------------------------
           Update
        ---------------------------------------------------- */

        $stmt = $pdo->prepare("
            UPDATE seo_meta
            SET
                entity_type = :entity_type,
                entity_id = :entity_id,
                meta_title = :meta_title,
                meta_description = :meta_description,
                meta_keywords = :meta_keywords,
                canonical_url = :canonical_url,
                robots = :robots,
                og_title = :og_title,
                og_description = :og_description,
                og_image_id = :og_image_id,
                twitter_title = :twitter_title,
                twitter_description = :twitter_description,
                twitter_image_id = :twitter_image_id,
                schema_json = :schema_json
            WHERE id = :id
            LIMIT 1
        ");

        $stmt->execute([
            ':entity_type'         => $entityType,
            ':entity_id'           => $entityId,
            ':meta_title'          => $metaTitle,
            ':meta_description'    => $metaDescription,
            ':meta_keywords'       => $metaKeywords,
            ':canonical_url'       => $canonicalUrl,
            ':robots'              => $robots ?: 'index,follow',
            ':og_title'            => $ogTitle,
            ':og_description'      => $ogDescription,
            ':og_image_id'         => $ogImageId > 0 ? $ogImageId : null,
            ':twitter_title'       => $twitterTitle,
            ':twitter_description' => $twitterDescription,
            ':twitter_image_id'    => $twitterImageId > 0
                ? $twitterImageId
                : null,
            ':schema_json'         => $schemaJson,
            ':id'                  => $id
        ]);

        seoRedirect(
            'success',
            'SEO record updated successfully.'
        );
    }

    /* ========================================================
       DELETE
    ======================================================== */

    if ($action === 'delete') {

        $id = (int)($_POST['id'] ?? 0);

        if ($id <= 0) {
            seoRedirect(
                'error',
                'Invalid SEO record.'
            );
        }

        $stmt = $pdo->prepare("
            DELETE FROM seo_meta
            WHERE id = :id
            LIMIT 1
        ");

        $stmt->execute([
            ':id' => $id
        ]);

        seoRedirect(
            'success',
            'SEO record deleted successfully.'
        );
    }
}

/* ============================================================
   MESSAGES
============================================================ */

$messageType = $_GET['msg'] ?? '';
$messageText = $_GET['text'] ?? '';

if (!in_array($messageType, ['success', 'error'], true)) {
    $messageType = '';
}

/* ============================================================
   EDIT RECORD
============================================================ */

$editId = (int)($_GET['edit'] ?? 0);

$editSeo = $defaultSeo;

if ($editId > 0) {

    $stmt = $pdo->prepare("
        SELECT
            id,
            entity_type,
            entity_id,
            meta_title,
            meta_description,
            meta_keywords,
            canonical_url,
            robots,
            og_title,
            og_description,
            og_image_id,
            twitter_title,
            twitter_description,
            twitter_image_id,
            schema_json
        FROM seo_meta
        WHERE id = :id
        LIMIT 1
    ");

    $stmt->execute([
        ':id' => $editId
    ]);

    $record = $stmt->fetch();

    if ($record) {
        $editSeo = array_merge(
            $defaultSeo,
            $record
        );
    } else {
        $editId = 0;
    }
}

/* ============================================================
   FILTERS
============================================================ */

$search = trim($_GET['q'] ?? '');
$entityFilter = trim($_GET['entity_type'] ?? '');

/* ============================================================
   LIST QUERY
============================================================ */

$where = [];
$params = [];

if ($search !== '') {

    $where[] = "
        (
            entity_type LIKE :search_type
            OR CAST(entity_id AS CHAR) LIKE :search_id
            OR meta_title LIKE :search_title
            OR meta_description LIKE :search_description
            OR canonical_url LIKE :search_url
        )
    ";

    $like = '%' . $search . '%';

    $params[':search_type'] = $like;
    $params[':search_id'] = $like;
    $params[':search_title'] = $like;
    $params[':search_description'] = $like;
    $params[':search_url'] = $like;
}

if ($entityFilter !== '') {

    $where[] = "
        entity_type = :entity_filter
    ";

    $params[':entity_filter'] = $entityFilter;
}

$whereSql = '';

if (!empty($where)) {
    $whereSql = 'WHERE ' . implode(
        ' AND ',
        $where
    );
}

$stmt = $pdo->prepare("
    SELECT
        id,
        entity_type,
        entity_id,
        meta_title,
        meta_description,
        canonical_url,
        robots,
        og_title,
        og_image_id,
        twitter_title,
        twitter_image_id,
        schema_json,
        created_at,
        updated_at
    FROM seo_meta
    $whereSql
    ORDER BY id DESC
");

$stmt->execute($params);

$seoRows = $stmt->fetchAll();

/* ============================================================
   ENTITY TYPES
============================================================ */

$stmt = $pdo->query("
    SELECT DISTINCT entity_type
    FROM seo_meta
    WHERE entity_type <> ''
    ORDER BY entity_type ASC
");

$entityTypes = $stmt->fetchAll(
    PDO::FETCH_COLUMN
);

/* ============================================================
   GLOBAL STATS
============================================================ */

$stmt = $pdo->query("
    SELECT COUNT(*)
    FROM seo_meta
");

$totalSeo = (int)$stmt->fetchColumn();

$stmt = $pdo->query("
    SELECT COUNT(*)
    FROM seo_meta
    WHERE meta_title IS NOT NULL
      AND meta_title <> ''
");

$optimizedTitles = (int)$stmt->fetchColumn();

$stmt = $pdo->query("
    SELECT COUNT(*)
    FROM seo_meta
    WHERE meta_description IS NOT NULL
      AND meta_description <> ''
");

$optimizedDescriptions = (int)$stmt->fetchColumn();

$stmt = $pdo->query("
    SELECT COUNT(*)
    FROM seo_meta
    WHERE schema_json IS NOT NULL
      AND schema_json <> ''
");

$schemaRecords = (int)$stmt->fetchColumn();

/* Existing active image records for the social image selectors. */
$mediaImages = [];
try {
    $mediaStmt = $pdo->query("
        SELECT id, original_name, file_path, mime_type
        FROM media
        WHERE file_type = 'image' AND status = 1
        ORDER BY id DESC
    ");
    $mediaImages = $mediaStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $ex) {
    $mediaImages = [];
}

?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>
        SEO Manager - Pure Chemical Admin
    </title>

    <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: #16a34a;
            --primary-dark: #15803d;
            --primary-soft: #ecfdf3;

            --blue: #2563eb;
            --blue-soft: #eff6ff;

            --purple: #7c3aed;
            --purple-soft: #f5f3ff;

            --orange: #ea580c;
            --orange-soft: #fff7ed;

            --red: #dc2626;
            --red-soft: #fef2f2;

            --dark: #101828;
            --text: #344054;
            --muted: #667085;

            --border: #e4e7ec;
            --bg: #f7f9fc;
            --white: #ffffff;

            --shadow-sm:
                0 1px 2px rgba(16, 24, 40, .04);

            --shadow-md:
                0 8px 25px rgba(16, 24, 40, .07);

            --shadow-lg:
                0 20px 55px rgba(16, 24, 40, .12);

            --radius: 18px;
        }

        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            background:
                radial-gradient(
                    circle at 15% 10%,
                    rgba(22, 163, 74, .055),
                    transparent 30%
                ),
                var(--bg);

            color: var(--text);
            font-family: "Inter", sans-serif;
            font-size: 14px;
        }

        button,
        input,
        select,
        textarea {
            font: inherit;
        }

        a {
            text-decoration: none;
            color: inherit;
        }

        /* =====================================================
           LAYOUT
        ====================================================== */

        .page-wrapper {
            min-height: 100vh;
            margin-left: 280px;
        }

        .topbar {
            height: 76px;

            position: sticky;
            top: 0;
            z-index: 900;

            display: flex;
            align-items: center;
            justify-content: space-between;

            padding: 0 28px;

            background:
                rgba(255,255,255,.88);

            backdrop-filter: blur(18px);

            border-bottom:
                1px solid rgba(228,231,236,.85);
        }

        .topbar-title {
            margin: 0;

            color: var(--dark);

            font-size: 20px;
            font-weight: 800;

            letter-spacing: -.035em;
        }

        .topbar-subtitle {
            margin-top: 3px;

            color: var(--muted);
            font-size: 12px;
        }

        .topbar-actions {
            display: flex;
            gap: 9px;
        }

        .top-icon {
            width: 40px;
            height: 40px;

            display: flex;
            align-items: center;
            justify-content: center;

            border: 1px solid var(--border);
            border-radius: 12px;

            background: #fff;
            color: #475467;

            transition: .2s ease;
        }

        .top-icon:hover {
            color: var(--primary);
            border-color: #86efac;
            transform: translateY(-1px);
        }

        .main-content {
            max-width: 1800px;
            margin: auto;
            padding: 28px;
        }

        /* =====================================================
           HEADER
        ====================================================== */

        .page-header {
            display: flex;
            align-items: flex-end;
            justify-content: space-between;

            gap: 20px;
            margin-bottom: 24px;
        }

        .eyebrow {
            display: inline-flex;
            align-items: center;
            gap: 7px;

            margin-bottom: 10px;
            padding: 7px 11px;

            border-radius: 999px;

            background: var(--primary-soft);
            color: var(--primary-dark);

            font-size: 10px;
            font-weight: 800;

            text-transform: uppercase;
            letter-spacing: .08em;
        }

        .page-header h1 {
            margin: 0;

            color: var(--dark);

            font-size: 30px;
            font-weight: 800;

            letter-spacing: -.045em;
        }

        .page-header p {
            max-width: 720px;

            margin: 8px 0 0;

            color: var(--muted);

            line-height: 1.6;
        }

        .add-btn {
            height: 45px;

            display: inline-flex;
            align-items: center;
            gap: 8px;

            padding: 0 17px;

            border: 0;
            border-radius: 11px;

            background:
                linear-gradient(
                    135deg,
                    #22c55e,
                    #15803d
                );

            color: #fff;

            font-size: 12px;
            font-weight: 800;

            cursor: pointer;

            box-shadow:
                0 8px 20px rgba(22,163,74,.18);

            transition: .2s ease;
        }

        .add-btn:hover {
            transform: translateY(-1px);
            box-shadow:
                0 12px 25px rgba(22,163,74,.25);
        }

        /* =====================================================
           ALERT
        ====================================================== */

        .alert {
            display: flex;
            align-items: flex-start;
            gap: 12px;

            padding: 14px 16px;
            margin-bottom: 20px;

            border: 1px solid;
            border-radius: 14px;
        }

        .alert.success {
            color: #166534;
            background: var(--primary-soft);
            border-color: #bbf7d0;
        }

        .alert.error {
            color: #991b1b;
            background: var(--red-soft);
            border-color: #fecaca;
        }

        .alert-icon {
            width: 30px;
            height: 30px;

            flex: 0 0 30px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 9px;

            background: rgba(255,255,255,.7);
        }

        .alert-close {
            margin-left: auto;

            border: 0;
            background: transparent;

            color: currentColor;

            cursor: pointer;
        }

        /* =====================================================
           STATS
        ====================================================== */

        .stats {
            display: grid;

            grid-template-columns:
                repeat(4, minmax(0, 1fr));

            gap: 15px;

            margin-bottom: 22px;
        }

        .stat-card {
            position: relative;
            overflow: hidden;

            padding: 19px;

            background: #fff;

            border: 1px solid var(--border);
            border-radius: var(--radius);

            box-shadow: var(--shadow-sm);

            transition: .2s ease;
        }

        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }

        .stat-icon {
            width: 43px;
            height: 43px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 13px;

            background: var(--primary-soft);
            color: var(--primary);
        }

        .stat-icon.blue {
            color: var(--blue);
            background: var(--blue-soft);
        }

        .stat-icon.purple {
            color: var(--purple);
            background: var(--purple-soft);
        }

        .stat-icon.orange {
            color: var(--orange);
            background: var(--orange-soft);
        }

        .stat-number {
            margin-top: 15px;

            color: var(--dark);

            font-size: 26px;
            font-weight: 800;

            letter-spacing: -.04em;
        }

        .stat-label {
            margin-top: 4px;

            color: var(--muted);

            font-size: 11px;
            font-weight: 600;
        }

        /* =====================================================
           FILTER PANEL
        ====================================================== */

        .filter-panel {
            display: flex;
            align-items: center;
            gap: 10px;

            margin-bottom: 18px;
            padding: 15px;

            background: #fff;

            border: 1px solid var(--border);
            border-radius: var(--radius);

            box-shadow: var(--shadow-sm);
        }

        .search-box {
            position: relative;
            flex: 1;
        }

        .search-box i {
            position: absolute;

            left: 13px;
            top: 50%;

            transform: translateY(-50%);

            color: #98a2b3;
        }

        .search-box input {
            width: 100%;
            height: 42px;

            padding:
                0 13px 0 39px;

            border:
                1px solid var(--border);

            border-radius: 11px;

            outline: none;
        }

        .filter-select {
            height: 42px;

            min-width: 160px;

            padding: 0 12px;

            border:
                1px solid var(--border);

            border-radius: 11px;

            background: #fff;

            color: var(--text);

            outline: none;
        }

        .filter-select:focus,
        .search-box input:focus,
        .form-control:focus {
            border-color: #86efac;

            box-shadow:
                0 0 0 4px rgba(34,197,94,.08);
        }

        .filter-btn {
            height: 42px;

            padding: 0 14px;

            display: inline-flex;
            align-items: center;
            gap: 7px;

            border:
                1px solid var(--border);

            border-radius: 11px;

            background: #fff;

            color: #475467;

            font-size: 11px;
            font-weight: 800;

            cursor: pointer;
        }

        /* =====================================================
           TABLE
        ====================================================== */

        .table-card {
            overflow: hidden;

            background: #fff;

            border: 1px solid var(--border);
            border-radius: var(--radius);

            box-shadow: var(--shadow-sm);
        }

        .table-head {
            display: flex;
            align-items: center;
            justify-content: space-between;

            gap: 15px;

            padding: 18px 20px;

            border-bottom: 1px solid var(--border);
        }

        .table-title {
            margin: 0;

            color: var(--dark);

            font-size: 15px;
            font-weight: 800;
        }

        .table-count {
            padding: 6px 9px;

            border-radius: 999px;

            background: #f2f4f7;

            color: #475467;

            font-size: 10px;
            font-weight: 800;
        }

        .table-scroll {
            overflow-x: auto;
        }

        table {
            width: 100%;
            min-width: 1050px;

            border-collapse: collapse;
        }

        th {
            padding: 12px 16px;

            background: #fafbfc;

            color: #667085;

            border-bottom:
                1px solid var(--border);

            font-size: 10px;
            font-weight: 800;

            text-align: left;

            text-transform: uppercase;
            letter-spacing: .045em;
        }

        td {
            padding: 15px 16px;

            border-bottom:
                1px solid #f0f2f5;

            vertical-align: middle;
        }

        tr:last-child td {
            border-bottom: 0;
        }

        tbody tr {
            transition: .15s ease;
        }

        tbody tr:hover {
            background: #fcfefc;
        }

        .entity-cell {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .entity-icon {
            width: 38px;
            height: 38px;

            flex: 0 0 38px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 11px;

            background: var(--primary-soft);
            color: var(--primary);
        }

        .entity-name {
            color: var(--dark);

            font-size: 12px;
            font-weight: 800;
        }

        .entity-id {
            margin-top: 3px;

            color: #98a2b3;

            font-size: 10px;
            font-family: Consolas, monospace;
        }

        .meta-title {
            max-width: 300px;

            color: var(--dark);

            font-size: 12px;
            font-weight: 700;

            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .meta-description {
            max-width: 320px;

            margin-top: 4px;

            color: var(--muted);

            font-size: 10px;
            line-height: 1.5;

            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;

            overflow: hidden;
        }

        .tag {
            display: inline-flex;
            align-items: center;
            gap: 5px;

            padding: 5px 8px;

            border-radius: 7px;

            font-size: 9px;
            font-weight: 800;
        }

        .tag.green {
            color: #166534;
            background: #f0fdf4;
        }

        .tag.blue {
            color: #1d4ed8;
            background: #eff6ff;
        }

        .tag.purple {
            color: #6d28d9;
            background: #f5f3ff;
        }

        .tag.orange {
            color: #9a3412;
            background: #fff7ed;
        }

        .url-text {
            max-width: 230px;

            color: #475467;

            font-size: 10px;

            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .action-buttons {
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .action-btn {
            width: 34px;
            height: 34px;

            display: inline-flex;
            align-items: center;
            justify-content: center;

            border: 1px solid var(--border);
            border-radius: 9px;

            background: #fff;
            color: #667085;

            cursor: pointer;

            transition: .2s ease;
        }

        .action-btn:hover {
            border-color: #86efac;
            color: var(--primary);
            background: #f8fffa;
        }

        .action-btn.delete:hover {
            border-color: #fecaca;
            color: var(--red);
            background: var(--red-soft);
        }

        /* =====================================================
           EMPTY
        ====================================================== */

        .empty-state {
            padding: 70px 25px;

            text-align: center;
        }

        .empty-icon {
            width: 64px;
            height: 64px;

            margin: 0 auto 15px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 20px;

            background: #f2f4f7;
            color: #98a2b3;

            font-size: 25px;
        }

        .empty-state h3 {
            margin: 0;

            color: var(--dark);

            font-size: 16px;
        }

        .empty-state p {
            max-width: 450px;

            margin: 7px auto 0;

            color: var(--muted);

            font-size: 12px;
            line-height: 1.6;
        }

        /* =====================================================
           MODAL
        ====================================================== */

        .modal-backdrop {
            position: fixed;
            inset: 0;
            z-index: 2000;

            display: none;
            align-items: center;
            justify-content: center;

            padding: 20px;

            background:
                rgba(15,23,42,.58);

            backdrop-filter: blur(7px);
        }

        .modal-backdrop.show {
            display: flex;
        }

        .modal {
            width: min(1000px, 100%);

            max-height:
                calc(100vh - 40px);

            overflow-y: auto;

            background: #fff;

            border-radius: 22px;

            box-shadow: var(--shadow-lg);

            animation:
                modalIn .2s ease;
        }

        @keyframes modalIn {
            from {
                opacity: 0;
                transform: translateY(10px) scale(.98);
            }

            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }

        .modal-header {
            position: sticky;
            top: 0;
            z-index: 2;

            display: flex;
            align-items: center;
            justify-content: space-between;

            padding: 18px 22px;

            background:
                rgba(255,255,255,.94);

            backdrop-filter: blur(15px);

            border-bottom:
                1px solid var(--border);
        }

        .modal-title {
            margin: 0;

            color: var(--dark);

            font-size: 17px;
            font-weight: 800;
        }

        .modal-subtitle {
            margin-top: 3px;

            color: var(--muted);

            font-size: 11px;
        }

        .modal-close {
            width: 36px;
            height: 36px;

            display: flex;
            align-items: center;
            justify-content: center;

            border: 1px solid var(--border);
            border-radius: 10px;

            background: #fff;

            color: #667085;

            cursor: pointer;
        }

        .modal-body {
            padding: 22px;
        }

        .form-section {
            margin-bottom: 24px;
        }

        .form-section:last-child {
            margin-bottom: 0;
        }

        .section-heading {
            display: flex;
            align-items: center;
            gap: 9px;

            margin-bottom: 13px;
        }

        .section-heading-icon {
            width: 32px;
            height: 32px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 9px;

            background: var(--primary-soft);
            color: var(--primary);

            font-size: 12px;
        }

        .section-heading h3 {
            margin: 0;

            color: var(--dark);

            font-size: 13px;
            font-weight: 800;
        }

        .section-heading p {
            margin: 2px 0 0;

            color: var(--muted);

            font-size: 10px;
        }

        .form-grid {
            display: grid;

            grid-template-columns:
                repeat(2, minmax(0, 1fr));

            gap: 15px;
        }

        .form-group.full {
            grid-column: 1 / -1;
        }

        .form-label {
            display: flex;
            align-items: center;
            justify-content: space-between;

            margin-bottom: 7px;

            color: #344054;

            font-size: 11px;
            font-weight: 800;
        }

        .counter {
            color: #98a2b3;

            font-size: 9px;
            font-weight: 600;
        }

        .form-control {
            width: 100%;

            border:
                1px solid var(--border);

            border-radius: 11px;

            outline: none;

            background: #fff;

            color: var(--dark);

            transition: .2s ease;
        }

        input.form-control,
        select.form-control {
            height: 43px;

            padding: 0 12px;
        }

        textarea.form-control {
            min-height: 100px;

            padding: 11px 12px;

            resize: vertical;

            line-height: 1.55;
        }

        input[type="file"].form-control {
            height: auto;
            min-height: 43px;
            padding: 9px 10px;
            background: #fbfcfe;
        }

        textarea.schema {
            min-height: 220px;

            font-family:
                Consolas,
                Monaco,
                monospace;

            font-size: 11px;
        }

        .field-help {
            margin-top: 5px;

            color: #98a2b3;

            font-size: 9px;
            line-height: 1.5;
        }

        /* =====================================================
           SEO PREVIEW
        ====================================================== */

        .seo-preview {
            padding: 16px;

            border:
                1px solid var(--border);

            border-radius: 14px;

            background: #fafbfc;
        }

        .preview-url {
            color: #188038;

            font-size: 10px;

            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .preview-title {
            margin-top: 5px;

            color: #1a0dab;

            font-size: 17px;
            font-weight: 500;

            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .preview-description {
            max-width: 700px;

            margin-top: 4px;

            color: #4d5156;

            font-size: 11px;

            line-height: 1.5;

            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;

            overflow: hidden;
        }

        /* =====================================================
           MODAL FOOTER
        ====================================================== */

        .modal-footer {
            position: sticky;
            bottom: 0;
            z-index: 2;

            display: flex;
            justify-content: flex-end;
            gap: 9px;

            padding: 15px 22px;

            background:
                rgba(255,255,255,.94);

            backdrop-filter: blur(15px);

            border-top:
                1px solid var(--border);
        }

        .btn {
            height: 42px;

            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 7px;

            padding: 0 15px;

            border-radius: 10px;

            font-size: 11px;
            font-weight: 800;

            cursor: pointer;
        }

        .btn-secondary {
            border: 1px solid var(--border);

            background: #fff;
            color: #475467;
        }

        .btn-primary {
            border: 0;

            background:
                linear-gradient(
                    135deg,
                    #22c55e,
                    #15803d
                );

            color: #fff;
        }

        /* =====================================================
           RESPONSIVE
        ====================================================== */

        @media (max-width: 1100px) {

            .page-wrapper {
                margin-left: 0;
            }

            .stats {
                grid-template-columns:
                    repeat(2, minmax(0, 1fr));
            }
        }

        @media (max-width: 760px) {

            .main-content {
                padding: 17px;
            }

            .topbar {
                padding: 0 17px;
            }

            .topbar-subtitle {
                display: none;
            }

            .page-header {
                align-items: flex-start;
                flex-direction: column;
            }

            .page-header h1 {
                font-size: 25px;
            }

            .add-btn {
                width: 100%;
            }

            .filter-panel {
                align-items: stretch;
                flex-direction: column;
            }

            .filter-select,
            .filter-btn {
                width: 100%;
            }

            .form-grid {
                grid-template-columns: 1fr;
            }

            .form-group.full {
                grid-column: auto;
            }
        }

        @media (max-width: 500px) {

            .stats {
                grid-template-columns: 1fr;
            }

            .main-content {
                padding: 13px;
            }

            .modal-backdrop {
                padding: 8px;
            }

            .modal {
                border-radius: 17px;
            }

            .modal-body,
            .modal-header,
            .modal-footer {
                padding-left: 15px;
                padding-right: 15px;
            }

            .modal-footer {
                flex-direction: column-reverse;
            }

            .modal-footer .btn {
                width: 100%;
            }
        }

    </style>

</head>

<body>

<?php
/*
|--------------------------------------------------------------------------
| Existing Sidebar
|--------------------------------------------------------------------------
|
| Sidebar is intentionally included separately.
| Do NOT include admin/header.php here.
|
*/
require_once __DIR__ . '/sidebar.php';
?>

<div class="page-wrapper">

    <!-- ========================================================
         TOPBAR
    ========================================================= -->

    <header class="topbar">

        <div>

            <h1 class="topbar-title">
                SEO Manager
            </h1>

            <div class="topbar-subtitle">
                Search engine optimisation & social metadata
            </div>

        </div>

        <div class="topbar-actions">

            <a
                href="pages.php"
                class="top-icon"
                title="Pages"
            >
                <i class="fa-solid fa-file-lines"></i>
            </a>

            <button
                type="button"
                class="top-icon"
                title="Add SEO"
                onclick="openSeoModal()"
            >
                <i class="fa-solid fa-plus"></i>
            </button>

        </div>

    </header>

    <!-- ========================================================
         MAIN CONTENT
    ========================================================= -->

    <main class="main-content">

        <!-- PAGE HEADER -->

        <div class="page-header">

            <div>

                <div class="eyebrow">

                    <i class="fa-solid fa-magnifying-glass-chart"></i>

                    Search Optimisation

                </div>

                <h1>
                    SEO Meta Manager
                </h1>

                <p>
                    Manage title tags, descriptions, canonical URLs,
                    robots directives, Open Graph, Twitter metadata
                    and structured data for your website entities.
                </p>

            </div>

            <button
                type="button"
                class="add-btn"
                onclick="openSeoModal()"
            >

                <i class="fa-solid fa-plus"></i>

                Add SEO Record

            </button>

        </div>

        <!-- ALERT -->

        <?php if ($messageText !== ''): ?>

            <div
                class="alert <?= $messageType === 'success'
                    ? 'success'
                    : 'error' ?>"
                id="pageAlert"
            >

                <div class="alert-icon">

                    <?php if ($messageType === 'success'): ?>

                        <i class="fa-solid fa-check"></i>

                    <?php else: ?>

                        <i class="fa-solid fa-triangle-exclamation"></i>

                    <?php endif; ?>

                </div>

                <div>

                    <strong>
                        <?= $messageType === 'success'
                            ? 'Success'
                            : 'Action Failed' ?>
                    </strong>

                    <?= e($messageText) ?>

                </div>

                <button
                    type="button"
                    class="alert-close"
                    onclick="document.getElementById('pageAlert').remove()"
                >
                    <i class="fa-solid fa-xmark"></i>
                </button>

            </div>

        <?php endif; ?>

        <!-- ====================================================
             STATS
        ===================================================== -->

        <section class="stats">

            <div class="stat-card">

                <div class="stat-icon">

                    <i class="fa-solid fa-tags"></i>

                </div>

                <div class="stat-number">
                    <?= number_format($totalSeo) ?>
                </div>

                <div class="stat-label">
                    Total SEO Records
                </div>

            </div>


            <div class="stat-card">

                <div class="stat-icon blue">

                    <i class="fa-solid fa-heading"></i>

                </div>

                <div class="stat-number">
                    <?= number_format($optimizedTitles) ?>
                </div>

                <div class="stat-label">
                    Records With Meta Title
                </div>

            </div>


            <div class="stat-card">

                <div class="stat-icon purple">

                    <i class="fa-solid fa-align-left"></i>

                </div>

                <div class="stat-number">
                    <?= number_format($optimizedDescriptions) ?>
                </div>

                <div class="stat-label">
                    Records With Description
                </div>

            </div>


            <div class="stat-card">

                <div class="stat-icon orange">

                    <i class="fa-solid fa-code"></i>

                </div>

                <div class="stat-number">
                    <?= number_format($schemaRecords) ?>
                </div>

                <div class="stat-label">
                    Records With Schema JSON
                </div>

            </div>

        </section>

        <!-- ====================================================
             FILTERS
        ===================================================== -->

        <form
            method="get"
            action="seo.php"
            class="filter-panel"
        >

            <div class="search-box">

                <i class="fa-solid fa-magnifying-glass"></i>

                <input
                    type="text"
                    name="q"
                    value="<?= e($search) ?>"
                    placeholder="Search entity, ID, title, description or URL..."
                >

            </div>

            <select
                name="entity_type"
                class="filter-select"
            >

                <option value="">
                    All Entity Types
                </option>

                <?php foreach ($entityTypes as $type): ?>

                    <option
                        value="<?= e($type) ?>"
                        <?= $entityFilter === $type
                            ? 'selected'
                            : '' ?>
                    >
                        <?= e($type) ?>
                    </option>

                <?php endforeach; ?>

            </select>

            <button
                type="submit"
                class="filter-btn"
            >
                <i class="fa-solid fa-filter"></i>
                Filter
            </button>

            <?php if ($search !== '' || $entityFilter !== ''): ?>

                <a
                    href="seo.php"
                    class="filter-btn"
                >
                    <i class="fa-solid fa-xmark"></i>
                    Clear
                </a>

            <?php endif; ?>

        </form>

        <!-- ====================================================
             TABLE
        ===================================================== -->

        <section class="table-card">

            <div class="table-head">

                <h2 class="table-title">
                    SEO Records
                </h2>

                <span class="table-count">
                    <?= number_format(count($seoRows)) ?> records
                </span>

            </div>

            <?php if (!empty($seoRows)): ?>

                <div class="table-scroll">

                    <table>

                        <thead>

                            <tr>

                                <th>
                                    Entity
                                </th>

                                <th>
                                    Meta Information
                                </th>

                                <th>
                                    Robots
                                </th>

                                <th>
                                    Social
                                </th>

                                <th>
                                    Structured Data
                                </th>

                                <th>
                                    Actions
                                </th>

                            </tr>

                        </thead>

                        <tbody>

                        <?php foreach ($seoRows as $row): ?>

                            <tr>

                                <!-- ENTITY -->

                                <td>

                                    <div class="entity-cell">

                                        <div class="entity-icon">

                                            <i class="fa-solid fa-cube"></i>

                                        </div>

                                        <div>

                                            <div class="entity-name">

                                                <?= e(
                                                    $row['entity_type']
                                                ) ?>

                                            </div>

                                            <div class="entity-id">

                                                ID:
                                                <?= (int)$row['entity_id'] ?>

                                            </div>

                                        </div>

                                    </div>

                                </td>


                                <!-- META -->

                                <td>

                                    <?php if (!empty($row['meta_title'])): ?>

                                        <div class="meta-title">

                                            <?= e(
                                                $row['meta_title']
                                            ) ?>

                                        </div>

                                    <?php else: ?>

                                        <div class="meta-title">
                                            No meta title
                                        </div>

                                    <?php endif; ?>


                                    <?php if (!empty($row['meta_description'])): ?>

                                        <div class="meta-description">

                                            <?= e(
                                                $row['meta_description']
                                            ) ?>

                                        </div>

                                    <?php else: ?>

                                        <div class="meta-description">
                                            No meta description
                                        </div>

                                    <?php endif; ?>


                                    <?php if (!empty($row['canonical_url'])): ?>

                                        <div
                                            class="url-text"
                                            title="<?= e(
                                                $row['canonical_url']
                                            ) ?>"
                                            style="margin-top:6px;"
                                        >

                                            <i class="fa-solid fa-link"></i>

                                            <?= e(
                                                $row['canonical_url']
                                            ) ?>

                                        </div>

                                    <?php endif; ?>

                                </td>


                                <!-- ROBOTS -->

                                <td>

                                    <?php
                                    $robotsValue =
                                        trim(
                                            $row['robots']
                                        ) ?: 'index,follow';
                                    ?>

                                    <span class="tag green">

                                        <i class="fa-solid fa-robot"></i>

                                        <?= e(
                                            $robotsValue
                                        ) ?>

                                    </span>

                                </td>


                                <!-- SOCIAL -->

                                <td>

                                    <div
                                        style="
                                            display:flex;
                                            flex-direction:column;
                                            gap:6px;
                                            align-items:flex-start;
                                        "
                                    >

                                        <?php if (
                                            !empty($row['og_title']) ||
                                            !empty($row['og_image_id'])
                                        ): ?>

                                            <span class="tag blue">

                                                <i class="fa-brands fa-facebook"></i>

                                                Open Graph

                                            </span>

                                        <?php endif; ?>


                                        <?php if (
                                            !empty($row['twitter_title']) ||
                                            !empty($row['twitter_image_id'])
                                        ): ?>

                                            <span class="tag purple">

                                                <i class="fa-brands fa-x-twitter"></i>

                                                Twitter

                                            </span>

                                        <?php endif; ?>


                                        <?php if (
                                            empty($row['og_title']) &&
                                            empty($row['og_image_id']) &&
                                            empty($row['twitter_title']) &&
                                            empty($row['twitter_image_id'])
                                        ): ?>

                                            <span class="tag orange">

                                                <i class="fa-solid fa-minus"></i>

                                                Not configured

                                            </span>

                                        <?php endif; ?>

                                    </div>

                                </td>


                                <!-- SCHEMA -->

                                <td>

                                    <?php if (
                                        !empty($row['schema_json'])
                                    ): ?>

                                        <span class="tag green">

                                            <i class="fa-solid fa-code"></i>

                                            JSON-LD

                                        </span>

                                    <?php else: ?>

                                        <span class="tag orange">

                                            <i class="fa-solid fa-minus"></i>

                                            None

                                        </span>

                                    <?php endif; ?>

                                </td>


                                <!-- ACTIONS -->

                                <td>

                                    <div class="action-buttons">

                                        <a
                                            href="seo.php?edit=<?= (int)$row['id'] ?>"
                                            class="action-btn"
                                            title="Edit SEO"
                                        >

                                            <i class="fa-solid fa-pen"></i>

                                        </a>


                                        <button
                                            type="button"
                                            class="action-btn delete"
                                            title="Delete SEO"
                                            onclick="deleteSeo(
                                                <?= (int)$row['id'] ?>,
                                                <?= htmlspecialchars(
                                                    json_encode(
                                                        $row['entity_type']
                                                    ),
                                                    ENT_QUOTES,
                                                    'UTF-8'
                                                ) ?>,
                                                <?= (int)$row['entity_id'] ?>
                                            )"
                                        >

                                            <i class="fa-solid fa-trash"></i>

                                        </button>

                                    </div>

                                </td>

                            </tr>

                        <?php endforeach; ?>

                        </tbody>

                    </table>

                </div>

            <?php else: ?>

                <div class="empty-state">

                    <div class="empty-icon">

                        <i class="fa-solid fa-magnifying-glass-chart"></i>

                    </div>

                    <h3>
                        No SEO records found
                    </h3>

                    <p>
                        Start by adding SEO metadata for a website
                        entity, page, product, category or other
                        supported entity.
                    </p>

                </div>

            <?php endif; ?>

        </section>

    </main>

</div>


<!-- ============================================================
     SEO MODAL
============================================================= -->

<div
    class="modal-backdrop <?= $editId > 0 ? 'show' : '' ?>"
    id="seoModal"
>

    <div class="modal">

        <form
            method="post"
            action="seo.php"
            id="seoForm"
            enctype="multipart/form-data"
        >

            <?= csrf_field() ?>

            <input
                type="hidden"
                name="action"
                value="save"
            >

            <input
                type="hidden"
                name="id"
                id="seo_id"
                value="<?= (int)$editSeo['id'] ?>"
            >

            <!-- HEADER -->

            <div class="modal-header">

                <div>

                    <h2 class="modal-title">

                        <?= $editId > 0
                            ? 'Edit SEO Record'
                            : 'Add SEO Record' ?>

                    </h2>

                    <div class="modal-subtitle">
                        Configure search engine and social metadata
                    </div>

                </div>

                <button
                    type="button"
                    class="modal-close"
                    onclick="closeSeoModal()"
                >

                    <i class="fa-solid fa-xmark"></i>

                </button>

            </div>


            <!-- BODY -->

            <div class="modal-body">

                <!-- =================================================
                     ENTITY
                ================================================== -->

                <section class="form-section">

                    <div class="section-heading">

                        <div class="section-heading-icon">

                            <i class="fa-solid fa-cube"></i>

                        </div>

                        <div>

                            <h3>
                                Entity Mapping
                            </h3>

                            <p>
                                Connect SEO metadata to an existing website entity.
                            </p>

                        </div>

                    </div>


                    <div class="form-grid">

                        <div class="form-group">

                            <label class="form-label">

                                Entity Type

                            </label>

                            <input
                                type="text"
                                class="form-control"
                                name="entity_type"
                                id="entity_type"
                                maxlength="100"
                                required
                                value="<?= e(
                                    $editSeo['entity_type']
                                ) ?>"
                                placeholder="e.g. page, product, category"
                            >

                            <div class="field-help">
                                Use the entity type used by your frontend.
                            </div>

                        </div>


                        <div class="form-group">

                            <label class="form-label">

                                Entity ID

                            </label>

                            <input
                                type="number"
                                class="form-control"
                                name="entity_id"
                                id="entity_id"
                                min="1"
                                required
                                value="<?= e(
                                    $editSeo['entity_id']
                                ) ?>"
                                placeholder="e.g. 1"
                            >

                            <div class="field-help">
                                Enter the ID of the related record.
                            </div>

                        </div>

                    </div>

                </section>


                <!-- =================================================
                     BASIC SEO
                ================================================== -->

                <section class="form-section">

                    <div class="section-heading">

                        <div class="section-heading-icon">

                            <i class="fa-solid fa-magnifying-glass"></i>

                        </div>

                        <div>

                            <h3>
                                Basic SEO
                            </h3>

                            <p>
                                Search engine title, description and canonical URL.
                            </p>

                        </div>

                    </div>


                    <div class="form-grid">

                        <div class="form-group full">

                            <label class="form-label">

                                <span>
                                    Meta Title
                                </span>

                                <span
                                    class="counter"
                                    id="metaTitleCounter"
                                >
                                    0 / 255
                                </span>

                            </label>

                            <input
                                type="text"
                                class="form-control"
                                name="meta_title"
                                id="meta_title"
                                maxlength="255"
                                value="<?= e(
                                    $editSeo['meta_title']
                                ) ?>"
                                placeholder="Write a clear SEO title..."
                            >

                        </div>


                        <div class="form-group full">

                            <label class="form-label">

                                <span>
                                    Meta Description
                                </span>

                                <span
                                    class="counter"
                                    id="metaDescriptionCounter"
                                >
                                    0
                                </span>

                            </label>

                            <textarea
                                class="form-control"
                                name="meta_description"
                                id="meta_description"
                                rows="4"
                                placeholder="Write a concise search engine description..."
                            ><?= e(
                                $editSeo['meta_description']
                            ) ?></textarea>

                            <div class="field-help">
                                Keep it useful, natural and relevant to the entity.
                            </div>

                        </div>


                        <div class="form-group full">

                            <label class="form-label">

                                Meta Keywords

                            </label>

                            <textarea
                                class="form-control"
                                name="meta_keywords"
                                rows="2"
                                placeholder="keyword one, keyword two, keyword three"
                            ><?= e(
                                $editSeo['meta_keywords']
                            ) ?></textarea>

                        </div>


                        <div class="form-group">

                            <label class="form-label">

                                Canonical URL

                            </label>

                            <input
                                type="url"
                                class="form-control"
                                name="canonical_url"
                                id="canonical_url"
                                maxlength="1000"
                                value="<?= e(
                                    $editSeo['canonical_url']
                                ) ?>"
                                placeholder="https://example.com/page"
                            >

                        </div>


                        <div class="form-group">

                            <label class="form-label">

                                Robots

                            </label>

                            <select
                                class="form-control"
                                name="robots"
                            >

                                <?php
                                $robotsOptions = [
                                    'index,follow' =>
                                        'Index, Follow',

                                    'noindex,follow' =>
                                        'Noindex, Follow',

                                    'index,nofollow' =>
                                        'Index, Nofollow',

                                    'noindex,nofollow' =>
                                        'Noindex, Nofollow',

                                    'noarchive' =>
                                        'No Archive',

                                    'nosnippet' =>
                                        'No Snippet',

                                    'noimageindex' =>
                                        'No Image Index'
                                ];
                                ?>

                                <?php foreach (
                                    $robotsOptions
                                    as $robotValue => $robotLabel
                                ): ?>

                                    <option
                                        value="<?= e(
                                            $robotValue
                                        ) ?>"
                                        <?= $editSeo['robots'] === $robotValue
                                            ? 'selected'
                                            : '' ?>
                                    >
                                        <?= e($robotLabel) ?>
                                    </option>

                                <?php endforeach; ?>

                            </select>

                        </div>

                    </div>

                </section>


                <!-- =================================================
                     SEARCH PREVIEW
                ================================================== -->

                <section class="form-section">

                    <div class="section-heading">

                        <div class="section-heading-icon">

                            <i class="fa-brands fa-google"></i>

                        </div>

                        <div>

                            <h3>
                                Search Preview
                            </h3>

                            <p>
                                Approximate search result appearance.
                            </p>

                        </div>

                    </div>


                    <div class="seo-preview">

                        <div
                            class="preview-url"
                            id="previewUrl"
                        >
                            https://example.com/
                        </div>

                        <div
                            class="preview-title"
                            id="previewTitle"
                        >
                            Your SEO title will appear here
                        </div>

                        <div
                            class="preview-description"
                            id="previewDescription"
                        >
                            Your meta description will appear here.
                        </div>

                    </div>

                </section>


                <!-- =================================================
                     OPEN GRAPH
                ================================================== -->

                <section class="form-section">

                    <div class="section-heading">

                        <div class="section-heading-icon">

                            <i class="fa-brands fa-facebook"></i>

                        </div>

                        <div>

                            <h3>
                                Open Graph
                            </h3>

                            <p>
                                Social sharing metadata.
                            </p>

                        </div>

                    </div>


                    <div class="form-grid">

                        <div class="form-group">

                            <label class="form-label">
                                OG Title
                            </label>

                            <input
                                type="text"
                                class="form-control"
                                name="og_title"
                                maxlength="255"
                                value="<?= e(
                                    $editSeo['og_title']
                                ) ?>"
                                placeholder="Social sharing title"
                            >

                        </div>


                        <div class="form-group">

                            <label class="form-label">Open Graph Image</label>
                            <select class="form-control" name="og_image_id" id="og_image_id">
                                <option value="0">No image selected</option>
                                <?php foreach ($mediaImages as $mediaImage): ?>
                                    <option value="<?= (int)$mediaImage['id'] ?>"
                                        <?= (int)$editSeo['og_image_id'] === (int)$mediaImage['id'] ? 'selected' : '' ?>>
                                        #<?= (int)$mediaImage['id'] ?> — <?= e($mediaImage['original_name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <div class="field-help">Select an existing image from Media Library or upload a new one below.</div>
                            <input type="file" class="form-control" name="og_image_upload" id="og_image_upload" accept="image/jpeg,image/png,image/webp,image/gif" style="margin-top:8px;padding:9px;height:auto">
                            <div class="field-help">JPG, PNG, WEBP or GIF; maximum 8 MB. A new upload replaces the selected image.</div>

                        </div>


                        <div class="form-group full">

                            <label class="form-label">
                                OG Description
                            </label>

                            <textarea
                                class="form-control"
                                name="og_description"
                                rows="3"
                                placeholder="Description used when sharing this page..."
                            ><?= e(
                                $editSeo['og_description']
                            ) ?></textarea>

                        </div>

                    </div>

                </section>


                <!-- =================================================
                     TWITTER
                ================================================== -->

                <section class="form-section">

                    <div class="section-heading">

                        <div class="section-heading-icon">

                            <i class="fa-brands fa-x-twitter"></i>

                        </div>

                        <div>

                            <h3>
                                Twitter / X
                            </h3>

                            <p>
                                Social card metadata.
                            </p>

                        </div>

                    </div>


                    <div class="form-grid">

                        <div class="form-group">

                            <label class="form-label">
                                Twitter Title
                            </label>

                            <input
                                type="text"
                                class="form-control"
                                name="twitter_title"
                                maxlength="255"
                                value="<?= e(
                                    $editSeo['twitter_title']
                                ) ?>"
                                placeholder="Twitter card title"
                            >

                        </div>


                        <div class="form-group">

                            <label class="form-label">Twitter / X Image</label>
                            <select class="form-control" name="twitter_image_id" id="twitter_image_id">
                                <option value="0">No image selected</option>
                                <?php foreach ($mediaImages as $mediaImage): ?>
                                    <option value="<?= (int)$mediaImage['id'] ?>"
                                        <?= (int)$editSeo['twitter_image_id'] === (int)$mediaImage['id'] ? 'selected' : '' ?>>
                                        #<?= (int)$mediaImage['id'] ?> — <?= e($mediaImage['original_name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <div class="field-help">Choose an existing Media Library image or upload a new one.</div>
                            <input type="file" class="form-control" name="twitter_image_upload" id="twitter_image_upload" accept="image/jpeg,image/png,image/webp,image/gif" style="margin-top:8px;padding:9px;height:auto">
                            <div class="field-help">JPG, PNG, WEBP or GIF; maximum 8 MB. A new upload replaces the selected image.</div>

                        </div>


                        <div class="form-group full">

                            <label class="form-label">
                                Twitter Description
                            </label>

                            <textarea
                                class="form-control"
                                name="twitter_description"
                                rows="3"
                                placeholder="Twitter card description..."
                            ><?= e(
                                $editSeo['twitter_description']
                            ) ?></textarea>

                        </div>

                    </div>

                </section>


                <!-- =================================================
                     SCHEMA
                ================================================== -->

                <section class="form-section">

                    <div class="section-heading">

                        <div class="section-heading-icon">

                            <i class="fa-solid fa-code"></i>

                        </div>

                        <div>

                            <h3>
                                Structured Data
                            </h3>

                            <p>
                                JSON-LD structured data for search engines.
                            </p>

                        </div>

                    </div>


                    <div class="form-group">

                        <label class="form-label">

                            Schema JSON

                            <span
                                class="counter"
                                id="jsonStatus"
                            >
                                Optional
                            </span>

                        </label>

                        <textarea
                            class="form-control schema"
                            name="schema_json"
                            id="schema_json"
                            placeholder='{
  "@context": "https://schema.org",
  "@type": "Organization"
}'
                        ><?= e(
                            $editSeo['schema_json']
                        ) ?></textarea>

                        <div class="field-help">
                            Enter valid JSON-LD JSON. The server validates
                            the JSON before saving.
                        </div>

                    </div>

                </section>

            </div>


            <!-- FOOTER -->

            <div class="modal-footer">

                <button
                    type="button"
                    class="btn btn-secondary"
                    onclick="closeSeoModal()"
                >

                    Cancel

                </button>

                <button
                    type="submit"
                    class="btn btn-primary"
                    id="saveSeoBtn"
                >

                    <i class="fa-solid fa-floppy-disk"></i>

                    <?= $editId > 0
                        ? 'Update SEO'
                        : 'Save SEO' ?>

                </button>

            </div>

        </form>

    </div>

</div>


<!-- ============================================================
     DELETE FORM
============================================================= -->

<form
    method="post"
    action="seo.php"
    id="deleteSeoForm"
    style="display:none;"
>

    <?= csrf_field() ?>

    <input
        type="hidden"
        name="action"
        value="delete"
    >

    <input
        type="hidden"
        name="id"
        id="deleteSeoId"
        value=""
    >

</form>


<script>

/* ============================================================
   MODAL
============================================================ */

function openSeoModal() {

    const modal =
        document.getElementById('seoModal');

    if (!modal) {
        return;
    }

    /*
     * Only reset when opening a fresh add modal.
     * Existing edit modal should keep its server values.
     */
    const form =
        document.getElementById('seoForm');

    if (
        !form.querySelector('#seo_id').value ||
        form.querySelector('#seo_id').value === '0'
    ) {

        form.reset();

        document.getElementById('seo_id').value = '0';

        const robots =
            form.querySelector('[name="robots"]');

        if (robots) {
            robots.value = 'index,follow';
        }
    }

    modal.classList.add('show');

    document.body.style.overflow = 'hidden';

    updateCounters();
    updatePreview();
    validateSchemaClient();
}


/* ============================================================
   CLOSE
============================================================ */

function closeSeoModal() {

    const modal =
        document.getElementById('seoModal');

    if (!modal) {
        return;
    }

    modal.classList.remove('show');

    document.body.style.overflow = '';

    /*
     * If currently editing from URL, return to clean page.
     */
    const currentUrl =
        new URL(window.location.href);

    if (currentUrl.searchParams.has('edit')) {

        currentUrl.searchParams.delete('edit');

        window.history.replaceState(
            {},
            document.title,
            currentUrl.toString()
        );
    }
}


/* ============================================================
   DELETE
============================================================ */

function deleteSeo(id, entityType, entityId) {

    const confirmed = confirm(
        'Delete SEO record for "' +
        entityType +
        ' #' +
        entityId +
        '"?\n\nThis action cannot be undone.'
    );

    if (!confirmed) {
        return;
    }

    document.getElementById(
        'deleteSeoId'
    ).value = id;

    document.getElementById(
        'deleteSeoForm'
    ).submit();
}


/* ============================================================
   COUNTERS
============================================================ */

function updateCounters() {

    const title =
        document.getElementById('meta_title');

    const description =
        document.getElementById('meta_description');

    const titleCounter =
        document.getElementById(
            'metaTitleCounter'
        );

    const descriptionCounter =
        document.getElementById(
            'metaDescriptionCounter'
        );

    if (title && titleCounter) {

        titleCounter.textContent =
            title.value.length +
            ' / 255';

    }

    if (description && descriptionCounter) {

        descriptionCounter.textContent =
            description.value.length +
            ' characters';

    }
}


/* ============================================================
   GOOGLE PREVIEW
============================================================ */

function updatePreview() {

    const title =
        document.getElementById('meta_title');

    const description =
        document.getElementById(
            'meta_description'
        );

    const canonical =
        document.getElementById(
            'canonical_url'
        );

    const previewTitle =
        document.getElementById(
            'previewTitle'
        );

    const previewDescription =
        document.getElementById(
            'previewDescription'
        );

    const previewUrl =
        document.getElementById(
            'previewUrl'
        );

    if (previewTitle) {

        previewTitle.textContent =
            title && title.value.trim()
                ? title.value.trim()
                : 'Your SEO title will appear here';

    }

    if (previewDescription) {

        previewDescription.textContent =
            description &&
            description.value.trim()
                ? description.value.trim()
                : 'Your meta description will appear here.';

    }

    if (previewUrl) {

        previewUrl.textContent =
            canonical &&
            canonical.value.trim()
                ? canonical.value.trim()
                : 'https://example.com/';

    }
}


/* ============================================================
   CLIENT JSON VALIDATION
============================================================ */

function validateSchemaClient() {

    const field =
        document.getElementById(
            'schema_json'
        );

    const status =
        document.getElementById(
            'jsonStatus'
        );

    if (!field || !status) {
        return;
    }

    const value =
        field.value.trim();

    if (!value) {

        status.textContent =
            'Optional';

        status.style.color =
            '#98a2b3';

        return;
    }

    try {

        JSON.parse(value);

        status.textContent =
            'Valid JSON';

        status.style.color =
            '#16a34a';

    } catch (error) {

        status.textContent =
            'Invalid JSON';

        status.style.color =
            '#dc2626';

    }
}


/* ============================================================
   INPUT EVENTS
============================================================ */

const metaTitle =
    document.getElementById(
        'meta_title'
    );

const metaDescription =
    document.getElementById(
        'meta_description'
    );

const canonicalUrl =
    document.getElementById(
        'canonical_url'
    );

const schemaJson =
    document.getElementById(
        'schema_json'
    );


if (metaTitle) {

    metaTitle.addEventListener(
        'input',
        function () {
            updateCounters();
            updatePreview();
        }
    );

}


if (metaDescription) {

    metaDescription.addEventListener(
        'input',
        function () {
            updateCounters();
            updatePreview();
        }
    );

}


if (canonicalUrl) {

    canonicalUrl.addEventListener(
        'input',
        updatePreview
    );

}


if (schemaJson) {

    schemaJson.addEventListener(
        'input',
        validateSchemaClient
    );

}


/* ============================================================
   FORM SUBMIT
============================================================ */

const seoForm =
    document.getElementById(
        'seoForm'
    );

if (seoForm) {

    seoForm.addEventListener(
        'submit',
        function (event) {

            const entityType =
                document.getElementById(
                    'entity_type'
                );

            const entityId =
                document.getElementById(
                    'entity_id'
                );

            const schema =
                document.getElementById(
                    'schema_json'
                );

            if (
                !entityType.value.trim() ||
                !entityId.value ||
                Number(entityId.value) <= 0
            ) {

                event.preventDefault();

                alert(
                    'Please enter a valid entity type and entity ID.'
                );

                return;
            }

            if (schema.value.trim()) {

                try {

                    JSON.parse(
                        schema.value
                    );

                } catch (error) {

                    event.preventDefault();

                    alert(
                        'Schema JSON is invalid. Please correct it before saving.'
                    );

                    schema.focus();

                    return;
                }
            }

            const button =
                document.getElementById(
                    'saveSeoBtn'
                );

            if (button) {

                button.disabled = true;

                button.innerHTML =
                    '<i class="fa-solid fa-spinner fa-spin"></i> Saving...';

            }

        }
    );
}


/* ============================================================
   ESC CLOSE
============================================================ */

document.addEventListener(
    'keydown',
    function (event) {

        if (event.key === 'Escape') {

            const modal =
                document.getElementById(
                    'seoModal'
                );

            if (
                modal &&
                modal.classList.contains('show')
            ) {
                closeSeoModal();
            }

        }

    }
);


/* ============================================================
   BACKDROP CLICK
============================================================ */

const seoModal =
    document.getElementById(
        'seoModal'
    );

if (seoModal) {

    seoModal.addEventListener(
        'click',
        function (event) {

            if (event.target === seoModal) {
                closeSeoModal();
            }

        }
    );

}


/* ============================================================
   AUTO HIDE ALERT
============================================================ */

setTimeout(function () {

    const alert =
        document.getElementById(
            'pageAlert'
        );

    if (!alert) {
        return;
    }

    alert.style.transition =
        'opacity .3s ease, transform .3s ease';

    alert.style.opacity = '0';

    alert.style.transform =
        'translateY(-5px)';

    setTimeout(function () {

        if (alert) {
            alert.remove();
        }

    }, 300);

}, 5000);


/* ============================================================
   INITIAL
============================================================ */

updateCounters();
updatePreview();
validateSchemaClient();

<?php if ($editId > 0): ?>

document.body.style.overflow = 'hidden';

<?php endif; ?>

</script>

</body>
</html>