<?php
/**
 * Pure Chemical Admin
 * File: admin/blog_categories.php
 * Purpose: Blog Categories Management
 */

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

/* =========================================================
   CORE FILES
========================================================= */

require_once __DIR__ . '/includes/db.php';

if (file_exists(__DIR__ . '/includes/auth.php')) {
    require_once __DIR__ . '/includes/auth.php';
}

if (file_exists(__DIR__ . '/includes/functions.php')) {
    require_once __DIR__ . '/includes/functions.php';
}

if (file_exists(__DIR__ . '/includes/csrf.php')) {
    require_once __DIR__ . '/includes/csrf.php';
}

/* =========================================================
   AUTH
========================================================= */

if (function_exists('requireAdmin')) {
    requireAdmin();
}

/* =========================================================
   HELPERS
========================================================= */

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars(
            (string)$value,
            ENT_QUOTES,
            'UTF-8'
        );
    }
}

if (!function_exists('blog_category_slug')) {
    function blog_category_slug($text)
    {
        $text = trim(
            mb_strtolower(
                (string)$text,
                'UTF-8'
            )
        );

        $text = preg_replace(
            '/[^\pL\pN]+/u',
            '-',
            $text
        );

        $text = trim(
            $text,
            '-'
        );

        return $text !== ''
            ? $text
            : 'category-' . time();
    }
}

function verify_blog_category_csrf()
{
    if (function_exists('csrf_verify')) {
        return csrf_verify();
    }

    $token = $_POST['_csrf'] ?? '';

    if (
        empty($_SESSION['_csrf_token']) ||
        empty($token)
    ) {
        return false;
    }

    return hash_equals(
        $_SESSION['_csrf_token'],
        $token
    );
}

function blog_category_csrf_field()
{
    if (function_exists('csrf_field')) {
        return csrf_field();
    }

    if (empty($_SESSION['_csrf_token'])) {
        $_SESSION['_csrf_token'] =
            bin2hex(random_bytes(32));
    }

    return '<input type="hidden" name="_csrf" value="' .
        e($_SESSION['_csrf_token']) .
        '">';
}

function category_exists(PDO $pdo, $id)
{
    $stmt = $pdo->prepare("
        SELECT id
        FROM blog_categories
        WHERE id = ?
        LIMIT 1
    ");

    $stmt->execute([
        (int)$id
    ]);

    return (bool)$stmt->fetchColumn();
}

function category_has_children(PDO $pdo, $id)
{
    $stmt = $pdo->prepare("
        SELECT COUNT(*)
        FROM blog_categories
        WHERE parent_id = ?
    ");

    $stmt->execute([
        (int)$id
    ]);

    return (int)$stmt->fetchColumn() > 0;
}

function category_has_posts(PDO $pdo, $id)
{
    try {

        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM blog_posts
            WHERE category_id = ?
        ");

        $stmt->execute([
            (int)$id
        ]);

        return (int)$stmt->fetchColumn() > 0;

    } catch (Throwable $e) {
        return false;
    }
}

/* =========================================================
   ADMIN NAME
========================================================= */

$adminName =
    $_SESSION['ADMIN_NAME']
    ?? $_SESSION['admin_name']
    ?? $_SESSION['name']
    ?? 'Administrator';

/* =========================================================
   FLASH MESSAGE
========================================================= */

$successMessage =
    $_SESSION['success_message']
    ?? '';

$errorMessage =
    $_SESSION['error_message']
    ?? '';

unset(
    $_SESSION['success_message'],
    $_SESSION['error_message']
);

/* =========================================================
   FORM DEFAULTS
========================================================= */

$form = [
    'id'          => 0,
    'parent_id'   => '',
    'name'        => '',
    'slug'        => '',
    'description' => '',
    'image_id'    => '',
    'sort_order'  => 0,
    'status'      => 1
];

$formErrors = [];

/* =========================================================
   EDIT ID
========================================================= */

$editId = isset($_GET['edit'])
    ? (int)$_GET['edit']
    : 0;

/* =========================================================
   DELETE
========================================================= */

if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    &&
    ($_POST['action'] ?? '') === 'delete'
) {

    if (!verify_blog_category_csrf()) {

        $_SESSION['error_message'] =
            'Security verification failed. Please refresh the page and try again.';

        header(
            'Location: blog_categories.php'
        );

        exit;
    }

    $deleteId = (int)(
        $_POST['category_id']
        ?? 0
    );

    if ($deleteId <= 0) {

        $_SESSION['error_message'] =
            'Invalid category selected.';

    } else {

        try {

            if (!category_exists(
                $pdo,
                $deleteId
            )) {

                throw new RuntimeException(
                    'Category not found.'
                );
            }

            /*
             * Do not delete a category if it still
             * has child categories.
             */

            if (category_has_children(
                $pdo,
                $deleteId
            )) {

                throw new RuntimeException(
                    'This category has child categories. Please move or delete them first.'
                );
            }

            /*
             * Do not delete a category which is
             * currently used by blog posts.
             */

            if (category_has_posts(
                $pdo,
                $deleteId
            )) {

                throw new RuntimeException(
                    'This category is being used by one or more blog posts. Please move those posts to another category first.'
                );
            }

            $stmt = $pdo->prepare("
                DELETE FROM blog_categories
                WHERE id = ?
                LIMIT 1
            ");

            $stmt->execute([
                $deleteId
            ]);

            $_SESSION['success_message'] =
                'Blog category deleted successfully.';

        } catch (Throwable $e) {

            error_log(
                'Blog Category Delete Error: ' .
                $e->getMessage()
            );

            $_SESSION['error_message'] =
                $e->getMessage();
        }
    }

    header(
        'Location: blog_categories.php'
    );

    exit;
}

/* =========================================================
   SAVE / UPDATE
========================================================= */

if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    &&
    ($_POST['action'] ?? '') === 'save'
) {

    if (!verify_blog_category_csrf()) {

        $formErrors[] =
            'Security verification failed. Please refresh the page and try again.';

    } else {

        $form['id'] =
            (int)(
                $_POST['id']
                ?? 0
            );

        $form['parent_id'] =
            trim(
                $_POST['parent_id']
                ?? ''
            );

        $form['name'] =
            trim(
                $_POST['name']
                ?? ''
            );

        $form['slug'] =
            trim(
                $_POST['slug']
                ?? ''
            );

        $form['description'] =
            trim(
                $_POST['description']
                ?? ''
            );

        $form['image_id'] =
            trim(
                $_POST['image_id']
                ?? ''
            );

        $form['sort_order'] =
            trim(
                $_POST['sort_order']
                ?? '0'
            );

        $form['status'] =
            isset($_POST['status'])
                ? 1
                : 0;

        /* ---------------------------------------------
           NAME
        --------------------------------------------- */

        if ($form['name'] === '') {

            $formErrors[] =
                'Category name is required.';

        } elseif (
            mb_strlen(
                $form['name'],
                'UTF-8'
            ) > 255
        ) {

            $formErrors[] =
                'Category name cannot exceed 255 characters.';
        }

        /* ---------------------------------------------
           SLUG
        --------------------------------------------- */

        if ($form['slug'] === '') {

            $form['slug'] =
                blog_category_slug(
                    $form['name']
                );

        } else {

            $form['slug'] =
                blog_category_slug(
                    $form['slug']
                );
        }

        if (
            mb_strlen(
                $form['slug'],
                'UTF-8'
            ) > 255
        ) {

            $formErrors[] =
                'Slug cannot exceed 255 characters.';
        }

        /* ---------------------------------------------
           PARENT
        --------------------------------------------- */

        $parentId = null;

        if ($form['parent_id'] !== '') {

            if (
                !ctype_digit(
                    $form['parent_id']
                )
            ) {

                $formErrors[] =
                    'Invalid parent category selected.';

            } else {

                $parentId =
                    (int)$form['parent_id'];

                if (
                    $parentId <= 0
                    ||
                    !category_exists(
                        $pdo,
                        $parentId
                    )
                ) {

                    $formErrors[] =
                        'Selected parent category does not exist.';
                }

                /*
                 * Prevent category from becoming its own parent.
                 */

                if (
                    $form['id'] > 0
                    &&
                    $parentId === $form['id']
                ) {

                    $formErrors[] =
                        'A category cannot be its own parent.';
                }
            }
        }

        /* ---------------------------------------------
           IMAGE ID
        --------------------------------------------- */

        $imageId = null;

        if ($form['image_id'] !== '') {

            if (
                !ctype_digit(
                    $form['image_id']
                )
            ) {

                $formErrors[] =
                    'Image ID must be a valid numeric media ID.';

            } else {

                $imageId = (int)$form['image_id'];

                // blog_categories.image_id refers to an existing media.id.
                // Validate before INSERT/UPDATE so an invalid ID cannot trigger an FK error.
                try {
                    $mediaStmt = $pdo->prepare(
                        'SELECT id FROM media WHERE id = ? LIMIT 1'
                    );
                    $mediaStmt->execute([$imageId]);

                    if (!$mediaStmt->fetchColumn()) {
                        $formErrors[] = 'Selected image was not found in the media library. Please choose a valid Media ID or leave this field empty.';
                        $imageId = null;
                    }
                } catch (Throwable $mediaError) {
                    error_log('Blog Category Media Validation Error: ' . $mediaError->getMessage());
                    $formErrors[] = 'Unable to validate the selected image against the media table. Please leave the image field empty or check the media table.';
                }
            }
        }

        /* ---------------------------------------------
           SORT ORDER
        --------------------------------------------- */

        if (
            $form['sort_order'] === ''
        ) {

            $form['sort_order'] = 0;
        }

        if (
            !preg_match(
                '/^-?\d+$/',
                (string)$form['sort_order']
            )
        ) {

            $formErrors[] =
                'Sort order must be a valid integer.';

        } else {

            $form['sort_order'] =
                (int)$form['sort_order'];
        }

        /* ---------------------------------------------
           SLUG DUPLICATE
        --------------------------------------------- */

        if (empty($formErrors)) {

            try {

                if ($form['id'] > 0) {

                    $stmt = $pdo->prepare("
                        SELECT id
                        FROM blog_categories
                        WHERE slug = ?
                        AND id != ?
                        LIMIT 1
                    ");

                    $stmt->execute([
                        $form['slug'],
                        $form['id']
                    ]);

                } else {

                    $stmt = $pdo->prepare("
                        SELECT id
                        FROM blog_categories
                        WHERE slug = ?
                        LIMIT 1
                    ");

                    $stmt->execute([
                        $form['slug']
                    ]);
                }

                if ($stmt->fetch()) {

                    $formErrors[] =
                        'This slug already exists. Please use a different slug.';
                }

            } catch (Throwable $e) {

                $formErrors[] =
                    'Unable to validate category slug.';
            }
        }

        /* ---------------------------------------------
           SAVE
        --------------------------------------------- */

        if (empty($formErrors)) {

            try {

                $pdo->beginTransaction();

                if ($form['id'] > 0) {

                    /*
                     * UPDATE
                     */

                    $stmt = $pdo->prepare("
                        UPDATE blog_categories
                        SET
                            parent_id = :parent_id,
                            name = :name,
                            slug = :slug,
                            description = :description,
                            image_id = :image_id,
                            sort_order = :sort_order,
                            status = :status
                        WHERE id = :id
                    ");

                    $stmt->execute([
                        ':parent_id' =>
                            $parentId,

                        ':name' =>
                            $form['name'],

                        ':slug' =>
                            $form['slug'],

                        ':description' =>
                            $form['description'] !== ''
                                ? $form['description']
                                : null,

                        ':image_id' =>
                            $imageId,

                        ':sort_order' =>
                            $form['sort_order'],

                        ':status' =>
                            $form['status'],

                        ':id' =>
                            $form['id']
                    ]);

                    $message =
                        'Blog category updated successfully.';

                } else {

                    /*
                     * INSERT
                     */

                    $stmt = $pdo->prepare("
                        INSERT INTO blog_categories
                        (
                            parent_id,
                            name,
                            slug,
                            description,
                            image_id,
                            sort_order,
                            status
                        )
                        VALUES
                        (
                            :parent_id,
                            :name,
                            :slug,
                            :description,
                            :image_id,
                            :sort_order,
                            :status
                        )
                    ");

                    $stmt->execute([
                        ':parent_id' =>
                            $parentId,

                        ':name' =>
                            $form['name'],

                        ':slug' =>
                            $form['slug'],

                        ':description' =>
                            $form['description'] !== ''
                                ? $form['description']
                                : null,

                        ':image_id' =>
                            $imageId,

                        ':sort_order' =>
                            $form['sort_order'],

                        ':status' =>
                            $form['status']
                    ]);

                    $message =
                        'Blog category created successfully.';
                }

                $pdo->commit();

                $_SESSION['success_message'] =
                    $message;

                header(
                    'Location: blog_categories.php'
                );

                exit;

            } catch (Throwable $e) {

                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }

                error_log(
                    'Blog Category Save Error: ' .
                    $e->getMessage()
                );

                // Keep the user-facing message actionable while recording full details in the PHP error log.
                $dbMessage = trim((string)$e->getMessage());
                if (stripos($dbMessage, 'foreign key constraint fails') !== false) {
                    $formErrors[] = 'Category could not be saved because a related parent category or media record is invalid. Check Parent Category and Category Image ID.';
                } elseif (stripos($dbMessage, 'duplicate entry') !== false) {
                    $formErrors[] = 'This category slug already exists. Please enter a different slug.';
                } else {
                    $formErrors[] = 'Unable to save the category. Database says: ' . $dbMessage;
                }
            }
        }
    }
}

/* =========================================================
   LOAD EDIT CATEGORY
========================================================= */

if (
    $_SERVER['REQUEST_METHOD'] !== 'POST'
    &&
    $editId > 0
) {

    try {

        $stmt = $pdo->prepare("
            SELECT
                id,
                parent_id,
                name,
                slug,
                description,
                image_id,
                sort_order,
                status
            FROM blog_categories
            WHERE id = ?
            LIMIT 1
        ");

        $stmt->execute([
            $editId
        ]);

        $editCategory =
            $stmt->fetch();

        if ($editCategory) {

            $form = [
                'id' =>
                    (int)$editCategory['id'],

                'parent_id' =>
                    $editCategory['parent_id'] !== null
                        ? (string)$editCategory['parent_id']
                        : '',

                'name' =>
                    $editCategory['name'],

                'slug' =>
                    $editCategory['slug'],

                'description' =>
                    $editCategory['description'] ?? '',

                'image_id' =>
                    $editCategory['image_id'] !== null
                        ? (string)$editCategory['image_id']
                        : '',

                'sort_order' =>
                    $editCategory['sort_order'],

                'status' =>
                    (int)$editCategory['status']
            ];

        } else {

            $_SESSION['error_message'] =
                'Blog category not found.';

            header(
                'Location: blog_categories.php'
            );

            exit;
        }

    } catch (Throwable $e) {

        $formErrors[] =
            'Unable to load the selected category.';
    }
}

/* =========================================================
   LOAD ALL CATEGORIES
========================================================= */

$categories = [];

try {

    $stmt = $pdo->query("
        SELECT
            id,
            parent_id,
            name,
            slug,
            description,
            image_id,
            sort_order,
            status,
            created_at
        FROM blog_categories
        ORDER BY
            sort_order ASC,
            name ASC,
            id ASC
    ");

    $categories =
        $stmt->fetchAll();

} catch (Throwable $e) {

    $categories = [];

    $errorMessage =
        'Unable to load blog categories.';
}

/* =========================================================
   LOAD IMAGE OPTIONS FROM MEDIA LIBRARY
========================================================= */

$mediaItems = [];
$mediaLoadError = false;

try {
    $mediaStmt = $pdo->query("
        SELECT id, original_name, file_name, title, alt_text, mime_type, file_type
        FROM media
        WHERE (mime_type LIKE 'image/%' OR file_type = 'image')
        ORDER BY id DESC
    ");
    $mediaItems = $mediaStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $mediaLoadException) {
    $mediaLoadError = true;
    error_log('Blog Category Media Options Error: ' . $mediaLoadException->getMessage());
}

/* =========================================================
   PARENT CATEGORY OPTIONS
========================================================= */

$parentCategories = [];

foreach ($categories as $category) {

    /*
     * Do not show the current category as its
     * own parent.
     */

    if (
        $form['id'] > 0
        &&
        (int)$category['id'] ===
        (int)$form['id']
    ) {
        continue;
    }

    $parentCategories[] =
        $category;
}

/* =========================================================
   SEARCH
========================================================= */

$search =
    trim(
        $_GET['q'] ?? ''
    );

$filterStatus =
    $_GET['status'] ?? 'all';

$filteredCategories = [];

foreach ($categories as $category) {

    if ($search !== '') {

        $haystack =
            mb_strtolower(
                $category['name']
                . ' '
                . $category['slug']
                . ' '
                . ($category['description'] ?? ''),
                'UTF-8'
            );

        $needle =
            mb_strtolower(
                $search,
                'UTF-8'
            );

        if (
            mb_strpos(
                $haystack,
                $needle
            ) === false
        ) {
            continue;
        }
    }

    if (
        $filterStatus !== 'all'
        &&
        in_array(
            $filterStatus,
            ['active', 'inactive'],
            true
        )
    ) {

        $expectedStatus =
            $filterStatus === 'active'
                ? 1
                : 0;

        if (
            (int)$category['status']
            !==
            $expectedStatus
        ) {
            continue;
        }
    }

    $filteredCategories[] =
        $category;
}

/* =========================================================
   CATEGORY MAP
========================================================= */

$categoryMap = [];

foreach ($categories as $category) {
    $categoryMap[
        (int)$category['id']
    ] = $category;
}

/* =========================================================
   STATS
========================================================= */

$totalCategories =
    count($categories);

$activeCategories = 0;
$inactiveCategories = 0;
$parentCategoriesCount = 0;

foreach ($categories as $category) {

    if ((int)$category['status'] === 1) {
        $activeCategories++;
    } else {
        $inactiveCategories++;
    }

    if (
        empty($category['parent_id'])
    ) {
        $parentCategoriesCount++;
    }
}

?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>
        Blog Categories | Pure Chemical Admin
    </title>

    <meta
        name="theme-color"
        content="#071a14"
    >

    <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 {
            --green: #0d6b4d;
            --green-dark: #064c37;
            --green-soft: #eaf8f2;

            --bg: #f4f7f6;
            --card: #ffffff;

            --text: #17221e;
            --muted: #74817b;

            --border: #e3ebe6;

            --danger: #c83c4a;
            --danger-soft: #fff0f2;

            --warning: #a96e00;
            --warning-soft: #fff7e5;

            --blue: #2764c8;
            --blue-soft: #edf4ff;

            --shadow:
                0 16px 45px rgba(11, 46, 34, .07);

            --radius: 18px;
        }

        * {
            box-sizing: border-box;
        }

        html {
            scroll-behavior: smooth;
        }

        body {
            margin: 0;

            font-family: "Inter", sans-serif;

            color: var(--text);

            background: var(--bg);
        }

        a {
            color: inherit;
            text-decoration: none;
        }

        button,
        input,
        select,
        textarea {
            font: inherit;
        }

        /* =================================================
           PAGE
        ================================================= */

        .pc-page {
            margin-left: 280px;
            min-height: 100vh;
        }

        /* =================================================
           TOPBAR
        ================================================= */

        .pc-topbar {
            position: sticky;
            top: 0;
            z-index: 900;

            min-height: 76px;

            display: flex;
            align-items: center;
            justify-content: space-between;

            padding: 12px 30px;

            background: rgba(255, 255, 255, .93);

            backdrop-filter: blur(18px);
            -webkit-backdrop-filter: blur(18px);

            border-bottom: 1px solid var(--border);
        }

        .topbar-left {
            display: flex;
            align-items: center;
            gap: 14px;
        }

        .topbar-icon {
            width: 44px;
            height: 44px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 14px;

            color: #fff;

            background:
                linear-gradient(
                    135deg,
                    var(--green),
                    var(--green-dark)
                );

            box-shadow:
                0 9px 22px rgba(13, 107, 77, .22);
        }

        .topbar-title h1 {
            margin: 0;

            font-size: 18px;
            font-weight: 800;

            letter-spacing: -.35px;
        }

        .topbar-title span {
            display: block;

            margin-top: 3px;

            color: var(--muted);

            font-size: 11px;
        }

        .topbar-right {
            display: flex;
            align-items: center;
            gap: 11px;
        }

        .admin-chip {
            display: flex;
            align-items: center;
            gap: 9px;

            padding: 6px 12px 6px 7px;

            border: 1px solid var(--border);
            border-radius: 999px;

            background: #fff;
        }

        .admin-avatar {
            width: 34px;
            height: 34px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 50%;

            color: #fff;

            background:
                linear-gradient(
                    135deg,
                    #13875f,
                    #07543d
                );

            font-size: 12px;
            font-weight: 800;
        }

        .admin-name {
            font-size: 12px;
            font-weight: 700;
        }

        .top-action {
            display: inline-flex;
            align-items: center;
            gap: 8px;

            min-height: 41px;

            padding: 0 14px;

            border-radius: 11px;

            font-size: 12px;
            font-weight: 800;

            transition: .2s ease;
        }

        .top-action:hover {
            transform: translateY(-1px);
        }

        .top-action.secondary {
            color: #4d5b54;

            background: #fff;

            border: 1px solid var(--border);
        }

        .top-action.primary {
            color: #fff;

            background:
                linear-gradient(
                    135deg,
                    #0f7655,
                    #07553e
                );

            box-shadow:
                0 8px 20px rgba(13, 107, 77, .19);
        }

        /* =================================================
           CONTENT
        ================================================= */

        .pc-content {
            max-width: 1550px;

            margin: 0 auto;

            padding: 30px;
        }

        .page-heading {
            display: flex;
            align-items: flex-end;
            justify-content: space-between;

            gap: 20px;

            margin-bottom: 25px;
        }

        .eyebrow {
            display: inline-flex;
            align-items: center;
            gap: 7px;

            margin-bottom: 9px;

            color: var(--green);

            font-size: 10px;
            font-weight: 800;

            text-transform: uppercase;
            letter-spacing: .13em;
        }

        .page-heading h2 {
            margin: 0;

            font-size: 29px;
            line-height: 1.15;

            letter-spacing: -.8px;
        }

        .page-heading p {
            margin: 9px 0 0;

            color: var(--muted);

            font-size: 13px;
        }

        /* =================================================
           ALERTS
        ================================================= */

        .alert {
            display: flex;
            align-items: flex-start;
            gap: 11px;

            padding: 14px 16px;

            margin-bottom: 20px;

            border-radius: 13px;

            font-size: 12px;
            line-height: 1.55;
        }

        .alert.success {
            color: #166243;

            background: #eaf8f2;

            border: 1px solid #c7eadc;
        }

        .alert.error {
            color: #8e2b36;

            background: var(--danger-soft);

            border: 1px solid #f0c9cf;
        }

        /* =================================================
           STATS
        ================================================= */

        .stats-grid {
            display: grid;

            grid-template-columns:
                repeat(4, minmax(0, 1fr));

            gap: 15px;

            margin-bottom: 22px;
        }

        .stat-card {
            position: relative;

            overflow: hidden;

            padding: 18px;

            border: 1px solid var(--border);

            border-radius: 16px;

            background: var(--card);

            box-shadow: var(--shadow);
        }

        .stat-card::after {
            content: "";

            position: absolute;

            width: 100px;
            height: 100px;

            right: -35px;
            top: -45px;

            border-radius: 50%;

            background: var(--green-soft);

            opacity: .7;
        }

        .stat-top {
            position: relative;
            z-index: 2;

            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .stat-label {
            color: var(--muted);

            font-size: 11px;
            font-weight: 700;
        }

        .stat-icon {
            width: 35px;
            height: 35px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 10px;

            color: var(--green);

            background: var(--green-soft);
        }

        .stat-number {
            position: relative;
            z-index: 2;

            margin-top: 12px;

            font-size: 25px;
            font-weight: 800;

            letter-spacing: -.7px;
        }

        /* =================================================
           MAIN GRID
        ================================================= */

        .main-grid {
            display: grid;

            grid-template-columns:
                minmax(0, 1fr)
                365px;

            gap: 21px;

            align-items: start;
        }

        .card {
            background: var(--card);

            border: 1px solid var(--border);

            border-radius: var(--radius);

            box-shadow: var(--shadow);
        }

        .card-header {
            display: flex;
            align-items: center;
            justify-content: space-between;

            gap: 15px;

            padding: 20px 22px;

            border-bottom: 1px solid var(--border);
        }

        .card-heading {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .card-heading-icon {
            width: 37px;
            height: 37px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 11px;

            color: var(--green);

            background: var(--green-soft);
        }

        .card-heading h3 {
            margin: 0;

            font-size: 14px;
            font-weight: 800;
        }

        .card-heading p {
            margin: 3px 0 0;

            color: var(--muted);

            font-size: 10px;
        }

        .card-body {
            padding: 21px;
        }

        /* =================================================
           SEARCH
        ================================================= */

        .filter-bar {
            display: flex;
            align-items: center;

            gap: 9px;

            margin-bottom: 17px;
        }

        .search-wrap {
            position: relative;

            flex: 1;
        }

        .search-wrap i {
            position: absolute;

            left: 14px;
            top: 50%;

            transform: translateY(-50%);

            color: #8b9891;

            font-size: 12px;
        }

        .search-input {
            width: 100%;
            height: 43px;

            padding: 0 13px 0 38px;

            border: 1px solid var(--border);

            border-radius: 11px;

            outline: none;

            background: #fff;

            color: var(--text);

            font-size: 12px;
        }

        .search-input:focus {
            border-color: rgba(13, 107, 77, .5);

            box-shadow:
                0 0 0 4px rgba(13, 107, 77, .07);
        }

        .filter-select {
            width: 145px;
            height: 43px;

            padding: 0 11px;

            border: 1px solid var(--border);

            border-radius: 11px;

            outline: none;

            background: #fff;

            font-size: 11px;
            font-weight: 700;

            color: #46534d;
        }

        .filter-btn {
            height: 43px;

            display: inline-flex;
            align-items: center;
            justify-content: center;

            gap: 7px;

            padding: 0 14px;

            border: 1px solid var(--border);

            border-radius: 11px;

            color: #53615a;

            background: #fff;

            cursor: pointer;

            font-size: 11px;
            font-weight: 800;
        }

        /* =================================================
           TABLE
        ================================================= */

        .table-wrap {
            overflow-x: auto;

            border: 1px solid var(--border);

            border-radius: 14px;
        }

        table {
            width: 100%;

            border-collapse: collapse;

            min-width: 780px;
        }

        th {
            padding: 13px 14px;

            color: #76827c;

            background: #f8faf9;

            border-bottom: 1px solid var(--border);

            text-align: left;

            font-size: 9px;
            font-weight: 800;

            text-transform: uppercase;
            letter-spacing: .07em;

            white-space: nowrap;
        }

        td {
            padding: 14px;

            border-bottom: 1px solid #edf1ef;

            vertical-align: middle;

            font-size: 11px;
        }

        tbody tr:last-child td {
            border-bottom: 0;
        }

        tbody tr {
            transition: background .18s ease;
        }

        tbody tr:hover {
            background: #fbfdfc;
        }

        .category-name {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .category-icon {
            width: 36px;
            height: 36px;

            display: flex;
            align-items: center;
            justify-content: center;

            flex: 0 0 auto;

            border-radius: 10px;

            color: var(--green);

            background: var(--green-soft);
        }

        .category-info strong {
            display: block;

            color: #24312b;

            font-size: 12px;
            font-weight: 800;
        }

        .category-info span {
            display: block;

            max-width: 230px;

            margin-top: 3px;

            overflow: hidden;

            color: #8b9690;

            font-size: 10px;

            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .slug-text {
            color: #6d7973;

            font-family: monospace;

            font-size: 10px;
        }

        .parent-badge {
            display: inline-flex;
            align-items: center;
            gap: 5px;

            padding: 5px 8px;

            border-radius: 7px;

            color: #526159;

            background: #f4f7f5;

            font-size: 9px;
            font-weight: 700;
        }

        .root-badge {
            color: var(--green);
            background: var(--green-soft);
        }

        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;

            padding: 5px 9px;

            border-radius: 999px;

            font-size: 9px;
            font-weight: 800;
        }

        .status-badge.active {
            color: #18714f;
            background: #eaf8f2;
        }

        .status-badge.inactive {
            color: #8d3540;
            background: #fff0f2;
        }

        .status-dot {
            width: 6px;
            height: 6px;

            border-radius: 50%;

            background: currentColor;
        }

        .order-number {
            display: inline-flex;
            align-items: center;
            justify-content: center;

            min-width: 30px;
            height: 26px;

            padding: 0 7px;

            border-radius: 7px;

            color: #526159;

            background: #f5f7f6;

            font-size: 10px;
            font-weight: 800;
        }

        .action-group {
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .icon-btn {
            width: 33px;
            height: 33px;

            display: inline-flex;
            align-items: center;
            justify-content: center;

            border-radius: 9px;

            border: 1px solid var(--border);

            background: #fff;

            cursor: pointer;

            transition: .18s ease;
        }

        .icon-btn.edit {
            color: var(--blue);
        }

        .icon-btn.delete {
            color: var(--danger);
        }

        .icon-btn:hover {
            transform: translateY(-1px);
            background: #f8faf9;
        }

        /* =================================================
           EMPTY
        ================================================= */

        .empty-state {
            padding: 55px 25px;

            text-align: center;
        }

        .empty-icon {
            width: 58px;
            height: 58px;

            margin: 0 auto 13px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 17px;

            color: var(--green);

            background: var(--green-soft);

            font-size: 21px;
        }

        .empty-state h4 {
            margin: 0;

            font-size: 14px;
        }

        .empty-state p {
            margin: 7px auto 0;

            max-width: 400px;

            color: var(--muted);

            font-size: 11px;
            line-height: 1.6;
        }

        /* =================================================
           FORM
        ================================================= */

        .form-card {
            position: sticky;
            top: 96px;
        }

        .field {
            margin-bottom: 17px;
        }

        .field:last-child {
            margin-bottom: 0;
        }

        .field label {
            display: flex;
            align-items: center;
            gap: 5px;

            margin-bottom: 7px;

            color: #36443d;

            font-size: 11px;
            font-weight: 800;
        }

        .required {
            color: var(--danger);
        }

        .input,
        .select,
        .textarea {
            width: 100%;

            border: 1px solid #dce5e0;

            border-radius: 11px;

            outline: none;

            background: #fff;

            color: var(--text);

            transition: .2s ease;
        }

        .input,
        .select {
            height: 43px;

            padding: 0 12px;

            font-size: 11px;
        }

        .textarea {
            min-height: 105px;

            padding: 11px 12px;

            resize: vertical;

            line-height: 1.6;

            font-size: 11px;
        }

        .input:focus,
        .select:focus,
        .textarea:focus {
            border-color: rgba(13, 107, 77, .55);

            box-shadow:
                0 0 0 4px rgba(13, 107, 77, .07);
        }

        .field-help {
            margin-top: 5px;

            color: #8b9690;

            font-size: 9px;
            line-height: 1.5;
        }

        .slug-wrap {
            position: relative;
        }

        .slug-wrap .input {
            padding-right: 42px;
        }

        .slug-btn {
            position: absolute;

            top: 5px;
            right: 5px;

            width: 33px;
            height: 33px;

            border: 0;

            border-radius: 8px;

            color: var(--green);

            background: var(--green-soft);

            cursor: pointer;
        }

        .media-input {
            display: flex;
            gap: 8px;
        }

        .media-icon {
            width: 43px;
            height: 43px;

            display: flex;
            align-items: center;
            justify-content: center;

            flex: 0 0 auto;

            border-radius: 10px;

            color: var(--blue);

            background: var(--blue-soft);
        }

        /* =================================================
           STATUS TOGGLE
        ================================================= */

        .toggle-row {
            display: flex;
            align-items: center;
            justify-content: space-between;

            gap: 10px;

            padding: 12px;

            border: 1px solid var(--border);

            border-radius: 11px;

            background: #fbfdfc;
        }

        .toggle-text strong {
            display: block;

            font-size: 11px;
        }

        .toggle-text span {
            display: block;

            margin-top: 3px;

            color: var(--muted);

            font-size: 9px;
        }

        .switch {
            position: relative;

            width: 44px;
            height: 25px;

            flex: 0 0 auto;
        }

        .switch input {
            width: 0;
            height: 0;

            opacity: 0;
        }

        .slider {
            position: absolute;

            inset: 0;

            cursor: pointer;

            border-radius: 999px;

            background: #ccd6d1;

            transition: .25s ease;
        }

        .slider::before {
            content: "";

            position: absolute;

            width: 19px;
            height: 19px;

            left: 3px;
            top: 3px;

            border-radius: 50%;

            background: #fff;

            box-shadow:
                0 2px 6px rgba(0, 0, 0, .17);

            transition: .25s ease;
        }

        .switch input:checked + .slider {
            background: var(--green);
        }

        .switch input:checked + .slider::before {
            transform: translateX(19px);
        }

        /* =================================================
           FORM ACTIONS
        ================================================= */

        .form-actions {
            display: flex;
            gap: 8px;

            margin-top: 20px;
            padding-top: 19px;

            border-top: 1px solid var(--border);
        }

        .btn {
            height: 42px;

            display: inline-flex;
            align-items: center;
            justify-content: center;

            gap: 7px;

            flex: 1;

            border-radius: 10px;

            cursor: pointer;

            font-size: 11px;
            font-weight: 800;

            transition: .2s ease;
        }

        .btn:hover {
            transform: translateY(-1px);
        }

        .btn-secondary {
            color: #56635c;

            background: #fff;

            border: 1px solid var(--border);
        }

        .btn-primary {
            color: #fff;

            border: 0;

            background:
                linear-gradient(
                    135deg,
                    #0f7655,
                    #07553e
                );

            box-shadow:
                0 8px 20px rgba(13, 107, 77, .18);
        }

        .edit-mode {
            padding: 9px 11px;

            margin-bottom: 17px;

            border-radius: 10px;

            color: #285f4c;

            background: var(--green-soft);

            font-size: 10px;
            font-weight: 700;
        }

        .edit-mode i {
            margin-right: 5px;
        }

        /* =================================================
           RESPONSIVE
        ================================================= */

        @media (max-width: 1200px) {

            .main-grid {
                grid-template-columns: 1fr;
            }

            .form-card {
                position: static;
            }

            .stats-grid {
                grid-template-columns:
                    repeat(2, minmax(0, 1fr));
            }
        }

        @media (max-width: 1100px) {

            .pc-page {
                margin-left: 0;
            }
        }

        @media (max-width: 760px) {

            .pc-topbar {
                min-height: 70px;

                padding: 11px 15px;
            }

            .topbar-title span {
                display: none;
            }

            .admin-name {
                display: none;
            }

            .top-action span {
                display: none;
            }

            .pc-content {
                padding: 20px 14px 30px;
            }

            .page-heading {
                align-items: flex-start;

                flex-direction: column;
            }

            .page-heading h2 {
                font-size: 24px;
            }

            .stats-grid {
                grid-template-columns: 1fr 1fr;

                gap: 10px;
            }

            .stat-card {
                padding: 14px;
            }

            .stat-number {
                font-size: 21px;
            }

            .filter-bar {
                align-items: stretch;

                flex-direction: column;
            }

            .filter-select,
            .filter-btn {
                width: 100%;
            }

            .card-header,
            .card-body {
                padding: 17px;
            }
        }

        @media (max-width: 450px) {

            .stats-grid {
                grid-template-columns: 1fr;
            }

            .topbar-icon {
                width: 40px;
                height: 40px;
            }
        }

    </style>

</head>

<body>

<?php
/*
|--------------------------------------------------------------------------
| IMPORTANT
|--------------------------------------------------------------------------
| Existing sidebar is included separately.
| header.php is NOT included to prevent duplicate sidebar.
|--------------------------------------------------------------------------
*/

require_once __DIR__ . '/sidebar.php';
?>

<div class="pc-page">

    <!-- =====================================================
         TOPBAR
    ====================================================== -->

    <header class="pc-topbar">

        <div class="topbar-left">

            <div class="topbar-icon">
                <i class="fa-solid fa-layer-group"></i>
            </div>

            <div class="topbar-title">

                <h1>
                    Blog Categories
                </h1>

                <span>
                    Organize and manage your blog content
                </span>

            </div>

        </div>

        <div class="topbar-right">

            <a
                href="blog_posts.php"
                class="top-action secondary"
            >
                <i class="fa-solid fa-newspaper"></i>
                <span>Blog Posts</span>
            </a>

            <a
                href="blog_categories.php"
                class="top-action primary"
            >
                <i class="fa-solid fa-folder-plus"></i>
                <span>Categories</span>
            </a>

            <div class="admin-chip">

                <div class="admin-avatar">

                    <?php
                    echo e(
                        strtoupper(
                            mb_substr(
                                $adminName,
                                0,
                                1,
                                'UTF-8'
                            )
                        )
                    );
                    ?>

                </div>

                <div class="admin-name">
                    <?php echo e($adminName); ?>
                </div>

            </div>

        </div>

    </header>

    <!-- =====================================================
         CONTENT
    ====================================================== -->

    <main class="pc-content">

        <div class="page-heading">

            <div>

                <div class="eyebrow">
                    <i class="fa-solid fa-folder-tree"></i>
                    Content Structure
                </div>

                <h2>
                    Blog Categories
                </h2>

                <p>
                    Create parent and child categories for your blog.
                </p>

            </div>

        </div>

        <!-- =================================================
             FLASH SUCCESS
        ================================================== -->

        <?php if ($successMessage !== ''): ?>

            <div class="alert success">

                <i class="fa-solid fa-circle-check"></i>

                <div>
                    <?php echo e($successMessage); ?>
                </div>

            </div>

        <?php endif; ?>

        <!-- =================================================
             FLASH ERROR
        ================================================== -->

        <?php if ($errorMessage !== ''): ?>

            <div class="alert error">

                <i class="fa-solid fa-circle-exclamation"></i>

                <div>
                    <?php echo e($errorMessage); ?>
                </div>

            </div>

        <?php endif; ?>

        <!-- =================================================
             FORM ERRORS
        ================================================== -->

        <?php if (!empty($formErrors)): ?>

            <div class="alert error">

                <i class="fa-solid fa-triangle-exclamation"></i>

                <div>

                    <strong>
                        Please fix the following:
                    </strong>

                    <ul style="margin:6px 0 0 16px;padding:0;">

                        <?php foreach ($formErrors as $formError): ?>

                            <li>
                                <?php echo e($formError); ?>
                            </li>

                        <?php endforeach; ?>

                    </ul>

                </div>

            </div>

        <?php endif; ?>

        <!-- =================================================
             STATS
        ================================================== -->

        <div class="stats-grid">

            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-label">
                        Total Categories
                    </div>

                    <div class="stat-icon">
                        <i class="fa-solid fa-folder"></i>
                    </div>

                </div>

                <div class="stat-number">
                    <?php echo number_format($totalCategories); ?>
                </div>

            </div>

            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-label">
                        Active
                    </div>

                    <div class="stat-icon">
                        <i class="fa-solid fa-circle-check"></i>
                    </div>

                </div>

                <div class="stat-number">
                    <?php echo number_format($activeCategories); ?>
                </div>

            </div>

            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-label">
                        Inactive
                    </div>

                    <div class="stat-icon">
                        <i class="fa-solid fa-circle-pause"></i>
                    </div>

                </div>

                <div class="stat-number">
                    <?php echo number_format($inactiveCategories); ?>
                </div>

            </div>

            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-label">
                        Parent Categories
                    </div>

                    <div class="stat-icon">
                        <i class="fa-solid fa-sitemap"></i>
                    </div>

                </div>

                <div class="stat-number">
                    <?php echo number_format($parentCategoriesCount); ?>
                </div>

            </div>

        </div>

        <!-- =================================================
             MAIN GRID
        ================================================== -->

        <div class="main-grid">

            <!-- =============================================
                 CATEGORY LIST
            ============================================== -->

            <section class="card">

                <div class="card-header">

                    <div class="card-heading">

                        <div class="card-heading-icon">
                            <i class="fa-solid fa-list-tree"></i>
                        </div>

                        <div>

                            <h3>
                                All Categories
                            </h3>

                            <p>
                                <?php
                                echo number_format(
                                    count($filteredCategories)
                                );
                                ?>
                                categories shown
                            </p>

                        </div>

                    </div>

                    <a
                        href="blog_categories.php"
                        class="filter-btn"
                    >
                        <i class="fa-solid fa-arrows-rotate"></i>
                        Reset
                    </a>

                </div>

                <div class="card-body">

                    <!-- SEARCH -->

                    <form
                        method="GET"
                        class="filter-bar"
                    >

                        <div class="search-wrap">

                            <i class="fa-solid fa-magnifying-glass"></i>

                            <input
                                type="search"
                                name="q"
                                class="search-input"
                                value="<?php echo e($search); ?>"
                                placeholder="Search category name, slug or description..."
                            >

                        </div>

                        <select
                            name="status"
                            class="filter-select"
                        >

                            <option
                                value="all"
                                <?php
                                echo $filterStatus === 'all'
                                    ? 'selected'
                                    : '';
                                ?>
                            >
                                All Status
                            </option>

                            <option
                                value="active"
                                <?php
                                echo $filterStatus === 'active'
                                    ? 'selected'
                                    : '';
                                ?>
                            >
                                Active
                            </option>

                            <option
                                value="inactive"
                                <?php
                                echo $filterStatus === 'inactive'
                                    ? 'selected'
                                    : '';
                                ?>
                            >
                                Inactive
                            </option>

                        </select>

                        <button
                            type="submit"
                            class="filter-btn"
                        >
                            <i class="fa-solid fa-filter"></i>
                            Filter
                        </button>

                    </form>

                    <!-- TABLE -->

                    <?php if (!empty($filteredCategories)): ?>

                        <div class="table-wrap">

                            <table>

                                <thead>

                                    <tr>

                                        <th>
                                            Category
                                        </th>

                                        <th>
                                            Parent
                                        </th>

                                        <th>
                                            Slug
                                        </th>

                                        <th>
                                            Sort
                                        </th>

                                        <th>
                                            Status
                                        </th>

                                        <th>
                                            Created
                                        </th>

                                        <th>
                                            Actions
                                        </th>

                                    </tr>

                                </thead>

                                <tbody>

                                    <?php foreach (
                                        $filteredCategories
                                        as $category
                                    ): ?>

                                        <tr>

                                            <!-- CATEGORY -->

                                            <td>

                                                <div class="category-name">

                                                    <div class="category-icon">

                                                        <i class="fa-regular fa-folder-open"></i>

                                                    </div>

                                                    <div class="category-info">

                                                        <strong>
                                                            <?php
                                                            echo e(
                                                                $category['name']
                                                            );
                                                            ?>
                                                        </strong>

                                                        <?php if (
                                                            !empty(
                                                                $category['description']
                                                            )
                                                        ): ?>

                                                            <span>
                                                                <?php
                                                                echo e(
                                                                    $category['description']
                                                                );
                                                                ?>
                                                            </span>

                                                        <?php else: ?>

                                                            <span>
                                                                No description
                                                            </span>

                                                        <?php endif; ?>

                                                    </div>

                                                </div>

                                            </td>

                                            <!-- PARENT -->

                                            <td>

                                                <?php
                                                $parentId =
                                                    (int)(
                                                        $category['parent_id']
                                                        ?? 0
                                                    );

                                                if (
                                                    $parentId > 0
                                                    &&
                                                    isset(
                                                        $categoryMap[$parentId]
                                                    )
                                                ):
                                                ?>

                                                    <span class="parent-badge">

                                                        <i class="fa-solid fa-turn-up"></i>

                                                        <?php
                                                        echo e(
                                                            $categoryMap[
                                                                $parentId
                                                            ]['name']
                                                        );
                                                        ?>

                                                    </span>

                                                <?php else: ?>

                                                    <span class="parent-badge root-badge">

                                                        <i class="fa-solid fa-house"></i>

                                                        Root

                                                    </span>

                                                <?php endif; ?>

                                            </td>

                                            <!-- SLUG -->

                                            <td>

                                                <span class="slug-text">
                                                    /<?php
                                                    echo e(
                                                        $category['slug']
                                                    );
                                                    ?>
                                                </span>

                                            </td>

                                            <!-- SORT -->

                                            <td>

                                                <span class="order-number">
                                                    <?php
                                                    echo (int)(
                                                        $category['sort_order']
                                                    );
                                                    ?>
                                                </span>

                                            </td>

                                            <!-- STATUS -->

                                            <td>

                                                <?php if (
                                                    (int)$category['status']
                                                    ===
                                                    1
                                                ): ?>

                                                    <span class="status-badge active">

                                                        <span class="status-dot"></span>

                                                        Active

                                                    </span>

                                                <?php else: ?>

                                                    <span class="status-badge inactive">

                                                        <span class="status-dot"></span>

                                                        Inactive

                                                    </span>

                                                <?php endif; ?>

                                            </td>

                                            <!-- CREATED -->

                                            <td>

                                                <span
                                                    style="
                                                        color:#718078;
                                                        font-size:10px;
                                                        white-space:nowrap;
                                                    "
                                                >
                                                    <?php
                                                    echo !empty(
                                                        $category['created_at']
                                                    )
                                                        ? e(
                                                            date(
                                                                'd M Y',
                                                                strtotime(
                                                                    $category['created_at']
                                                                )
                                                            )
                                                        )
                                                        : '—';
                                                    ?>
                                                </span>

                                            </td>

                                            <!-- ACTIONS -->

                                            <td>

                                                <div class="action-group">

                                                    <a
                                                        href="blog_categories.php?edit=<?php echo (int)$category['id']; ?>"
                                                        class="icon-btn edit"
                                                        title="Edit category"
                                                    >
                                                        <i class="fa-solid fa-pen"></i>
                                                    </a>

                                                    <form
                                                        method="POST"
                                                        class="delete-form"
                                                        style="display:inline;"
                                                    >

                                                        <?php
                                                        echo blog_category_csrf_field();
                                                        ?>

                                                        <input
                                                            type="hidden"
                                                            name="action"
                                                            value="delete"
                                                        >

                                                        <input
                                                            type="hidden"
                                                            name="category_id"
                                                            value="<?php echo (int)$category['id']; ?>"
                                                        >

                                                        <button
                                                            type="submit"
                                                            class="icon-btn delete"
                                                            title="Delete category"
                                                        >
                                                            <i class="fa-regular fa-trash-can"></i>
                                                        </button>

                                                    </form>

                                                </div>

                                            </td>

                                        </tr>

                                    <?php endforeach; ?>

                                </tbody>

                            </table>

                        </div>

                    <?php else: ?>

                        <div class="empty-state">

                            <div class="empty-icon">

                                <i class="fa-regular fa-folder-open"></i>

                            </div>

                            <h4>
                                No blog categories found
                            </h4>

                            <p>
                                <?php if ($search !== ''): ?>

                                    No categories match your search.

                                <?php else: ?>

                                    Create your first blog category using the form.

                                <?php endif; ?>
                            </p>

                        </div>

                    <?php endif; ?>

                </div>

            </section>

            <!-- =============================================
                 ADD / EDIT FORM
            ============================================== -->

            <section class="card form-card">

                <div class="card-header">

                    <div class="card-heading">

                        <div class="card-heading-icon">

                            <?php if ($form['id'] > 0): ?>

                                <i class="fa-solid fa-pen-to-square"></i>

                            <?php else: ?>

                                <i class="fa-solid fa-folder-plus"></i>

                            <?php endif; ?>

                        </div>

                        <div>

                            <h3>

                                <?php if ($form['id'] > 0): ?>

                                    Edit Category

                                <?php else: ?>

                                    Add Category

                                <?php endif; ?>

                            </h3>

                            <p>
                                Manage category details
                            </p>

                        </div>

                    </div>

                </div>

                <div class="card-body">

                    <?php if ($form['id'] > 0): ?>

                        <div class="edit-mode">

                            <i class="fa-solid fa-pen"></i>

                            Editing category
                            #<?php echo (int)$form['id']; ?>

                        </div>

                    <?php endif; ?>

                    <form
                        method="POST"
                        id="categoryForm"
                    >

                        <?php
                        echo blog_category_csrf_field();
                        ?>

                        <input
                            type="hidden"
                            name="action"
                            value="save"
                        >

                        <input
                            type="hidden"
                            name="id"
                            value="<?php echo (int)$form['id']; ?>"
                        >

                        <!-- NAME -->

                        <div class="field">

                            <label for="name">

                                Category Name

                                <span class="required">
                                    *
                                </span>

                            </label>

                            <input
                                type="text"
                                id="name"
                                name="name"
                                class="input"
                                maxlength="255"
                                required
                                value="<?php echo e($form['name']); ?>"
                                placeholder="e.g. Chemical Industry"
                            >

                        </div>

                        <!-- SLUG -->

                        <div class="field">

                            <label for="slug">
                                Slug
                            </label>

                            <div class="slug-wrap">

                                <input
                                    type="text"
                                    id="slug"
                                    name="slug"
                                    class="input"
                                    maxlength="255"
                                    value="<?php echo e($form['slug']); ?>"
                                    placeholder="chemical-industry"
                                >

                                <button
                                    type="button"
                                    class="slug-btn"
                                    id="generateSlug"
                                    title="Generate slug"
                                >
                                    <i class="fa-solid fa-wand-magic-sparkles"></i>
                                </button>

                            </div>

                            <div class="field-help">
                                URL-friendly category identifier.
                            </div>

                        </div>

                        <!-- PARENT -->

                        <div class="field">

                            <label for="parent_id">
                                Parent Category
                            </label>

                            <select
                                name="parent_id"
                                id="parent_id"
                                class="select"
                            >

                                <option value="">
                                    — Root Category —
                                </option>

                                <?php foreach (
                                    $parentCategories
                                    as $parent
                                ): ?>

                                    <option
                                        value="<?php echo (int)$parent['id']; ?>"
                                        <?php
                                        echo (
                                            (string)$form['parent_id']
                                            ===
                                            (string)$parent['id']
                                        )
                                            ? 'selected'
                                            : '';
                                        ?>
                                    >

                                        <?php
                                        echo e(
                                            $parent['name']
                                        );
                                        ?>

                                    </option>

                                <?php endforeach; ?>

                            </select>

                            <div class="field-help">
                                Select a parent to create a nested category.
                            </div>

                        </div>

                        <!-- DESCRIPTION -->

                        <div class="field">

                            <label for="description">
                                Description
                            </label>

                            <textarea
                                name="description"
                                id="description"
                                class="textarea"
                                placeholder="Short description of this blog category..."
                            ><?php
                            echo e(
                                $form['description']
                            );
                            ?></textarea>

                        </div>

                        <!-- IMAGE: SELECT AN EXISTING IMAGE FROM MEDIA LIBRARY -->

                        <div class="field">

                            <label for="image_id">
                                Category Image <span class="field-help-inline">(Optional)</span>
                            </label>

                            <div class="media-input">

                                <div class="media-icon">
                                    <i class="fa-regular fa-image"></i>
                                </div>

                                <select
                                    id="image_id"
                                    name="image_id"
                                    class="input"
                                >
                                    <option value="">No image selected</option>
                                    <?php foreach ($mediaItems as $mediaItem): ?>
                                        <?php
                                        $mediaId = (int)($mediaItem['id'] ?? 0);
                                        $mediaLabel = trim((string)($mediaItem['title'] ?? ''));
                                        if ($mediaLabel === '') {
                                            $mediaLabel = trim((string)($mediaItem['original_name'] ?? ''));
                                        }
                                        if ($mediaLabel === '') {
                                            $mediaLabel = trim((string)($mediaItem['file_name'] ?? ''));
                                        }
                                        if ($mediaLabel === '') {
                                            $mediaLabel = 'Image';
                                        }
                                        ?>
                                        <option
                                            value="<?php echo $mediaId; ?>"
                                            <?php echo ((string)$form['image_id'] === (string)$mediaId) ? 'selected' : ''; ?>
                                        ><?php echo e($mediaLabel . ' (Media ID: ' . $mediaId . ')'); ?></option>
                                    <?php endforeach; ?>
                                </select>

                            </div>

                            <div class="field-help">
                                <?php if ($mediaLoadError): ?>
                                    Could not load the media library. You can still save this category without an image; check the media table/database connection.
                                <?php elseif (empty($mediaItems)): ?>
                                    No images were found in the media library. Upload an image in Media Library first, or leave this as “No image selected”.
                                <?php else: ?>
                                    Choose an existing image from the list. The Media ID is linked automatically; you do not need to type an ID.
                                <?php endif; ?>
                            </div>

                        </div>

                        <!-- SORT -->

                        <div class="field">

                            <label for="sort_order">
                                Sort Order
                            </label>

                            <input
                                type="number"
                                id="sort_order"
                                name="sort_order"
                                class="input"
                                value="<?php echo e($form['sort_order']); ?>"
                                placeholder="0"
                            >

                            <div class="field-help">
                                Lower values appear first.
                            </div>

                        </div>

                        <!-- STATUS -->

                        <div class="field">

                            <div class="toggle-row">

                                <div class="toggle-text">

                                    <strong>
                                        Active Category
                                    </strong>

                                    <span>
                                        Show this category on the website.
                                    </span>

                                </div>

                                <label class="switch">

                                    <input
                                        type="checkbox"
                                        name="status"
                                        value="1"
                                        <?php
                                        echo (int)$form['status'] === 1
                                            ? 'checked'
                                            : '';
                                        ?>
                                    >

                                    <span class="slider"></span>

                                </label>

                            </div>

                        </div>

                        <!-- ACTIONS -->

                        <div class="form-actions">

                            <?php if ($form['id'] > 0): ?>

                                <a
                                    href="blog_categories.php"
                                    class="btn btn-secondary"
                                >
                                    <i class="fa-solid fa-xmark"></i>
                                    Cancel
                                </a>

                            <?php else: ?>

                                <button
                                    type="reset"
                                    class="btn btn-secondary"
                                    id="resetForm"
                                >
                                    <i class="fa-solid fa-rotate-left"></i>
                                    Reset
                                </button>

                            <?php endif; ?>

                            <button
                                type="submit"
                                class="btn btn-primary"
                                id="saveButton"
                            >

                                <?php if ($form['id'] > 0): ?>

                                    <i class="fa-solid fa-floppy-disk"></i>
                                    Update

                                <?php else: ?>

                                    <i class="fa-solid fa-plus"></i>
                                    Create

                                <?php endif; ?>

                            </button>

                        </div>

                    </form>

                </div>

            </section>

        </div>

    </main>

</div>

<!-- =========================================================
     JAVASCRIPT
========================================================= -->

<script>

/* =========================================================
   SLUG GENERATOR
========================================================= */

(function () {

    const nameInput =
        document.getElementById('name');

    const slugInput =
        document.getElementById('slug');

    const generateButton =
        document.getElementById('generateSlug');

    if (
        !nameInput ||
        !slugInput ||
        !generateButton
    ) {
        return;
    }

    function makeSlug(value) {

        value = value
            .toString()
            .trim()
            .toLowerCase();

        value = value
            .normalize('NFD')
            .replace(
                /[\u0300-\u036f]/g,
                ''
            );

        value = value
            .replace(
                /[^a-z0-9]+/g,
                '-'
            )
            .replace(
                /^-+|-+$/g,
                ''
            );

        return value || 'category';
    }

    let slugChanged =
        slugInput.value.trim() !== '';

    nameInput.addEventListener(
        'input',
        function () {

            if (!slugChanged) {

                slugInput.value =
                    makeSlug(
                        nameInput.value
                    );
            }
        }
    );

    slugInput.addEventListener(
        'input',
        function () {

            slugChanged = true;

        }
    );

    generateButton.addEventListener(
        'click',
        function () {

            slugInput.value =
                makeSlug(
                    nameInput.value
                );

            slugChanged = true;

            slugInput.focus();

        }
    );

})();

/* =========================================================
   DELETE CONFIRMATION
========================================================= */

(function () {

    const forms =
        document.querySelectorAll(
            '.delete-form'
        );

    forms.forEach(function (form) {

        form.addEventListener(
            'submit',
            function (event) {

                const confirmed =
                    window.confirm(
                        'Are you sure you want to delete this blog category?\n\nCategories with child categories or blog posts cannot be deleted.'
                    );

                if (!confirmed) {
                    event.preventDefault();
                }

            }
        );

    });

})();

/* =========================================================
   SAVE BUTTON PROTECTION
========================================================= */

(function () {

    const form =
        document.getElementById(
            'categoryForm'
        );

    const button =
        document.getElementById(
            'saveButton'
        );

    if (!form || !button) {
        return;
    }

    form.addEventListener(
        'submit',
        function () {

            button.disabled = true;

            button.innerHTML =
                '<i class="fa-solid fa-spinner fa-spin"></i> Saving...';

        }
    );

})();

/* =========================================================
   RESET SLUG
========================================================= */

(function () {

    const resetButton =
        document.getElementById(
            'resetForm'
        );

    if (!resetButton) {
        return;
    }

    resetButton.addEventListener(
        'click',
        function () {

            setTimeout(
                function () {

                    const slug =
                        document.getElementById(
                            'slug'
                        );

                    if (slug) {
                        slug.value = '';
                    }

                },
                0
            );

        }
    );

})();

</script>

</body>
</html>