<?php
/**
 * Pure Chemical - Product SEO Management
 * File: admin/product_seo.php
 *
 * Uses existing tables:
 *   - products
 *   - seo_meta
 *
 * No new table required.
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/* ---------------------------------------------------------
   DATABASE
--------------------------------------------------------- */
require_once __DIR__ . '/includes/db.php';


/* ---------------------------------------------------------
   OPTIONAL AUTH / FUNCTIONS / CSRF
--------------------------------------------------------- */
$authFile = __DIR__ . '/includes/auth.php';
$functionsFile = __DIR__ . '/includes/functions.php';
$csrfFile = __DIR__ . '/includes/csrf.php';

if (file_exists($authFile)) {
    require_once $authFile;
}

if (file_exists($functionsFile)) {
    require_once $functionsFile;
}

if (file_exists($csrfFile)) {
    require_once $csrfFile;
}


/* ---------------------------------------------------------
   FALLBACK HELPERS
--------------------------------------------------------- */

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('requireAdmin')) {
    function requireAdmin()
    {
        if (
            empty($_SESSION['admin_id']) &&
            empty($_SESSION['admin_logged_in'])
        ) {
            header('Location: login.php');
            exit;
        }
    }
}

if (!function_exists('csrf_token')) {
    function csrf_token()
    {
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        }

        return $_SESSION['csrf_token'];
    }
}

if (!function_exists('csrf_field')) {
    function csrf_field()
    {
        return '<input type="hidden" name="csrf_token" value="' .
            e(csrf_token()) .
            '">';
    }
}

if (!function_exists('csrf_verify')) {
    function csrf_verify()
    {
        $token = $_POST['csrf_token'] ?? '';

        return !empty($_SESSION['csrf_token']) &&
            hash_equals($_SESSION['csrf_token'], $token);
    }
}

if (!function_exists('redirectWithMessage')) {
    function redirectWithMessage($type, $message)
    {
        $url = basename($_SERVER['PHP_SELF']);

        header(
            'Location: ' .
            $url .
            '?' .
            http_build_query([
                'message_type' => $type,
                'message' => $message
            ])
        );

        exit;
    }
}


/* ---------------------------------------------------------
   AUTH
--------------------------------------------------------- */
requireAdmin();


/* ---------------------------------------------------------
   CONSTANTS
--------------------------------------------------------- */
$page_title = 'Product SEO';
$active_menu = 'product_seo';


/* ---------------------------------------------------------
   FLASH MESSAGE
--------------------------------------------------------- */
$message = $_GET['message'] ?? '';
$messageType = $_GET['message_type'] ?? '';


/* ---------------------------------------------------------
   DELETE SEO
--------------------------------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_seo'])) {

    if (!csrf_verify()) {
        redirectWithMessage('error', 'Invalid security token.');
    }

    $seoId = (int)($_POST['seo_id'] ?? 0);

    if ($seoId <= 0) {
        redirectWithMessage('error', 'Invalid SEO record.');
    }

    try {

        $stmt = $pdo->prepare("
            SELECT id
            FROM seo_meta
            WHERE id = ?
              AND entity_type = 'product'
            LIMIT 1
        ");

        $stmt->execute([$seoId]);

        if (!$stmt->fetch()) {
            redirectWithMessage('error', 'SEO record not found.');
        }

        $delete = $pdo->prepare("
            DELETE FROM seo_meta
            WHERE id = ?
              AND entity_type = 'product'
        ");

        $delete->execute([$seoId]);

        redirectWithMessage(
            'success',
            'Product SEO deleted successfully.'
        );

    } catch (Throwable $e) {

        error_log(
            'Product SEO Delete Error: ' .
            $e->getMessage()
        );

        redirectWithMessage(
            'error',
            'Unable to delete SEO record.'
        );
    }
}


/* ---------------------------------------------------------
   SAVE / UPDATE SEO
--------------------------------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_seo'])) {

    if (!csrf_verify()) {
        redirectWithMessage('error', 'Invalid security token.');
    }

    $seoId = (int)($_POST['seo_id'] ?? 0);
    $productId = (int)($_POST['product_id'] ?? 0);

    $metaTitle = trim($_POST['meta_title'] ?? '');
    $metaDescription = trim($_POST['meta_description'] ?? '');
    $metaKeywords = trim($_POST['meta_keywords'] ?? '');

    $canonicalUrl = trim($_POST['canonical_url'] ?? '');
    $robots = trim($_POST['robots'] ?? 'index,follow');

    $ogTitle = trim($_POST['og_title'] ?? '');
    $ogDescription = trim($_POST['og_description'] ?? '');
    $ogImageId = (int)($_POST['og_image_id'] ?? 0);

    $twitterTitle = trim($_POST['twitter_title'] ?? '');
    $twitterDescription = trim($_POST['twitter_description'] ?? '');
    $twitterImageId = (int)($_POST['twitter_image_id'] ?? 0);

    $schemaJson = trim($_POST['schema_json'] ?? '');


    /* -----------------------------------------------------
       VALIDATION
    ----------------------------------------------------- */

    if ($productId <= 0) {
        redirectWithMessage(
            'error',
            'Please select a product.'
        );
    }

    $productStmt = $pdo->prepare("
        SELECT id, name, slug
        FROM products
        WHERE id = ?
        LIMIT 1
    ");

    $productStmt->execute([$productId]);

    $product = $productStmt->fetch();

    if (!$product) {
        redirectWithMessage(
            'error',
            'Selected product does not exist.'
        );
    }


    /* -----------------------------------------------------
       ROBOTS VALIDATION
    ----------------------------------------------------- */

    $allowedRobots = [
        'index,follow',
        'noindex,follow',
        'index,nofollow',
        'noindex,nofollow'
    ];

    if (!in_array($robots, $allowedRobots, true)) {
        $robots = 'index,follow';
    }


    /* -----------------------------------------------------
       SCHEMA JSON VALIDATION
    ----------------------------------------------------- */

    if ($schemaJson !== '') {

        $decodedSchema = json_decode($schemaJson, true);

        if (
            json_last_error() !== JSON_ERROR_NONE ||
            !is_array($decodedSchema)
        ) {
            redirectWithMessage(
                'error',
                'Schema JSON is invalid. Please enter valid JSON-LD.'
            );
        }

        /*
         * Re-format valid JSON for clean storage.
         */
        $schemaJson = json_encode(
            $decodedSchema,
            JSON_UNESCAPED_SLASHES |
            JSON_UNESCAPED_UNICODE |
            JSON_PRETTY_PRINT
        );
    }


    /* -----------------------------------------------------
       IMAGE IDs
    ----------------------------------------------------- */

    $ogImageId = $ogImageId > 0 ? $ogImageId : null;
    $twitterImageId = $twitterImageId > 0 ? $twitterImageId : null;


    /* -----------------------------------------------------
       CHECK EXISTING SEO RECORD
    ----------------------------------------------------- */

    try {

        $existingStmt = $pdo->prepare("
            SELECT id
            FROM seo_meta
            WHERE entity_type = 'product'
              AND entity_id = ?
            LIMIT 1
        ");

        $existingStmt->execute([$productId]);

        $existing = $existingStmt->fetch();


        /* -------------------------------------------------
           UPDATE
        ------------------------------------------------- */

        if ($seoId > 0) {

            $verifyStmt = $pdo->prepare("
                SELECT id
                FROM seo_meta
                WHERE id = ?
                  AND entity_type = 'product'
                  AND entity_id = ?
                LIMIT 1
            ");

            $verifyStmt->execute([
                $seoId,
                $productId
            ]);

            $verify = $verifyStmt->fetch();

            if (!$verify) {

                redirectWithMessage(
                    'error',
                    'Invalid SEO record for selected product.'
                );
            }

            $update = $pdo->prepare("
                UPDATE seo_meta
                SET
                    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 = ?
                WHERE id = ?
                  AND entity_type = 'product'
                  AND entity_id = ?
            ");

            $update->execute([
                $metaTitle !== '' ? $metaTitle : null,
                $metaDescription !== '' ? $metaDescription : null,
                $metaKeywords !== '' ? $metaKeywords : null,
                $canonicalUrl !== '' ? $canonicalUrl : null,
                $robots,
                $ogTitle !== '' ? $ogTitle : null,
                $ogDescription !== '' ? $ogDescription : null,
                $ogImageId,
                $twitterTitle !== '' ? $twitterTitle : null,
                $twitterDescription !== '' ? $twitterDescription : null,
                $twitterImageId,
                $schemaJson !== '' ? $schemaJson : null,
                $seoId,
                $productId
            ]);

            redirectWithMessage(
                'success',
                'Product SEO updated successfully.'
            );
        }


        /* -------------------------------------------------
           EXISTING RECORD FOUND
           -> UPDATE INSTEAD OF DUPLICATE
        ------------------------------------------------- */

        if ($existing) {

            $update = $pdo->prepare("
                UPDATE seo_meta
                SET
                    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 = ?
                WHERE id = ?
                  AND entity_type = 'product'
                  AND entity_id = ?
            ");

            $update->execute([
                $metaTitle !== '' ? $metaTitle : null,
                $metaDescription !== '' ? $metaDescription : null,
                $metaKeywords !== '' ? $metaKeywords : null,
                $canonicalUrl !== '' ? $canonicalUrl : null,
                $robots,
                $ogTitle !== '' ? $ogTitle : null,
                $ogDescription !== '' ? $ogDescription : null,
                $ogImageId,
                $twitterTitle !== '' ? $twitterTitle : null,
                $twitterDescription !== '' ? $twitterDescription : null,
                $twitterImageId,
                $schemaJson !== '' ? $schemaJson : null,
                $existing['id'],
                $productId
            ]);

            redirectWithMessage(
                'success',
                'Product SEO updated successfully.'
            );
        }


        /* -------------------------------------------------
           INSERT NEW SEO
        ------------------------------------------------- */

        $insert = $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 (
                'product',
                ?,
                ?,
                ?,
                ?,
                ?,
                ?,
                ?,
                ?,
                ?,
                ?,
                ?,
                ?,
                ?
            )
        ");

        $insert->execute([
            $productId,
            $metaTitle !== '' ? $metaTitle : null,
            $metaDescription !== '' ? $metaDescription : null,
            $metaKeywords !== '' ? $metaKeywords : null,
            $canonicalUrl !== '' ? $canonicalUrl : null,
            $robots,
            $ogTitle !== '' ? $ogTitle : null,
            $ogDescription !== '' ? $ogDescription : null,
            $ogImageId,
            $twitterTitle !== '' ? $twitterTitle : null,
            $twitterDescription !== '' ? $twitterDescription : null,
            $twitterImageId,
            $schemaJson !== '' ? $schemaJson : null
        ]);

        redirectWithMessage(
            'success',
            'Product SEO created successfully.'
        );

    } catch (Throwable $e) {

        error_log(
            'Product SEO Save Error: ' .
            $e->getMessage()
        );

        redirectWithMessage(
            'error',
            'Unable to save product SEO.'
        );
    }
}


/* ---------------------------------------------------------
   EDIT SEO
--------------------------------------------------------- */

$editId = (int)($_GET['edit'] ?? 0);

$editSeo = null;

if ($editId > 0) {

    $stmt = $pdo->prepare("
        SELECT
            s.*,
            p.name AS product_name,
            p.slug AS product_slug
        FROM seo_meta s
        INNER JOIN products p
            ON p.id = s.entity_id
        WHERE s.id = ?
          AND s.entity_type = 'product'
        LIMIT 1
    ");

    $stmt->execute([$editId]);

    $editSeo = $stmt->fetch();

    if (!$editSeo) {
        $message = 'SEO record not found.';
        $messageType = 'error';
    }
}


/* ---------------------------------------------------------
   PRODUCT LIST
--------------------------------------------------------- */

$productStmt = $pdo->query("
    SELECT
        id,
        name,
        slug,
        product_code,
        status
    FROM products
    ORDER BY name ASC
");

$products = $productStmt->fetchAll();


/* ---------------------------------------------------------
   FILTERS
--------------------------------------------------------- */

$search = trim($_GET['search'] ?? '');
$productFilter = (int)($_GET['product_id'] ?? 0);

$page = max(1, (int)($_GET['page'] ?? 1));

$perPage = 12;

$where = [
    "s.entity_type = 'product'"
];

$params = [];


/* Search */

if ($search !== '') {

    $where[] = "
        (
            p.name LIKE ?
            OR p.slug LIKE ?
            OR p.product_code LIKE ?
            OR s.meta_title LIKE ?
        )
    ";

    $searchValue = '%' . $search . '%';

    $params[] = $searchValue;
    $params[] = $searchValue;
    $params[] = $searchValue;
    $params[] = $searchValue;
}


/* Product filter */

if ($productFilter > 0) {

    $where[] = "s.entity_id = ?";

    $params[] = $productFilter;
}


$whereSql = implode(' AND ', $where);


/* ---------------------------------------------------------
   TOTAL RECORDS
--------------------------------------------------------- */

$countStmt = $pdo->prepare("
    SELECT COUNT(*)
    FROM seo_meta s
    INNER JOIN products p
        ON p.id = s.entity_id
    WHERE {$whereSql}
");

$countStmt->execute($params);

$totalRecords = (int)$countStmt->fetchColumn();

$totalPages = max(
    1,
    (int)ceil($totalRecords / $perPage)
);

if ($page > $totalPages) {
    $page = $totalPages;
}

$offset = ($page - 1) * $perPage;


/* ---------------------------------------------------------
   SEO RECORDS
--------------------------------------------------------- */

$listStmt = $pdo->prepare("
    SELECT
        s.*,
        p.name AS product_name,
        p.slug AS product_slug,
        p.product_code,
        p.status AS product_status
    FROM seo_meta s
    INNER JOIN products p
        ON p.id = s.entity_id
    WHERE {$whereSql}
    ORDER BY s.updated_at DESC, s.id DESC
    LIMIT {$perPage}
    OFFSET {$offset}
");

$listStmt->execute($params);

$seoRecords = $listStmt->fetchAll();


/* ---------------------------------------------------------
   STATS
--------------------------------------------------------- */

$totalProducts = (int)$pdo
    ->query("
        SELECT COUNT(*)
        FROM products
    ")
    ->fetchColumn();


$totalSeo = (int)$pdo
    ->query("
        SELECT COUNT(*)
        FROM seo_meta
        WHERE entity_type = 'product'
    ")
    ->fetchColumn();


$withMetaTitle = (int)$pdo
    ->query("
        SELECT COUNT(*)
        FROM seo_meta
        WHERE entity_type = 'product'
          AND meta_title IS NOT NULL
          AND meta_title <> ''
    ")
    ->fetchColumn();


$withSchema = (int)$pdo
    ->query("
        SELECT COUNT(*)
        FROM seo_meta
        WHERE entity_type = 'product'
          AND schema_json IS NOT NULL
          AND schema_json <> ''
    ")
    ->fetchColumn();


/* ---------------------------------------------------------
   HELPERS
--------------------------------------------------------- */

function seoTitleLength($title)
{
    return mb_strlen((string)$title);
}

function seoTitleClass($length)
{
    if ($length === 0) {
        return 'neutral';
    }

    if ($length >= 30 && $length <= 60) {
        return 'good';
    }

    if ($length < 30) {
        return 'warning';
    }

    return 'danger';
}

function seoDescriptionLength($description)
{
    return mb_strlen((string)$description);
}

function seoDescriptionClass($length)
{
    if ($length === 0) {
        return 'neutral';
    }

    if ($length >= 120 && $length <= 160) {
        return 'good';
    }

    if ($length < 120) {
        return 'warning';
    }

    return 'danger';
}

function queryUrl($page)
{
    $query = $_GET;

    $query['page'] = $page;

    return '?' . http_build_query($query);
}


/* ---------------------------------------------------------
   HEADER
--------------------------------------------------------- */

$headerFile = __DIR__ . '/includes/header.php';

if (!file_exists($headerFile)) {
    $headerFile = __DIR__ . '/header.php';
}

if (file_exists($headerFile)) {
    require_once $headerFile;
}

?>

<style>
/* =========================================================
   PRODUCT SEO - PREMIUM ADMIN UI
========================================================= */

:root {
    --seo-primary: #2563eb;
    --seo-primary-dark: #1d4ed8;
    --seo-secondary: #7c3aed;
    --seo-success: #059669;
    --seo-warning: #d97706;
    --seo-danger: #dc2626;
    --seo-text: #0f172a;
    --seo-muted: #64748b;
    --seo-border: #e2e8f0;
    --seo-bg: #f8fafc;
    --seo-card: #ffffff;
    --seo-radius: 18px;
    --seo-shadow: 0 10px 35px rgba(15, 23, 42, .07);
}

.seo-page {
    padding: 24px;
    max-width: 1700px;
    margin: 0 auto;
}

.seo-page *,
.seo-page *::before,
.seo-page *::after {
    box-sizing: border-box;
}

.seo-page a {
    text-decoration: none;
}


/* ---------------------------------------------------------
   HEADER
--------------------------------------------------------- */

.seo-hero {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 20px;
    margin-bottom: 24px;
}

.seo-eyebrow {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    font-size: 12px;
    font-weight: 800;
    letter-spacing: .08em;
    text-transform: uppercase;
    color: var(--seo-primary);
    margin-bottom: 8px;
}

.seo-eyebrow i {
    font-size: 13px;
}

.seo-title {
    margin: 0;
    font-size: 30px;
    line-height: 1.15;
    font-weight: 800;
    color: var(--seo-text);
    letter-spacing: -.03em;
}

.seo-subtitle {
    margin: 9px 0 0;
    color: var(--seo-muted);
    font-size: 14px;
    line-height: 1.7;
    max-width: 750px;
}

.seo-hero-actions {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.seo-btn {
    border: 0;
    border-radius: 12px;
    min-height: 44px;
    padding: 0 16px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    font-size: 13px;
    font-weight: 750;
    cursor: pointer;
    transition: .2s ease;
}

.seo-btn:hover {
    transform: translateY(-1px);
}

.seo-btn-primary {
    color: #fff;
    background: linear-gradient(
        135deg,
        var(--seo-primary),
        var(--seo-secondary)
    );
    box-shadow: 0 8px 20px rgba(37, 99, 235, .20);
}

.seo-btn-light {
    background: #fff;
    color: var(--seo-text);
    border: 1px solid var(--seo-border);
}

.seo-btn-danger {
    background: #fef2f2;
    color: var(--seo-danger);
    border: 1px solid #fecaca;
}


/* ---------------------------------------------------------
   ALERTS
--------------------------------------------------------- */

.seo-alert {
    border-radius: 14px;
    padding: 13px 16px;
    display: flex;
    align-items: center;
    gap: 11px;
    margin-bottom: 20px;
    font-size: 13px;
    font-weight: 650;
}

.seo-alert-success {
    background: #ecfdf5;
    color: #047857;
    border: 1px solid #a7f3d0;
}

.seo-alert-error {
    background: #fef2f2;
    color: #b91c1c;
    border: 1px solid #fecaca;
}


/* ---------------------------------------------------------
   STATS
--------------------------------------------------------- */

.seo-stats {
    display: grid;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    gap: 16px;
    margin-bottom: 22px;
}

.seo-stat {
    background: var(--seo-card);
    border: 1px solid var(--seo-border);
    border-radius: var(--seo-radius);
    padding: 19px;
    box-shadow: var(--seo-shadow);
    position: relative;
    overflow: hidden;
}

.seo-stat::after {
    content: "";
    position: absolute;
    width: 80px;
    height: 80px;
    border-radius: 50%;
    right: -30px;
    top: -30px;
    background: rgba(37, 99, 235, .06);
}

.seo-stat-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 10px;
}

.seo-stat-icon {
    width: 42px;
    height: 42px;
    border-radius: 13px;
    display: grid;
    place-items: center;
    color: var(--seo-primary);
    background: #eff6ff;
    font-size: 17px;
}

.seo-stat-label {
    font-size: 12px;
    font-weight: 700;
    color: var(--seo-muted);
}

.seo-stat-value {
    margin-top: 10px;
    font-size: 25px;
    font-weight: 850;
    color: var(--seo-text);
}


/* ---------------------------------------------------------
   CARD
--------------------------------------------------------- */

.seo-card {
    background: var(--seo-card);
    border: 1px solid var(--seo-border);
    border-radius: var(--seo-radius);
    box-shadow: var(--seo-shadow);
    overflow: hidden;
}

.seo-card-head {
    padding: 19px 21px;
    border-bottom: 1px solid var(--seo-border);
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
}

.seo-card-title {
    margin: 0;
    font-size: 16px;
    font-weight: 800;
    color: var(--seo-text);
}

.seo-card-description {
    margin: 4px 0 0;
    color: var(--seo-muted);
    font-size: 12px;
}


/* ---------------------------------------------------------
   FORM
--------------------------------------------------------- */

.seo-form {
    padding: 22px;
}

.seo-form-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 18px;
}

.seo-form-full {
    grid-column: 1 / -1;
}

.seo-field {
    display: flex;
    flex-direction: column;
    gap: 7px;
}

.seo-label {
    color: var(--seo-text);
    font-size: 12px;
    font-weight: 800;
}

.seo-label span {
    color: var(--seo-muted);
    font-weight: 600;
}

.seo-input,
.seo-select,
.seo-textarea {
    width: 100%;
    border: 1px solid #dbe3ee;
    background: #fff;
    color: var(--seo-text);
    border-radius: 12px;
    outline: none;
    font-family: inherit;
    font-size: 13px;
    transition: .2s ease;
}

.seo-input,
.seo-select {
    height: 45px;
    padding: 0 13px;
}

.seo-textarea {
    min-height: 115px;
    padding: 12px 13px;
    resize: vertical;
    line-height: 1.6;
}

.seo-input:focus,
.seo-select:focus,
.seo-textarea:focus {
    border-color: rgba(37, 99, 235, .7);
    box-shadow: 0 0 0 4px rgba(37, 99, 235, .08);
}

.seo-help {
    color: var(--seo-muted);
    font-size: 11px;
    line-height: 1.5;
}

.seo-counter {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: -1px;
}

.seo-counter-value {
    font-size: 11px;
    font-weight: 800;
}

.seo-counter-value.good {
    color: var(--seo-success);
}

.seo-counter-value.warning {
    color: var(--seo-warning);
}

.seo-counter-value.danger {
    color: var(--seo-danger);
}

.seo-counter-value.neutral {
    color: var(--seo-muted);
}


/* ---------------------------------------------------------
   SECTION DIVIDER
--------------------------------------------------------- */

.seo-section {
    margin-top: 24px;
    padding-top: 21px;
    border-top: 1px solid var(--seo-border);
}

.seo-section-heading {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 17px;
}

.seo-section-icon {
    width: 34px;
    height: 34px;
    border-radius: 10px;
    display: grid;
    place-items: center;
    background: #eff6ff;
    color: var(--seo-primary);
}

.seo-section-heading h3 {
    margin: 0;
    font-size: 14px;
    font-weight: 800;
    color: var(--seo-text);
}

.seo-section-heading p {
    margin: 3px 0 0;
    color: var(--seo-muted);
    font-size: 11px;
}


/* ---------------------------------------------------------
   FORM ACTIONS
--------------------------------------------------------- */

.seo-form-actions {
    margin-top: 24px;
    padding-top: 19px;
    border-top: 1px solid var(--seo-border);
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    flex-wrap: wrap;
}


/* ---------------------------------------------------------
   FILTERS
--------------------------------------------------------- */

.seo-filter {
    padding: 16px;
    background: #f8fafc;
    border-bottom: 1px solid var(--seo-border);
}

.seo-filter-form {
    display: grid;
    grid-template-columns: minmax(250px, 1.5fr) minmax(220px, 1fr) auto auto;
    gap: 10px;
}

.seo-search {
    position: relative;
}

.seo-search i {
    position: absolute;
    left: 14px;
    top: 50%;
    transform: translateY(-50%);
    color: #94a3b8;
}

.seo-search .seo-input {
    padding-left: 39px;
}


/* ---------------------------------------------------------
   TABLE
--------------------------------------------------------- */

.seo-table-wrap {
    overflow-x: auto;
}

.seo-table {
    width: 100%;
    min-width: 1100px;
    border-collapse: collapse;
}

.seo-table th {
    padding: 13px 16px;
    background: #f8fafc;
    color: #64748b;
    text-transform: uppercase;
    letter-spacing: .05em;
    font-size: 10px;
    font-weight: 850;
    text-align: left;
    white-space: nowrap;
    border-bottom: 1px solid var(--seo-border);
}

.seo-table td {
    padding: 15px 16px;
    border-bottom: 1px solid #eef2f7;
    vertical-align: middle;
}

.seo-table tbody tr {
    transition: .18s ease;
}

.seo-table tbody tr:hover {
    background: #fafcff;
}

.seo-product {
    display: flex;
    flex-direction: column;
    gap: 3px;
}

.seo-product-name {
    color: var(--seo-text);
    font-weight: 800;
    font-size: 13px;
}

.seo-product-slug {
    color: #94a3b8;
    font-size: 11px;
}

.seo-code {
    display: inline-flex;
    align-items: center;
    padding: 5px 8px;
    border-radius: 7px;
    background: #f1f5f9;
    color: #475569;
    font-size: 10px;
    font-weight: 750;
}

.seo-meta-preview {
    max-width: 320px;
}

.seo-meta-title {
    color: #1d4ed8;
    font-weight: 750;
    font-size: 12px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.seo-meta-description {
    margin-top: 4px;
    color: #64748b;
    font-size: 11px;
    line-height: 1.45;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.seo-status {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 9px;
    border-radius: 999px;
    font-size: 10px;
    font-weight: 800;
}

.seo-status::before {
    content: "";
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: currentColor;
}

.seo-status-index {
    color: #047857;
    background: #ecfdf5;
}

.seo-status-noindex {
    color: #b45309;
    background: #fffbeb;
}

.seo-actions {
    display: flex;
    gap: 7px;
}

.seo-icon-btn {
    width: 35px;
    height: 35px;
    border-radius: 10px;
    border: 1px solid var(--seo-border);
    background: #fff;
    display: grid;
    place-items: center;
    color: #475569;
    cursor: pointer;
    transition: .2s ease;
}

.seo-icon-btn:hover {
    border-color: #bfdbfe;
    color: var(--seo-primary);
    background: #eff6ff;
}

.seo-icon-btn.delete:hover {
    border-color: #fecaca;
    color: var(--seo-danger);
    background: #fef2f2;
}


/* ---------------------------------------------------------
   EMPTY
--------------------------------------------------------- */

.seo-empty {
    padding: 65px 25px;
    text-align: center;
}

.seo-empty-icon {
    width: 58px;
    height: 58px;
    border-radius: 17px;
    display: grid;
    place-items: center;
    margin: 0 auto 15px;
    background: #eff6ff;
    color: var(--seo-primary);
    font-size: 22px;
}

.seo-empty h3 {
    margin: 0;
    font-size: 17px;
    color: var(--seo-text);
}

.seo-empty p {
    margin: 7px auto 0;
    max-width: 450px;
    color: var(--seo-muted);
    font-size: 13px;
    line-height: 1.6;
}


/* ---------------------------------------------------------
   PAGINATION
--------------------------------------------------------- */

.seo-pagination {
    padding: 15px 18px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 15px;
    border-top: 1px solid var(--seo-border);
}

.seo-pagination-info {
    color: var(--seo-muted);
    font-size: 12px;
}

.seo-pagination-links {
    display: flex;
    align-items: center;
    gap: 6px;
}

.seo-page-link {
    min-width: 34px;
    height: 34px;
    padding: 0 9px;
    border-radius: 9px;
    border: 1px solid var(--seo-border);
    background: #fff;
    display: grid;
    place-items: center;
    color: #475569;
    font-size: 11px;
    font-weight: 750;
}

.seo-page-link:hover,
.seo-page-link.active {
    background: var(--seo-primary);
    border-color: var(--seo-primary);
    color: #fff;
}


/* ---------------------------------------------------------
   BADGES
--------------------------------------------------------- */

.seo-mini-badges {
    display: flex;
    gap: 5px;
    flex-wrap: wrap;
}

.seo-mini-badge {
    padding: 5px 7px;
    border-radius: 7px;
    background: #f1f5f9;
    color: #64748b;
    font-size: 9px;
    font-weight: 800;
}

.seo-mini-badge.active {
    background: #ecfdf5;
    color: #047857;
}


/* ---------------------------------------------------------
   JSON PREVIEW
--------------------------------------------------------- */

.seo-schema-box {
    border-radius: 12px;
    background: #0f172a;
    color: #dbeafe;
    padding: 14px;
    font-family: Consolas, Monaco, monospace;
    font-size: 11px;
    line-height: 1.6;
    max-height: 180px;
    overflow: auto;
}


/* ---------------------------------------------------------
   RESPONSIVE
--------------------------------------------------------- */

@media (max-width: 1200px) {

    .seo-stats {
        grid-template-columns: repeat(2, minmax(0, 1fr));
    }

    .seo-filter-form {
        grid-template-columns: 1fr 1fr;
    }

}

@media (max-width: 850px) {

    .seo-page {
        padding: 16px;
    }

    .seo-hero {
        flex-direction: column;
    }

    .seo-form-grid {
        grid-template-columns: 1fr;
    }

    .seo-form-full {
        grid-column: auto;
    }

    .seo-filter-form {
        grid-template-columns: 1fr;
    }

}

@media (max-width: 600px) {

    .seo-stats {
        grid-template-columns: 1fr;
    }

    .seo-title {
        font-size: 24px;
    }

    .seo-form {
        padding: 16px;
    }

    .seo-card-head {
        padding: 16px;
    }

    .seo-pagination {
        flex-direction: column;
        align-items: flex-start;
    }

}
</style>


<div class="seo-page">

    <!-- =====================================================
         HERO
    ====================================================== -->

    <div class="seo-hero">

        <div>

            <div class="seo-eyebrow">
                <i class="fa-solid fa-magnifying-glass-chart"></i>
                Search Engine Optimization
            </div>

            <h1 class="seo-title">
                Product SEO
            </h1>

            <p class="seo-subtitle">
                Manage meta tags, canonical URLs, robots directives,
                Open Graph, Twitter cards and structured data for
                your products.
            </p>

        </div>

        <div class="seo-hero-actions">

            <a
                href="product_seo.php"
                class="seo-btn seo-btn-light"
            >
                <i class="fa-solid fa-rotate"></i>
                Refresh
            </a>

            <a
                href="#seo-form"
                class="seo-btn seo-btn-primary"
            >
                <i class="fa-solid fa-plus"></i>
                Add Product SEO
            </a>

        </div>

    </div>


    <!-- =====================================================
         ALERT
    ====================================================== -->

    <?php if ($message !== ''): ?>

        <div class="seo-alert <?php echo $messageType === 'success'
            ? 'seo-alert-success'
            : 'seo-alert-error'; ?>">

            <i class="fa-solid <?php echo $messageType === 'success'
                ? 'fa-circle-check'
                : 'fa-circle-exclamation'; ?>"></i>

            <?php echo e($message); ?>

        </div>

    <?php endif; ?>


    <!-- =====================================================
         STATS
    ====================================================== -->

    <div class="seo-stats">

        <div class="seo-stat">

            <div class="seo-stat-top">

                <div class="seo-stat-label">
                    Total Products
                </div>

                <div class="seo-stat-icon">
                    <i class="fa-solid fa-box"></i>
                </div>

            </div>

            <div class="seo-stat-value">
                <?php echo number_format($totalProducts); ?>
            </div>

        </div>


        <div class="seo-stat">

            <div class="seo-stat-top">

                <div class="seo-stat-label">
                    SEO Configured
                </div>

                <div class="seo-stat-icon">
                    <i class="fa-solid fa-magnifying-glass"></i>
                </div>

            </div>

            <div class="seo-stat-value">
                <?php echo number_format($totalSeo); ?>
            </div>

        </div>


        <div class="seo-stat">

            <div class="seo-stat-top">

                <div class="seo-stat-label">
                    Meta Titles
                </div>

                <div class="seo-stat-icon">
                    <i class="fa-solid fa-heading"></i>
                </div>

            </div>

            <div class="seo-stat-value">
                <?php echo number_format($withMetaTitle); ?>
            </div>

        </div>


        <div class="seo-stat">

            <div class="seo-stat-top">

                <div class="seo-stat-label">
                    Schema Added
                </div>

                <div class="seo-stat-icon">
                    <i class="fa-solid fa-code"></i>
                </div>

            </div>

            <div class="seo-stat-value">
                <?php echo number_format($withSchema); ?>
            </div>

        </div>

    </div>


    <!-- =====================================================
         SEO FORM
    ====================================================== -->

    <div
        class="seo-card"
        id="seo-form"
    >

        <div class="seo-card-head">

            <div>

                <h2 class="seo-card-title">

                    <?php echo $editSeo
                        ? 'Edit Product SEO'
                        : 'Configure Product SEO'; ?>

                </h2>

                <p class="seo-card-description">
                    <?php echo $editSeo
                        ? 'Update SEO settings for this product.'
                        : 'Select a product and configure its search engine metadata.'; ?>
                </p>

            </div>

            <?php if ($editSeo): ?>

                <a
                    href="product_seo.php"
                    class="seo-btn seo-btn-light"
                >
                    <i class="fa-solid fa-xmark"></i>
                    Cancel Edit
                </a>

            <?php endif; ?>

        </div>


        <form
            method="post"
            class="seo-form"
            novalidate
        >

            <?php echo csrf_field(); ?>

            <input
                type="hidden"
                name="seo_id"
                value="<?php echo $editSeo
                    ? (int)$editSeo['id']
                    : 0; ?>"
            >


            <!-- PRODUCT -->

            <div class="seo-form-grid">

                <div class="seo-field seo-form-full">

                    <label class="seo-label">
                        Product
                        <span>* Select product for SEO</span>
                    </label>

                    <select
                        name="product_id"
                        id="product_id"
                        class="seo-select"
                        required
                    >

                        <option value="">
                            Select Product
                        </option>

                        <?php foreach ($products as $product): ?>

                            <?php
                            $selectedProduct = $editSeo
                                ? (int)$editSeo['entity_id']
                                : 0;
                            ?>

                            <option
                                value="<?php echo (int)$product['id']; ?>"
                                <?php echo $selectedProduct === (int)$product['id']
                                    ? 'selected'
                                    : ''; ?>
                            >

                                <?php echo e($product['name']); ?>

                                <?php if (!empty($product['product_code'])): ?>
                                    — <?php echo e($product['product_code']); ?>
                                <?php endif; ?>

                                <?php if (!empty($product['slug'])): ?>
                                    (<?php echo e($product['slug']); ?>)
                                <?php endif; ?>

                            </option>

                        <?php endforeach; ?>

                    </select>

                    <div class="seo-help">
                        SEO record is stored using
                        <strong>entity_type = product</strong>
                        and the selected product ID.
                    </div>

                </div>

            </div>


            <!-- BASIC SEO -->

            <div class="seo-section">

                <div class="seo-section-heading">

                    <div class="seo-section-icon">
                        <i class="fa-solid fa-globe"></i>
                    </div>

                    <div>
                        <h3>
                            Basic Search Engine SEO
                        </h3>

                        <p>
                            Main metadata used by search engines.
                        </p>
                    </div>

                </div>


                <div class="seo-form-grid">

                    <!-- META TITLE -->

                    <div class="seo-field seo-form-full">

                        <label class="seo-label">
                            Meta Title
                        </label>

                        <input
                            type="text"
                            name="meta_title"
                            id="meta_title"
                            class="seo-input"
                            maxlength="255"
                            value="<?php echo e(
                                $editSeo['meta_title'] ?? ''
                            ); ?>"
                            placeholder="Example: High Purity Sodium Chloride | Pure Chemical"
                        >

                        <div class="seo-counter">

                            <span class="seo-help">
                                Recommended length: 30–60 characters.
                            </span>

                            <span
                                id="metaTitleCounter"
                                class="seo-counter-value neutral"
                            >
                                0 / 60
                            </span>

                        </div>

                    </div>


                    <!-- META DESCRIPTION -->

                    <div class="seo-field seo-form-full">

                        <label class="seo-label">
                            Meta Description
                        </label>

                        <textarea
                            name="meta_description"
                            id="meta_description"
                            class="seo-textarea"
                            maxlength="1000"
                            placeholder="Write a clear and compelling description for search engine results..."
                        ><?php echo e(
                            $editSeo['meta_description'] ?? ''
                        ); ?></textarea>

                        <div class="seo-counter">

                            <span class="seo-help">
                                Recommended length: 120–160 characters.
                            </span>

                            <span
                                id="metaDescriptionCounter"
                                class="seo-counter-value neutral"
                            >
                                0 / 160
                            </span>

                        </div>

                    </div>


                    <!-- KEYWORDS -->

                    <div class="seo-field seo-form-full">

                        <label class="seo-label">
                            Meta Keywords
                            <span>Optional</span>
                        </label>

                        <textarea
                            name="meta_keywords"
                            class="seo-textarea"
                            style="min-height:90px"
                            placeholder="chemical supplier, high purity chemical, laboratory chemical..."
                        ><?php echo e(
                            $editSeo['meta_keywords'] ?? ''
                        ); ?></textarea>

                        <div class="seo-help">
                            Separate keywords using commas.
                        </div>

                    </div>


                    <!-- CANONICAL -->

                    <div class="seo-field">

                        <label class="seo-label">
                            Canonical URL
                        </label>

                        <input
                            type="url"
                            name="canonical_url"
                            class="seo-input"
                            maxlength="1000"
                            value="<?php echo e(
                                $editSeo['canonical_url'] ?? ''
                            ); ?>"
                            placeholder="https://example.com/products/product-slug"
                        >

                        <div class="seo-help">
                            Use the preferred URL of this product.
                        </div>

                    </div>


                    <!-- ROBOTS -->

                    <div class="seo-field">

                        <label class="seo-label">
                            Robots
                        </label>

                        <select
                            name="robots"
                            class="seo-select"
                        >

                            <?php
                            $currentRobots =
                                $editSeo['robots']
                                ?? 'index,follow';
                            ?>

                            <option
                                value="index,follow"
                                <?php echo $currentRobots === 'index,follow'
                                    ? 'selected'
                                    : ''; ?>
                            >
                                index, follow
                            </option>

                            <option
                                value="noindex,follow"
                                <?php echo $currentRobots === 'noindex,follow'
                                    ? 'selected'
                                    : ''; ?>
                            >
                                noindex, follow
                            </option>

                            <option
                                value="index,nofollow"
                                <?php echo $currentRobots === 'index,nofollow'
                                    ? 'selected'
                                    : ''; ?>
                            >
                                index, nofollow
                            </option>

                            <option
                                value="noindex,nofollow"
                                <?php echo $currentRobots === 'noindex,nofollow'
                                    ? 'selected'
                                    : ''; ?>
                            >
                                noindex, nofollow
                            </option>

                        </select>

                        <div class="seo-help">
                            Recommended for published products:
                            <strong>index, follow</strong>.
                        </div>

                    </div>

                </div>

            </div>


            <!-- OPEN GRAPH -->

            <div class="seo-section">

                <div class="seo-section-heading">

                    <div class="seo-section-icon">
                        <i class="fa-brands fa-facebook"></i>
                    </div>

                    <div>

                        <h3>
                            Open Graph
                        </h3>

                        <p>
                            Social sharing metadata for Facebook,
                            LinkedIn and other platforms.
                        </p>

                    </div>

                </div>


                <div class="seo-form-grid">

                    <div class="seo-field">

                        <label class="seo-label">
                            OG Title
                        </label>

                        <input
                            type="text"
                            name="og_title"
                            maxlength="255"
                            class="seo-input"
                            value="<?php echo e(
                                $editSeo['og_title'] ?? ''
                            ); ?>"
                            placeholder="Social sharing title"
                        >

                    </div>


                    <div class="seo-field">

                        <label class="seo-label">
                            OG Image ID
                            <span>Media ID</span>
                        </label>

                        <input
                            type="number"
                            name="og_image_id"
                            min="0"
                            class="seo-input"
                            value="<?php echo !empty($editSeo['og_image_id'])
                                ? (int)$editSeo['og_image_id']
                                : ''; ?>"
                            placeholder="Example: 25"
                        >

                        <div class="seo-help">
                            Enter the existing Media Library ID.
                        </div>

                    </div>


                    <div class="seo-field seo-form-full">

                        <label class="seo-label">
                            OG Description
                        </label>

                        <textarea
                            name="og_description"
                            class="seo-textarea"
                            placeholder="Description shown when this product is shared..."
                        ><?php echo e(
                            $editSeo['og_description'] ?? ''
                        ); ?></textarea>

                    </div>

                </div>

            </div>


            <!-- TWITTER -->

            <div class="seo-section">

                <div class="seo-section-heading">

                    <div class="seo-section-icon">
                        <i class="fa-brands fa-x-twitter"></i>
                    </div>

                    <div>

                        <h3>
                            Twitter / X Card
                        </h3>

                        <p>
                            Social preview metadata for Twitter / X.
                        </p>

                    </div>

                </div>


                <div class="seo-form-grid">

                    <div class="seo-field">

                        <label class="seo-label">
                            Twitter Title
                        </label>

                        <input
                            type="text"
                            name="twitter_title"
                            maxlength="255"
                            class="seo-input"
                            value="<?php echo e(
                                $editSeo['twitter_title'] ?? ''
                            ); ?>"
                            placeholder="Twitter card title"
                        >

                    </div>


                    <div class="seo-field">

                        <label class="seo-label">
                            Twitter Image ID
                            <span>Media ID</span>
                        </label>

                        <input
                            type="number"
                            name="twitter_image_id"
                            min="0"
                            class="seo-input"
                            value="<?php echo !empty($editSeo['twitter_image_id'])
                                ? (int)$editSeo['twitter_image_id']
                                : ''; ?>"
                            placeholder="Example: 25"
                        >

                        <div class="seo-help">
                            Enter the existing Media Library ID.
                        </div>

                    </div>


                    <div class="seo-field seo-form-full">

                        <label class="seo-label">
                            Twitter Description
                        </label>

                        <textarea
                            name="twitter_description"
                            class="seo-textarea"
                            placeholder="Twitter / X card description..."
                        ><?php echo e(
                            $editSeo['twitter_description'] ?? ''
                        ); ?></textarea>

                    </div>

                </div>

            </div>


            <!-- SCHEMA -->

            <div class="seo-section">

                <div class="seo-section-heading">

                    <div class="seo-section-icon">
                        <i class="fa-solid fa-code"></i>
                    </div>

                    <div>

                        <h3>
                            Structured Data / JSON-LD
                        </h3>

                        <p>
                            Add valid JSON-LD schema for search engines.
                        </p>

                    </div>

                </div>


                <div class="seo-field">

                    <label class="seo-label">
                        Schema JSON
                        <span>Optional</span>
                    </label>

                    <textarea
                        name="schema_json"
                        id="schema_json"
                        class="seo-textarea"
                        style="
                            min-height:260px;
                            font-family:Consolas,Monaco,monospace;
                            font-size:12px;
                        "
                        placeholder='{
  "@context": "https://schema.org",
  "@type": "Product",
  "name": "Product Name"
}'
                    ><?php echo e(
                        $editSeo['schema_json'] ?? ''
                    ); ?></textarea>

                    <div
                        id="schemaStatus"
                        class="seo-help"
                    >
                        JSON-LD will be validated before saving.
                    </div>

                </div>

            </div>


            <!-- ACTION -->

            <div class="seo-form-actions">

                <?php if ($editSeo): ?>

                    <a
                        href="product_seo.php"
                        class="seo-btn seo-btn-light"
                    >
                        Cancel
                    </a>

                <?php endif; ?>

                <button
                    type="submit"
                    name="save_seo"
                    value="1"
                    class="seo-btn seo-btn-primary"
                >
                    <i class="fa-solid fa-floppy-disk"></i>

                    <?php echo $editSeo
                        ? 'Update Product SEO'
                        : 'Save Product SEO'; ?>

                </button>

            </div>

        </form>

    </div>


    <!-- =====================================================
         SEO RECORDS
    ====================================================== -->

    <div
        class="seo-card"
        style="margin-top:22px"
    >

        <div class="seo-card-head">

            <div>

                <h2 class="seo-card-title">
                    Product SEO Records
                </h2>

                <p class="seo-card-description">
                    Existing SEO configurations for your products.
                </p>

            </div>

            <div class="seo-mini-badges">

                <span class="seo-mini-badge">
                    <?php echo number_format($totalRecords); ?>
                    Records
                </span>

            </div>

        </div>


        <!-- FILTER -->

        <div class="seo-filter">

            <form
                method="get"
                class="seo-filter-form"
            >

                <div class="seo-search">

                    <i class="fa-solid fa-magnifying-glass"></i>

                    <input
                        type="search"
                        name="search"
                        class="seo-input"
                        value="<?php echo e($search); ?>"
                        placeholder="Search product, slug, code or meta title..."
                    >

                </div>


                <select
                    name="product_id"
                    class="seo-select"
                >

                    <option value="">
                        All Products
                    </option>

                    <?php foreach ($products as $product): ?>

                        <option
                            value="<?php echo (int)$product['id']; ?>"
                            <?php echo $productFilter === (int)$product['id']
                                ? 'selected'
                                : ''; ?>
                        >

                            <?php echo e($product['name']); ?>

                        </option>

                    <?php endforeach; ?>

                </select>


                <button
                    type="submit"
                    class="seo-btn seo-btn-primary"
                >
                    <i class="fa-solid fa-filter"></i>
                    Filter
                </button>


                <a
                    href="product_seo.php"
                    class="seo-btn seo-btn-light"
                >
                    Reset
                </a>

            </form>

        </div>


        <?php if (empty($seoRecords)): ?>

            <div class="seo-empty">

                <div class="seo-empty-icon">
                    <i class="fa-solid fa-magnifying-glass"></i>
                </div>

                <h3>
                    No Product SEO Found
                </h3>

                <p>
                    No SEO records match your current filter.
                    Select a product above and configure its SEO.
                </p>

            </div>

        <?php else: ?>

            <div class="seo-table-wrap">

                <table class="seo-table">

                    <thead>

                        <tr>

                            <th>
                                Product
                            </th>

                            <th>
                                Meta Title
                            </th>

                            <th>
                                SEO Length
                            </th>

                            <th>
                                Robots
                            </th>

                            <th>
                                Social
                            </th>

                            <th>
                                Schema
                            </th>

                            <th>
                                Updated
                            </th>

                            <th>
                                Actions
                            </th>

                        </tr>

                    </thead>


                    <tbody>

                        <?php foreach ($seoRecords as $record): ?>

                            <?php
                            $titleLength =
                                seoTitleLength(
                                    $record['meta_title'] ?? ''
                                );

                            $descriptionLength =
                                seoDescriptionLength(
                                    $record['meta_description'] ?? ''
                                );

                            $titleClass =
                                seoTitleClass($titleLength);

                            $descriptionClass =
                                seoDescriptionClass(
                                    $descriptionLength
                                );

                            $hasOg =
                                !empty($record['og_title']) ||
                                !empty($record['og_description']) ||
                                !empty($record['og_image_id']);

                            $hasTwitter =
                                !empty($record['twitter_title']) ||
                                !empty($record['twitter_description']) ||
                                !empty($record['twitter_image_id']);

                            $hasSchema =
                                !empty($record['schema_json']);

                            $robotsValue =
                                $record['robots'] ?? 'index,follow';

                            $robotsClass =
                                strpos(
                                    $robotsValue,
                                    'noindex'
                                ) !== false
                                    ? 'seo-status-noindex'
                                    : 'seo-status-index';
                            ?>

                            <tr>

                                <!-- PRODUCT -->

                                <td>

                                    <div class="seo-product">

                                        <div class="seo-product-name">
                                            <?php echo e(
                                                $record['product_name']
                                            ); ?>
                                        </div>

                                        <?php if (!empty($record['product_slug'])): ?>

                                            <div class="seo-product-slug">
                                                /<?php echo e(
                                                    $record['product_slug']
                                                ); ?>
                                            </div>

                                        <?php endif; ?>

                                        <?php if (!empty($record['product_code'])): ?>

                                            <div>
                                                <span class="seo-code">
                                                    <?php echo e(
                                                        $record['product_code']
                                                    ); ?>
                                                </span>
                                            </div>

                                        <?php endif; ?>

                                    </div>

                                </td>


                                <!-- META -->

                                <td>

                                    <div class="seo-meta-preview">

                                        <div class="seo-meta-title">

                                            <?php echo e(
                                                $record['meta_title']
                                                    ?: 'No meta title'
                                            ); ?>

                                        </div>

                                        <div class="seo-meta-description">

                                            <?php echo e(
                                                $record['meta_description']
                                                    ?: 'No meta description'
                                            ); ?>

                                        </div>

                                    </div>

                                </td>


                                <!-- LENGTH -->

                                <td>

                                    <div
                                        class="seo-mini-badges"
                                        style="max-width:130px"
                                    >

                                        <span
                                            class="seo-mini-badge <?php echo $titleClass; ?>"
                                        >

                                            Title:
                                            <?php echo $titleLength; ?>

                                        </span>

                                        <span
                                            class="seo-mini-badge <?php echo $descriptionClass; ?>"
                                        >

                                            Desc:
                                            <?php echo $descriptionLength; ?>

                                        </span>

                                    </div>

                                </td>


                                <!-- ROBOTS -->

                                <td>

                                    <span
                                        class="seo-status <?php echo $robotsClass; ?>"
                                    >
                                        <?php echo e($robotsValue); ?>
                                    </span>

                                </td>


                                <!-- SOCIAL -->

                                <td>

                                    <div class="seo-mini-badges">

                                        <?php if ($hasOg): ?>

                                            <span class="seo-mini-badge active">
                                                OG
                                            </span>

                                        <?php else: ?>

                                            <span class="seo-mini-badge">
                                                OG
                                            </span>

                                        <?php endif; ?>


                                        <?php if ($hasTwitter): ?>

                                            <span class="seo-mini-badge active">
                                                X
                                            </span>

                                        <?php else: ?>

                                            <span class="seo-mini-badge">
                                                X
                                            </span>

                                        <?php endif; ?>

                                    </div>

                                </td>


                                <!-- SCHEMA -->

                                <td>

                                    <?php if ($hasSchema): ?>

                                        <span class="seo-mini-badge active">
                                            <i class="fa-solid fa-check"></i>
                                            Added
                                        </span>

                                    <?php else: ?>

                                        <span class="seo-mini-badge">
                                            Not Added
                                        </span>

                                    <?php endif; ?>

                                </td>


                                <!-- UPDATED -->

                                <td>

                                    <div
                                        style="
                                            font-size:11px;
                                            color:#64748b;
                                            white-space:nowrap;
                                        "
                                    >

                                        <?php
                                        if (!empty($record['updated_at'])) {
                                            echo e(
                                                date(
                                                    'd M Y, h:i A',
                                                    strtotime(
                                                        $record['updated_at']
                                                    )
                                                )
                                            );
                                        } else {
                                            echo '-';
                                        }
                                        ?>

                                    </div>

                                </td>


                                <!-- ACTIONS -->

                                <td>

                                    <div class="seo-actions">

                                        <a
                                            href="?edit=<?php echo (int)$record['id']; ?>"
                                            class="seo-icon-btn"
                                            title="Edit SEO"
                                        >
                                            <i class="fa-solid fa-pen"></i>
                                        </a>


                                        <a
                                            href="product_seo.php?edit=<?php echo (int)$record['id']; ?>"
                                            class="seo-icon-btn"
                                            title="Open SEO"
                                        >
                                            <i class="fa-solid fa-arrow-up-right-from-square"></i>
                                        </a>


                                        <form
                                            method="post"
                                            style="display:inline"
                                            onsubmit="return confirm('Delete SEO settings for this product?');"
                                        >

                                            <?php echo csrf_field(); ?>

                                            <input
                                                type="hidden"
                                                name="seo_id"
                                                value="<?php echo (int)$record['id']; ?>"
                                            >

                                            <button
                                                type="submit"
                                                name="delete_seo"
                                                value="1"
                                                class="seo-icon-btn delete"
                                                title="Delete SEO"
                                            >
                                                <i class="fa-solid fa-trash"></i>
                                            </button>

                                        </form>

                                    </div>

                                </td>

                            </tr>

                        <?php endforeach; ?>

                    </tbody>

                </table>

            </div>


            <!-- PAGINATION -->

            <?php if ($totalPages > 1): ?>

                <div class="seo-pagination">

                    <div class="seo-pagination-info">

                        Showing

                        <strong>
                            <?php echo $offset + 1; ?>
                        </strong>

                        to

                        <strong>
                            <?php echo min(
                                $offset + $perPage,
                                $totalRecords
                            ); ?>
                        </strong>

                        of

                        <strong>
                            <?php echo $totalRecords; ?>
                        </strong>

                        SEO records

                    </div>


                    <div class="seo-pagination-links">

                        <?php if ($page > 1): ?>

                            <a
                                href="<?php echo e(
                                    queryUrl($page - 1)
                                ); ?>"
                                class="seo-page-link"
                            >
                                <i class="fa-solid fa-chevron-left"></i>
                            </a>

                        <?php endif; ?>


                        <?php

                        $startPage = max(1, $page - 2);
                        $endPage = min(
                            $totalPages,
                            $page + 2
                        );

                        for (
                            $p = $startPage;
                            $p <= $endPage;
                            $p++
                        ):
                        ?>

                            <a
                                href="<?php echo e(
                                    queryUrl($p)
                                ); ?>"
                                class="seo-page-link <?php echo $p === $page
                                    ? 'active'
                                    : ''; ?>"
                            >
                                <?php echo $p; ?>
                            </a>

                        <?php endfor; ?>


                        <?php if ($page < $totalPages): ?>

                            <a
                                href="<?php echo e(
                                    queryUrl($page + 1)
                                ); ?>"
                                class="seo-page-link"
                            >
                                <i class="fa-solid fa-chevron-right"></i>
                            </a>

                        <?php endif; ?>

                    </div>

                </div>

            <?php endif; ?>

        <?php endif; ?>

    </div>

</div>


<script>
document.addEventListener('DOMContentLoaded', function () {

    /* =====================================================
       META TITLE COUNTER
    ====================================================== */

    const metaTitle = document.getElementById('meta_title');
    const metaTitleCounter =
        document.getElementById('metaTitleCounter');

    function updateTitleCounter() {

        if (!metaTitle || !metaTitleCounter) {
            return;
        }

        const length = metaTitle.value.length;

        metaTitleCounter.textContent =
            length + ' / 60';

        metaTitleCounter.classList.remove(
            'good',
            'warning',
            'danger',
            'neutral'
        );

        if (length === 0) {

            metaTitleCounter.classList.add(
                'neutral'
            );

        } else if (length >= 30 && length <= 60) {

            metaTitleCounter.classList.add(
                'good'
            );

        } else if (length < 30) {

            metaTitleCounter.classList.add(
                'warning'
            );

        } else {

            metaTitleCounter.classList.add(
                'danger'
            );
        }
    }

    if (metaTitle) {

        metaTitle.addEventListener(
            'input',
            updateTitleCounter
        );

        updateTitleCounter();
    }


    /* =====================================================
       META DESCRIPTION COUNTER
    ====================================================== */

    const metaDescription =
        document.getElementById('meta_description');

    const metaDescriptionCounter =
        document.getElementById(
            'metaDescriptionCounter'
        );

    function updateDescriptionCounter() {

        if (
            !metaDescription ||
            !metaDescriptionCounter
        ) {
            return;
        }

        const length =
            metaDescription.value.length;

        metaDescriptionCounter.textContent =
            length + ' / 160';

        metaDescriptionCounter.classList.remove(
            'good',
            'warning',
            'danger',
            'neutral'
        );

        if (length === 0) {

            metaDescriptionCounter.classList.add(
                'neutral'
            );

        } else if (
            length >= 120 &&
            length <= 160
        ) {

            metaDescriptionCounter.classList.add(
                'good'
            );

        } else if (length < 120) {

            metaDescriptionCounter.classList.add(
                'warning'
            );

        } else {

            metaDescriptionCounter.classList.add(
                'danger'
            );
        }
    }

    if (metaDescription) {

        metaDescription.addEventListener(
            'input',
            updateDescriptionCounter
        );

        updateDescriptionCounter();
    }


    /* =====================================================
       SCHEMA JSON VALIDATION
    ====================================================== */

    const schemaJson =
        document.getElementById('schema_json');

    const schemaStatus =
        document.getElementById('schemaStatus');


    function validateSchema() {

        if (!schemaJson || !schemaStatus) {
            return true;
        }

        const value =
            schemaJson.value.trim();

        if (value === '') {

            schemaStatus.textContent =
                'JSON-LD is optional.';

            schemaStatus.style.color =
                '#64748b';

            return true;
        }

        try {

            JSON.parse(value);

            schemaStatus.textContent =
                '✓ Valid JSON detected. It will be formatted and stored.';

            schemaStatus.style.color =
                '#047857';

            return true;

        } catch (error) {

            schemaStatus.textContent =
                '✕ Invalid JSON. Please fix the JSON before saving.';

            schemaStatus.style.color =
                '#dc2626';

            return false;
        }
    }


    if (schemaJson) {

        schemaJson.addEventListener(
            'input',
            validateSchema
        );

        validateSchema();
    }


    /* =====================================================
       FORM VALIDATION
    ====================================================== */

    const form =
        document.querySelector('.seo-form');

    if (form) {

        form.addEventListener(
            'submit',
            function (event) {

                if (
                    schemaJson &&
                    schemaJson.value.trim() !== ''
                ) {

                    if (!validateSchema()) {

                        event.preventDefault();

                        schemaJson.focus();

                        return false;
                    }
                }


                const product =
                    document.getElementById(
                        'product_id'
                    );

                if (
                    product &&
                    !product.value
                ) {

                    event.preventDefault();

                    product.focus();

                    alert(
                        'Please select a product first.'
                    );

                    return false;
                }

            }
        );
    }


    /* =====================================================
       SMOOTH SCROLL
    ====================================================== */

    document
        .querySelectorAll('a[href="#seo-form"]')
        .forEach(function (link) {

            link.addEventListener(
                'click',
                function (event) {

                    const target =
                        document.getElementById(
                            'seo-form'
                        );

                    if (target) {

                        event.preventDefault();

                        target.scrollIntoView({
                            behavior: 'smooth',
                            block: 'start'
                        });
                    }
                }
            );

        });

});
</script>


<?php

/* ---------------------------------------------------------
   FOOTER
--------------------------------------------------------- */

$footerFile = __DIR__ . '/includes/footer.php';

if (!file_exists($footerFile)) {
    $footerFile = __DIR__ . '/footer.php';
}

if (file_exists($footerFile)) {
    require_once $footerFile;
}

?>