<?php
/**
 * Pure Chemical Admin
 * File: admin/sections.php
 *
 * Existing table used:
 * page_sections
 *
 * No new table required.
 */

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/includes/db.php';

if (file_exists(__DIR__ . '/includes/auth.php')) {
    require_once __DIR__ . '/includes/auth.php';
}

if (function_exists('requireAdmin')) {
    requireAdmin();
}

/* ---------------------------------------------------------
   Helpers
--------------------------------------------------------- */

function pc_e($value)
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function pc_csrf_token()
{
    if (function_exists('csrf_token')) {
        return csrf_token();
    }

    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }

    return $_SESSION['csrf_token'];
}

function pc_csrf_field()
{
    if (function_exists('csrf_field')) {
        return csrf_field();
    }

    return '<input type="hidden" name="csrf_token" value="' .
        pc_e(pc_csrf_token()) .
        '">';
}

function pc_verify_csrf()
{
    if (function_exists('csrf_verify')) {
        csrf_verify();
        return true;
    }

    $token = $_POST['csrf_token'] ?? '';

    if (
        empty($_SESSION['csrf_token']) ||
        !hash_equals($_SESSION['csrf_token'], $token)
    ) {
        throw new RuntimeException('Invalid security token. Please refresh and try again.');
    }

    return true;
}

function pc_redirect($url)
{
    header('Location: ' . $url);
    exit;
}

function pc_flash($type, $message)
{
    $_SESSION['sections_flash'] = [
        'type' => $type,
        'message' => $message
    ];
}

function pc_get_flash()
{
    $flash = $_SESSION['sections_flash'] ?? null;
    unset($_SESSION['sections_flash']);

    return $flash;
}

/* ---------------------------------------------------------
   Flash / current state
--------------------------------------------------------- */

$flash = pc_get_flash();

$editId = isset($_GET['edit']) ? (int)$_GET['edit'] : 0;
$selectedPage = isset($_GET['page_id']) ? (int)$_GET['page_id'] : 0;
$statusFilter = isset($_GET['status']) ? $_GET['status'] : '';
$search = trim($_GET['search'] ?? '');

/* ---------------------------------------------------------
   Page list
--------------------------------------------------------- */

$pages = [];

try {
    $pageStmt = $pdo->query("
        SELECT id, title, slug
        FROM pages
        ORDER BY title ASC, id ASC
    ");

    $pages = $pageStmt->fetchAll();
} catch (Throwable $e) {
    /*
     * If the pages table has a different display structure,
     * page_id can still be managed manually below.
     */
    $pages = [];
}

/* ---------------------------------------------------------
   Default form
--------------------------------------------------------- */

$form = [
    'id'               => 0,
    'page_id'          => $selectedPage,
    'section_key'      => '',
    'section_type'     => 'content',
    'title'            => '',
    'subtitle'         => '',
    'content'          => '',
    'settings'         => '',
    'background_type'  => 'none',
    'background_value' => '',
    'custom_css'       => '',
    'custom_js'        => '',
    'sort_order'       => 0,
    'status'           => 1
];

/* ---------------------------------------------------------
   Edit record
--------------------------------------------------------- */

if ($editId > 0) {
    try {
        $stmt = $pdo->prepare("
            SELECT
                id,
                page_id,
                section_key,
                section_type,
                title,
                subtitle,
                content,
                settings,
                background_type,
                background_value,
                custom_css,
                custom_js,
                sort_order,
                status,
                created_at,
                updated_at
            FROM page_sections
            WHERE id = ?
            LIMIT 1
        ");

        $stmt->execute([$editId]);
        $record = $stmt->fetch();

        if ($record) {
            $form = array_merge($form, $record);
            $selectedPage = (int)$record['page_id'];
        } else {
            pc_flash('error', 'Section record nahi mila.');
            pc_redirect('sections.php');
        }
    } catch (Throwable $e) {
        pc_flash('error', 'Section load nahi ho saka.');
        pc_redirect('sections.php');
    }
}

/* ---------------------------------------------------------
   POST ACTIONS
--------------------------------------------------------- */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    try {
        pc_verify_csrf();

        $action = $_POST['action'] ?? '';

        /* ---------------------------------------------
           SAVE / UPDATE
        --------------------------------------------- */
        if ($action === 'save') {

            $id = (int)($_POST['id'] ?? 0);

            $pageId = (int)($_POST['page_id'] ?? 0);

            $sectionKey = trim($_POST['section_key'] ?? '');
            $sectionType = trim($_POST['section_type'] ?? '');
            $title = trim($_POST['title'] ?? '');
            $subtitle = trim($_POST['subtitle'] ?? '');
            $content = $_POST['content'] ?? '';
            $settings = $_POST['settings'] ?? '';
            $backgroundType = $_POST['background_type'] ?? 'none';
            $backgroundValue = trim($_POST['background_value'] ?? '');
            $customCss = $_POST['custom_css'] ?? '';
            $customJs = $_POST['custom_js'] ?? '';
            $sortOrder = (int)($_POST['sort_order'] ?? 0);
            $status = isset($_POST['status']) ? 1 : 0;

            $allowedBackgrounds = [
                'none',
                'color',
                'image',
                'video'
            ];

            if ($pageId <= 0) {
                throw new RuntimeException('Please select a page.');
            }

            if ($sectionType === '') {
                throw new RuntimeException('Section type required hai.');
            }

            if (!in_array($backgroundType, $allowedBackgrounds, true)) {
                $backgroundType = 'none';
            }

            /*
             * section_key is optional according to schema.
             * If empty, NULL is stored.
             */
            $sectionKeyDb = ($sectionKey !== '') ? $sectionKey : null;

            $backgroundValueDb = (
                $backgroundValue !== ''
            ) ? $backgroundValue : null;

            $subtitleDb = (
                $subtitle !== ''
            ) ? $subtitle : null;

            $titleDb = (
                $title !== ''
            ) ? $title : null;

            $contentDb = (
                trim($content) !== ''
            ) ? $content : null;

            $settingsDb = (
                trim($settings) !== ''
            ) ? $settings : null;

            $customCssDb = (
                trim($customCss) !== ''
            ) ? $customCss : null;

            $customJsDb = (
                trim($customJs) !== ''
            ) ? $customJs : null;

            if ($id > 0) {

                $stmt = $pdo->prepare("
                    UPDATE page_sections
                    SET
                        page_id = ?,
                        section_key = ?,
                        section_type = ?,
                        title = ?,
                        subtitle = ?,
                        content = ?,
                        settings = ?,
                        background_type = ?,
                        background_value = ?,
                        custom_css = ?,
                        custom_js = ?,
                        sort_order = ?,
                        status = ?
                    WHERE id = ?
                    LIMIT 1
                ");

                $stmt->execute([
                    $pageId,
                    $sectionKeyDb,
                    $sectionType,
                    $titleDb,
                    $subtitleDb,
                    $contentDb,
                    $settingsDb,
                    $backgroundType,
                    $backgroundValueDb,
                    $customCssDb,
                    $customJsDb,
                    $sortOrder,
                    $status,
                    $id
                ]);

                pc_flash('success', 'Section successfully updated.');
            } else {

                $stmt = $pdo->prepare("
                    INSERT INTO page_sections
                    (
                        page_id,
                        section_key,
                        section_type,
                        title,
                        subtitle,
                        content,
                        settings,
                        background_type,
                        background_value,
                        custom_css,
                        custom_js,
                        sort_order,
                        status
                    )
                    VALUES
                    (
                        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
                    )
                ");

                $stmt->execute([
                    $pageId,
                    $sectionKeyDb,
                    $sectionType,
                    $titleDb,
                    $subtitleDb,
                    $contentDb,
                    $settingsDb,
                    $backgroundType,
                    $backgroundValueDb,
                    $customCssDb,
                    $customJsDb,
                    $sortOrder,
                    $status
                ]);

                pc_flash('success', 'New section successfully created.');
            }

            pc_redirect(
                'sections.php?page_id=' . $pageId
            );
        }

        /* ---------------------------------------------
           DELETE
        --------------------------------------------- */
        if ($action === 'delete') {

            $id = (int)($_POST['id'] ?? 0);

            if ($id <= 0) {
                throw new RuntimeException('Invalid section ID.');
            }

            $stmt = $pdo->prepare("
                DELETE FROM page_sections
                WHERE id = ?
                LIMIT 1
            ");

            $stmt->execute([$id]);

            pc_flash('success', 'Section deleted successfully.');

            $redirectPage = (int)($_POST['redirect_page'] ?? 0);

            pc_redirect(
                'sections.php' .
                ($redirectPage > 0
                    ? '?page_id=' . $redirectPage
                    : '')
            );
        }

        /* ---------------------------------------------
           TOGGLE STATUS
        --------------------------------------------- */
        if ($action === 'toggle_status') {

            $id = (int)($_POST['id'] ?? 0);

            if ($id <= 0) {
                throw new RuntimeException('Invalid section ID.');
            }

            $stmt = $pdo->prepare("
                UPDATE page_sections
                SET status = IF(status = 1, 0, 1)
                WHERE id = ?
                LIMIT 1
            ");

            $stmt->execute([$id]);

            pc_flash('success', 'Section status updated.');

            $redirectPage = (int)($_POST['redirect_page'] ?? 0);

            pc_redirect(
                'sections.php' .
                ($redirectPage > 0
                    ? '?page_id=' . $redirectPage
                    : '')
            );
        }

        /* ---------------------------------------------
           QUICK SORT
        --------------------------------------------- */
        if ($action === 'quick_sort') {

            $id = (int)($_POST['id'] ?? 0);
            $sortOrder = (int)($_POST['sort_order'] ?? 0);

            if ($id <= 0) {
                throw new RuntimeException('Invalid section ID.');
            }

            $stmt = $pdo->prepare("
                UPDATE page_sections
                SET sort_order = ?
                WHERE id = ?
                LIMIT 1
            ");

            $stmt->execute([
                $sortOrder,
                $id
            ]);

            pc_flash('success', 'Sort order updated.');

            $redirectPage = (int)($_POST['redirect_page'] ?? 0);

            pc_redirect(
                'sections.php' .
                ($redirectPage > 0
                    ? '?page_id=' . $redirectPage
                    : '')
            );
        }

    } catch (Throwable $e) {

        $flash = [
            'type' => 'error',
            'message' => $e->getMessage()
        ];
    }
}

/* ---------------------------------------------------------
   Section listing
--------------------------------------------------------- */

$sections = [];

try {

    $where = [];
    $params = [];

    if ($selectedPage > 0) {
        $where[] = 'ps.page_id = ?';
        $params[] = $selectedPage;
    }

    if ($statusFilter !== '' && in_array($statusFilter, ['0', '1'], true)) {
        $where[] = 'ps.status = ?';
        $params[] = (int)$statusFilter;
    }

    if ($search !== '') {
        $where[] = "
            (
                ps.title LIKE ?
                OR ps.section_key LIKE ?
                OR ps.section_type LIKE ?
            )
        ";

        $like = '%' . $search . '%';

        $params[] = $like;
        $params[] = $like;
        $params[] = $like;
    }

    $whereSql = '';

    if (!empty($where)) {
        $whereSql = 'WHERE ' . implode(' AND ', $where);
    }

    /*
     * pages.title / pages.slug are used only for display.
     * If your pages table contains these standard fields,
     * this gives a useful page label in the admin list.
     */
    $sql = "
        SELECT
            ps.id,
            ps.page_id,
            ps.section_key,
            ps.section_type,
            ps.title,
            ps.subtitle,
            ps.content,
            ps.settings,
            ps.background_type,
            ps.background_value,
            ps.custom_css,
            ps.custom_js,
            ps.sort_order,
            ps.status,
            ps.created_at,
            ps.updated_at,
            p.title AS page_title,
            p.slug AS page_slug
        FROM page_sections ps
        LEFT JOIN pages p
            ON p.id = ps.page_id
        {$whereSql}
        ORDER BY
            ps.page_id ASC,
            ps.sort_order ASC,
            ps.id ASC
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

    $sections = $stmt->fetchAll();

} catch (Throwable $e) {

    /*
     * Fallback if page display columns differ.
     * Sections themselves remain fully manageable.
     */
    try {

        $where = [];
        $params = [];

        if ($selectedPage > 0) {
            $where[] = 'page_id = ?';
            $params[] = $selectedPage;
        }

        if ($statusFilter !== '' && in_array($statusFilter, ['0', '1'], true)) {
            $where[] = 'status = ?';
            $params[] = (int)$statusFilter;
        }

        if ($search !== '') {
            $where[] = "
                (
                    title LIKE ?
                    OR section_key LIKE ?
                    OR section_type LIKE ?
                )
            ";

            $like = '%' . $search . '%';

            $params[] = $like;
            $params[] = $like;
            $params[] = $like;
        }

        $whereSql = '';

        if (!empty($where)) {
            $whereSql = 'WHERE ' . implode(' AND ', $where);
        }

        $stmt = $pdo->prepare("
            SELECT
                id,
                page_id,
                section_key,
                section_type,
                title,
                subtitle,
                content,
                settings,
                background_type,
                background_value,
                custom_css,
                custom_js,
                sort_order,
                status,
                created_at,
                updated_at
            FROM page_sections
            {$whereSql}
            ORDER BY page_id ASC, sort_order ASC, id ASC
        ");

        $stmt->execute($params);

        $sections = $stmt->fetchAll();

    } catch (Throwable $inner) {

        $sections = [];

        if (!$flash) {
            $flash = [
                'type' => 'error',
                'message' => 'Sections load nahi ho sake.'
            ];
        }
    }
}

/* ---------------------------------------------------------
   Statistics
--------------------------------------------------------- */

$totalSections = count($sections);
$activeSections = 0;
$inactiveSections = 0;

foreach ($sections as $section) {
    if ((int)$section['status'] === 1) {
        $activeSections++;
    } else {
        $inactiveSections++;
    }
}

$totalPages = count($pages);

/* ---------------------------------------------------------
   Page name helper
--------------------------------------------------------- */

function pc_page_name($pageId, $pages)
{
    foreach ($pages as $page) {
        if ((int)$page['id'] === (int)$pageId) {
            return $page['title'] ?: ('Page #' . $page['id']);
        }
    }

    return 'Page #' . $pageId;
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>
        Sections | Pure Chemical Admin
    </title>

    <meta
        name="robots"
        content="noindex,nofollow"
    >

    <link
        rel="preconnect"
        href="https://fonts.googleapis.com"
    >

    <link
        rel="preconnect"
        href="https://fonts.gstatic.com"
        crossorigin
    >

    <link
        href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap"
        rel="stylesheet"
    >

    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
    >

    <style>

        :root {
            --primary: #0f766e;
            --primary-dark: #115e59;
            --primary-soft: #ecfdf5;

            --blue: #2563eb;
            --blue-soft: #eff6ff;

            --orange: #ea580c;
            --orange-soft: #fff7ed;

            --red: #dc2626;
            --red-soft: #fef2f2;

            --green: #16a34a;
            --green-soft: #f0fdf4;

            --dark: #0f172a;
            --text: #334155;
            --muted: #64748b;

            --border: #e2e8f0;
            --surface: #ffffff;
            --surface-soft: #f8fafc;

            --shadow-sm:
                0 1px 2px rgba(15, 23, 42, .04);

            --shadow-md:
                0 10px 30px rgba(15, 23, 42, .07);

            --shadow-lg:
                0 20px 60px rgba(15, 23, 42, .10);

            --radius: 18px;
        }

        * {
            box-sizing: border-box;
        }

        html {
            scroll-behavior: smooth;
        }

        body {
            margin: 0;
            background:
                linear-gradient(
                    180deg,
                    #f8fafc 0%,
                    #f1f5f9 100%
                );
            color: var(--text);
            font-family: "Inter", sans-serif;
            font-size: 14px;
        }

        a {
            color: inherit;
            text-decoration: none;
        }

        button,
        input,
        select,
        textarea {
            font: inherit;
        }

        /* ------------------------------------------------
           TOPBAR
        ------------------------------------------------ */

        .pc-topbar {
            position: sticky;
            top: 0;
            z-index: 1000;

            min-height: 76px;
            margin-left: 280px;

            padding: 14px 30px;

            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 20px;

            background: rgba(255,255,255,.92);
            backdrop-filter: blur(18px);

            border-bottom: 1px solid rgba(226,232,240,.85);

            box-shadow:
                0 8px 30px rgba(15,23,42,.04);
        }

        .pc-top-title {
            display: flex;
            align-items: center;
            gap: 13px;
        }

        .pc-top-icon {
            width: 44px;
            height: 44px;

            border-radius: 14px;

            display: grid;
            place-items: center;

            color: #fff;
            background:
                linear-gradient(
                    135deg,
                    var(--primary),
                    var(--primary-dark)
                );

            box-shadow:
                0 10px 24px rgba(15,118,110,.22);
        }

        .pc-top-title h1 {
            margin: 0;
            color: var(--dark);
            font-size: 18px;
            font-weight: 800;
            letter-spacing: -.35px;
        }

        .pc-top-title p {
            margin: 3px 0 0;
            color: var(--muted);
            font-size: 12px;
        }

        .pc-top-actions {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .pc-top-link {
            height: 42px;
            padding: 0 15px;

            display: inline-flex;
            align-items: center;
            gap: 8px;

            border: 1px solid var(--border);
            border-radius: 12px;

            background: #fff;
            color: var(--text);

            font-size: 13px;
            font-weight: 700;

            transition: .2s ease;
        }

        .pc-top-link:hover {
            border-color: #cbd5e1;
            transform: translateY(-1px);
            box-shadow: var(--shadow-sm);
        }

        /* ------------------------------------------------
           MAIN
        ------------------------------------------------ */

        .pc-main {
            margin-left: 280px;
            padding: 30px;
            min-height: calc(100vh - 76px);
        }

        .pc-container {
            max-width: 1700px;
            margin: 0 auto;
        }

        /* ------------------------------------------------
           HERO
        ------------------------------------------------ */

        .pc-hero {
            position: relative;
            overflow: hidden;

            padding: 30px;

            border-radius: 24px;

            background:
                linear-gradient(
                    135deg,
                    #0f172a 0%,
                    #134e4a 55%,
                    #0f766e 100%
                );

            box-shadow: var(--shadow-lg);

            color: #fff;

            margin-bottom: 22px;
        }

        .pc-hero::before {
            content: "";
            position: absolute;

            width: 260px;
            height: 260px;

            right: -90px;
            top: -110px;

            border-radius: 50%;

            background: rgba(255,255,255,.07);
        }

        .pc-hero::after {
            content: "";
            position: absolute;

            width: 180px;
            height: 180px;

            right: 170px;
            bottom: -120px;

            border-radius: 50%;

            background: rgba(255,255,255,.05);
        }

        .pc-hero-inner {
            position: relative;
            z-index: 2;

            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 25px;
        }

        .pc-hero h2 {
            margin: 0 0 8px;
            font-size: 27px;
            font-weight: 800;
            letter-spacing: -.7px;
        }

        .pc-hero p {
            max-width: 760px;
            margin: 0;

            color: rgba(255,255,255,.76);

            line-height: 1.7;
        }

        .pc-hero-btn {
            flex-shrink: 0;

            height: 46px;
            padding: 0 19px;

            display: inline-flex;
            align-items: center;
            gap: 9px;

            border: 1px solid rgba(255,255,255,.15);
            border-radius: 13px;

            background: rgba(255,255,255,.12);
            color: #fff;

            font-weight: 800;

            backdrop-filter: blur(10px);

            transition: .2s ease;
        }

        .pc-hero-btn:hover {
            background: rgba(255,255,255,.2);
            transform: translateY(-1px);
        }

        /* ------------------------------------------------
           FLASH
        ------------------------------------------------ */

        .pc-alert {
            margin-bottom: 20px;

            padding: 14px 16px;

            border-radius: 14px;

            display: flex;
            align-items: center;
            gap: 11px;

            font-weight: 600;
        }

        .pc-alert.success {
            color: #166534;
            background: var(--green-soft);
            border: 1px solid #bbf7d0;
        }

        .pc-alert.error {
            color: #991b1b;
            background: var(--red-soft);
            border: 1px solid #fecaca;
        }

        /* ------------------------------------------------
           STATS
        ------------------------------------------------ */

        .pc-stats {
            display: grid;
            grid-template-columns: repeat(4, minmax(0, 1fr));
            gap: 16px;

            margin-bottom: 22px;
        }

        .pc-stat {
            padding: 20px;

            background: var(--surface);

            border: 1px solid var(--border);
            border-radius: var(--radius);

            box-shadow: var(--shadow-sm);

            display: flex;
            align-items: center;
            gap: 14px;
        }

        .pc-stat-icon {
            width: 48px;
            height: 48px;

            flex-shrink: 0;

            display: grid;
            place-items: center;

            border-radius: 14px;

            font-size: 18px;
        }

        .pc-stat:nth-child(1) .pc-stat-icon {
            background: var(--primary-soft);
            color: var(--primary);
        }

        .pc-stat:nth-child(2) .pc-stat-icon {
            background: var(--blue-soft);
            color: var(--blue);
        }

        .pc-stat:nth-child(3) .pc-stat-icon {
            background: var(--green-soft);
            color: var(--green);
        }

        .pc-stat:nth-child(4) .pc-stat-icon {
            background: var(--orange-soft);
            color: var(--orange);
        }

        .pc-stat-label {
            color: var(--muted);
            font-size: 12px;
            font-weight: 600;
            margin-bottom: 3px;
        }

        .pc-stat-value {
            color: var(--dark);
            font-size: 22px;
            font-weight: 800;
        }

        /* ------------------------------------------------
           CARD
        ------------------------------------------------ */

        .pc-card {
            background: var(--surface);
            border: 1px solid var(--border);
            border-radius: var(--radius);

            box-shadow: var(--shadow-md);

            overflow: hidden;
            margin-bottom: 22px;
        }

        .pc-card-head {
            padding: 20px 22px;

            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 15px;

            border-bottom: 1px solid var(--border);
        }

        .pc-card-head h3 {
            margin: 0;
            color: var(--dark);
            font-size: 15px;
            font-weight: 800;
        }

        .pc-card-head p {
            margin: 4px 0 0;
            color: var(--muted);
            font-size: 12px;
        }

        .pc-card-body {
            padding: 22px;
        }

        /* ------------------------------------------------
           FILTERS
        ------------------------------------------------ */

        .pc-filters {
            display: grid;
            grid-template-columns:
                minmax(220px, 1.3fr)
                minmax(190px, 1fr)
                minmax(150px, .65fr)
                auto;

            gap: 12px;
            align-items: end;
        }

        .pc-field {
            min-width: 0;
        }

        .pc-field label {
            display: block;

            margin: 0 0 7px;

            color: #475569;

            font-size: 12px;
            font-weight: 800;
        }

        .pc-input,
        .pc-select,
        .pc-textarea {
            width: 100%;

            border: 1px solid #dbe3ec;
            border-radius: 11px;

            background: #fff;
            color: var(--dark);

            outline: none;

            transition: .2s ease;
        }

        .pc-input,
        .pc-select {
            height: 43px;
            padding: 0 13px;
        }

        .pc-textarea {
            min-height: 130px;
            padding: 12px 13px;
            resize: vertical;
            line-height: 1.6;
        }

        .pc-input:focus,
        .pc-select:focus,
        .pc-textarea:focus {
            border-color: var(--primary);
            box-shadow:
                0 0 0 4px rgba(15,118,110,.09);
        }

        .pc-filter-actions {
            display: flex;
            gap: 8px;
        }

        /* ------------------------------------------------
           BUTTONS
        ------------------------------------------------ */

        .pc-btn {
            min-height: 43px;
            padding: 0 15px;

            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;

            border: 1px solid transparent;
            border-radius: 11px;

            cursor: pointer;

            font-size: 13px;
            font-weight: 800;

            transition: .2s ease;
        }

        .pc-btn:hover {
            transform: translateY(-1px);
        }

        .pc-btn-primary {
            color: #fff;
            background: var(--primary);
            box-shadow:
                0 8px 20px rgba(15,118,110,.18);
        }

        .pc-btn-primary:hover {
            background: var(--primary-dark);
        }

        .pc-btn-light {
            color: #334155;
            background: #fff;
            border-color: var(--border);
        }

        .pc-btn-danger {
            color: #b91c1c;
            background: #fff;
            border-color: #fecaca;
        }

        .pc-btn-danger:hover {
            background: var(--red-soft);
        }

        .pc-btn-small {
            min-height: 35px;
            padding: 0 10px;
            border-radius: 9px;
            font-size: 12px;
        }

        /* ------------------------------------------------
           TABLE
        ------------------------------------------------ */

        .pc-table-wrap {
            width: 100%;
            overflow-x: auto;
        }

        .pc-table {
            width: 100%;
            min-width: 1080px;

            border-collapse: collapse;
        }

        .pc-table th {
            padding: 13px 16px;

            background: #f8fafc;

            border-bottom: 1px solid var(--border);

            color: #64748b;

            text-align: left;

            font-size: 11px;
            font-weight: 800;

            text-transform: uppercase;
            letter-spacing: .05em;

            white-space: nowrap;
        }

        .pc-table td {
            padding: 15px 16px;

            border-bottom: 1px solid #edf1f5;

            vertical-align: middle;
        }

        .pc-table tbody tr {
            transition: .18s ease;
        }

        .pc-table tbody tr:hover {
            background: #fbfefd;
        }

        .pc-section-name {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .pc-section-icon {
            width: 40px;
            height: 40px;

            flex-shrink: 0;

            display: grid;
            place-items: center;

            border-radius: 12px;

            color: var(--primary);
            background: var(--primary-soft);
        }

        .pc-section-title {
            color: var(--dark);
            font-weight: 800;
        }

        .pc-section-key {
            margin-top: 3px;

            color: var(--muted);

            font-family: monospace;
            font-size: 11px;
        }

        .pc-page-label {
            color: var(--dark);
            font-weight: 700;
        }

        .pc-page-id {
            color: var(--muted);
            font-size: 11px;
            margin-top: 3px;
        }

        .pc-type {
            display: inline-flex;
            align-items: center;

            padding: 6px 9px;

            border-radius: 8px;

            color: #475569;
            background: #f1f5f9;

            font-family: monospace;
            font-size: 11px;
            font-weight: 700;
        }

        .pc-bg {
            display: inline-flex;
            align-items: center;
            gap: 6px;

            padding: 6px 9px;

            border-radius: 8px;

            color: #475569;
            background: #f8fafc;

            font-size: 11px;
            font-weight: 700;
        }

        .pc-status {
            display: inline-flex;
            align-items: center;
            gap: 6px;

            padding: 6px 9px;

            border-radius: 999px;

            font-size: 11px;
            font-weight: 800;
        }

        .pc-status.active {
            color: #166534;
            background: #dcfce7;
        }

        .pc-status.inactive {
            color: #991b1b;
            background: #fee2e2;
        }

        .pc-dot {
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: currentColor;
        }

        .pc-actions {
            display: flex;
            align-items: center;
            gap: 7px;
        }

        .pc-icon-btn {
            width: 35px;
            height: 35px;

            display: grid;
            place-items: center;

            border: 1px solid var(--border);
            border-radius: 9px;

            background: #fff;
            color: #64748b;

            cursor: pointer;

            transition: .2s ease;
        }

        .pc-icon-btn:hover {
            color: var(--primary);
            border-color: #99f6e4;
            background: #f0fdfa;
        }

        .pc-icon-btn.danger:hover {
            color: var(--red);
            border-color: #fecaca;
            background: var(--red-soft);
        }

        /* ------------------------------------------------
           FORM GRID
        ------------------------------------------------ */

        .pc-form-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 18px;
        }

        .pc-form-grid .full {
            grid-column: 1 / -1;
        }

        .pc-form-section {
            margin-top: 24px;
            padding-top: 22px;

            border-top: 1px solid var(--border);
        }

        .pc-form-section:first-child {
            margin-top: 0;
            padding-top: 0;
            border-top: 0;
        }

        .pc-form-section-title {
            display: flex;
            align-items: center;
            gap: 9px;

            margin-bottom: 16px;

            color: var(--dark);
            font-size: 13px;
            font-weight: 800;
        }

        .pc-form-section-title i {
            color: var(--primary);
        }

        .pc-help {
            margin-top: 6px;

            color: var(--muted);
            font-size: 11px;
            line-height: 1.5;
        }

        .pc-form-footer {
            margin-top: 24px;
            padding-top: 20px;

            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 15px;

            border-top: 1px solid var(--border);
        }

        .pc-form-actions {
            display: flex;
            gap: 9px;
        }

        /* ------------------------------------------------
           SWITCH
        ------------------------------------------------ */

        .pc-switch-row {
            height: 43px;

            display: flex;
            align-items: center;
            justify-content: space-between;

            padding: 0 12px;

            border: 1px solid #dbe3ec;
            border-radius: 11px;

            background: #fff;
        }

        .pc-switch-label {
            color: #334155;
            font-weight: 700;
        }

        .pc-switch {
            position: relative;

            width: 42px;
            height: 23px;
        }

        .pc-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .pc-slider {
            position: absolute;
            inset: 0;

            border-radius: 999px;

            background: #cbd5e1;

            cursor: pointer;

            transition: .2s ease;
        }

        .pc-slider::before {
            content: "";

            position: absolute;

            width: 17px;
            height: 17px;

            left: 3px;
            top: 3px;

            border-radius: 50%;

            background: #fff;

            box-shadow: 0 1px 3px rgba(0,0,0,.2);

            transition: .2s ease;
        }

        .pc-switch input:checked + .pc-slider {
            background: var(--primary);
        }

        .pc-switch input:checked + .pc-slider::before {
            transform: translateX(19px);
        }

        /* ------------------------------------------------
           CODE AREAS
        ------------------------------------------------ */

        .pc-code {
            font-family:
                "SFMono-Regular",
                Consolas,
                "Liberation Mono",
                monospace;

            font-size: 12px;
            line-height: 1.65;

            background: #0f172a;
            color: #e2e8f0;

            border-color: #1e293b;
        }

        .pc-code:focus {
            border-color: #2dd4bf;
            box-shadow:
                0 0 0 4px rgba(45,212,191,.1);
        }

        /* ------------------------------------------------
           EMPTY
        ------------------------------------------------ */

        .pc-empty {
            padding: 60px 25px;

            text-align: center;
        }

        .pc-empty-icon {
            width: 64px;
            height: 64px;

            margin: 0 auto 15px;

            display: grid;
            place-items: center;

            border-radius: 18px;

            color: var(--primary);
            background: var(--primary-soft);

            font-size: 24px;
        }

        .pc-empty h3 {
            margin: 0 0 7px;

            color: var(--dark);
            font-size: 16px;
        }

        .pc-empty p {
            max-width: 500px;
            margin: 0 auto;

            color: var(--muted);
            line-height: 1.6;
        }

        /* ------------------------------------------------
           RESPONSIVE
        ------------------------------------------------ */

        @media (max-width: 1200px) {

            .pc-stats {
                grid-template-columns: repeat(2, 1fr);
            }

            .pc-filters {
                grid-template-columns: repeat(2, 1fr);
            }

            .pc-filter-actions {
                grid-column: 1 / -1;
            }
        }

        @media (max-width: 1100px) {

            .pc-topbar,
            .pc-main {
                margin-left: 0;
            }

            .pc-main {
                padding: 22px;
            }
        }

        @media (max-width: 760px) {

            .pc-topbar {
                min-height: auto;
                padding: 13px 16px;
            }

            .pc-top-title p {
                display: none;
            }

            .pc-top-actions .pc-top-link span {
                display: none;
            }

            .pc-top-link {
                width: 42px;
                padding: 0;
                justify-content: center;
            }

            .pc-main {
                padding: 15px;
            }

            .pc-hero {
                padding: 23px;
                border-radius: 19px;
            }

            .pc-hero-inner {
                align-items: flex-start;
                flex-direction: column;
            }

            .pc-hero h2 {
                font-size: 23px;
            }

            .pc-stats {
                grid-template-columns: 1fr 1fr;
                gap: 10px;
            }

            .pc-stat {
                padding: 15px;
            }

            .pc-stat-value {
                font-size: 19px;
            }

            .pc-stat-icon {
                width: 42px;
                height: 42px;
            }

            .pc-filters {
                grid-template-columns: 1fr;
            }

            .pc-filter-actions {
                grid-column: auto;
            }

            .pc-form-grid {
                grid-template-columns: 1fr;
            }

            .pc-form-grid .full {
                grid-column: auto;
            }

            .pc-card-head,
            .pc-card-body {
                padding: 17px;
            }

            .pc-form-footer {
                align-items: stretch;
                flex-direction: column;
            }

            .pc-form-actions {
                width: 100%;
            }

            .pc-form-actions .pc-btn {
                flex: 1;
            }
        }

        @media (max-width: 480px) {

            .pc-stats {
                grid-template-columns: 1fr;
            }

            .pc-top-title h1 {
                font-size: 15px;
            }

            .pc-top-icon {
                width: 39px;
                height: 39px;
            }
        }

    </style>
</head>

<body>

<?php
/*
|--------------------------------------------------------------------------
| Existing sidebar - separately included
|--------------------------------------------------------------------------
*/
require_once __DIR__ . '/sidebar.php';
?>

<!-- =====================================================
     TOPBAR
===================================================== -->

<header class="pc-topbar">

    <div class="pc-top-title">

        <div class="pc-top-icon">
            <i class="fa-solid fa-layer-group"></i>
        </div>

        <div>
            <h1>Page Sections</h1>
            <p>Manage dynamic page sections</p>
        </div>

    </div>

    <div class="pc-top-actions">

        <a
            href="pages.php"
            class="pc-top-link"
        >
            <i class="fa-solid fa-file-lines"></i>
            <span>Pages</span>
        </a>

        <a
            href="sections.php"
            class="pc-top-link"
        >
            <i class="fa-solid fa-rotate"></i>
            <span>Refresh</span>
        </a>

    </div>

</header>

<!-- =====================================================
     MAIN
===================================================== -->

<main class="pc-main">

    <div class="pc-container">

        <!-- HERO -->

        <section class="pc-hero">

            <div class="pc-hero-inner">

                <div>

                    <h2>
                        Page Sections
                    </h2>

                    <p>
                        Build and manage individual page sections
                        using your existing <strong>page_sections</strong>
                        table. Control content, backgrounds, order,
                        status and custom styling from one place.
                    </p>

                </div>

                <a
                    href="sections.php#section-editor"
                    class="pc-hero-btn"
                >
                    <i class="fa-solid fa-plus"></i>
                    Add Section
                </a>

            </div>

        </section>

        <!-- FLASH -->

        <?php if ($flash): ?>

            <div
                class="pc-alert <?= $flash['type'] === 'success' ? 'success' : 'error' ?>"
            >

                <i class="fa-solid <?= $flash['type'] === 'success'
                    ? 'fa-circle-check'
                    : 'fa-circle-exclamation' ?>"></i>

                <span>
                    <?= pc_e($flash['message']) ?>
                </span>

            </div>

        <?php endif; ?>

        <!-- STATS -->

        <section class="pc-stats">

            <div class="pc-stat">

                <div class="pc-stat-icon">
                    <i class="fa-solid fa-layer-group"></i>
                </div>

                <div>
                    <div class="pc-stat-label">
                        Total Sections
                    </div>

                    <div class="pc-stat-value">
                        <?= number_format($totalSections) ?>
                    </div>
                </div>

            </div>

            <div class="pc-stat">

                <div class="pc-stat-icon">
                    <i class="fa-solid fa-file-lines"></i>
                </div>

                <div>
                    <div class="pc-stat-label">
                        Available Pages
                    </div>

                    <div class="pc-stat-value">
                        <?= number_format($totalPages) ?>
                    </div>
                </div>

            </div>

            <div class="pc-stat">

                <div class="pc-stat-icon">
                    <i class="fa-solid fa-circle-check"></i>
                </div>

                <div>
                    <div class="pc-stat-label">
                        Active
                    </div>

                    <div class="pc-stat-value">
                        <?= number_format($activeSections) ?>
                    </div>
                </div>

            </div>

            <div class="pc-stat">

                <div class="pc-stat-icon">
                    <i class="fa-solid fa-circle-pause"></i>
                </div>

                <div>
                    <div class="pc-stat-label">
                        Inactive
                    </div>

                    <div class="pc-stat-value">
                        <?= number_format($inactiveSections) ?>
                    </div>
                </div>

            </div>

        </section>

        <!-- FILTER CARD -->

        <section class="pc-card">

            <div class="pc-card-head">

                <div>
                    <h3>
                        Filter Sections
                    </h3>

                    <p>
                        Quickly find sections by page, status or keyword.
                    </p>
                </div>

            </div>

            <div class="pc-card-body">

                <form
                    method="get"
                    action="sections.php"
                >

                    <div class="pc-filters">

                        <div class="pc-field">

                            <label for="page_id">
                                Page
                            </label>

                            <select
                                name="page_id"
                                id="page_id"
                                class="pc-select"
                            >

                                <option value="">
                                    All Pages
                                </option>

                                <?php foreach ($pages as $page): ?>

                                    <option
                                        value="<?= (int)$page['id'] ?>"
                                        <?= (int)$selectedPage === (int)$page['id']
                                            ? 'selected'
                                            : '' ?>
                                    >
                                        <?= pc_e($page['title']) ?>
                                        <?php if (!empty($page['slug'])): ?>
                                            — <?= pc_e($page['slug']) ?>
                                        <?php endif; ?>
                                    </option>

                                <?php endforeach; ?>

                            </select>

                        </div>

                        <div class="pc-field">

                            <label for="search">
                                Search
                            </label>

                            <input
                                type="text"
                                name="search"
                                id="search"
                                class="pc-input"
                                value="<?= pc_e($search) ?>"
                                placeholder="Title, key or section type..."
                            >

                        </div>

                        <div class="pc-field">

                            <label for="status">
                                Status
                            </label>

                            <select
                                name="status"
                                id="status"
                                class="pc-select"
                            >

                                <option value="">
                                    All Status
                                </option>

                                <option
                                    value="1"
                                    <?= $statusFilter === '1'
                                        ? 'selected'
                                        : '' ?>
                                >
                                    Active
                                </option>

                                <option
                                    value="0"
                                    <?= $statusFilter === '0'
                                        ? 'selected'
                                        : '' ?>
                                >
                                    Inactive
                                </option>

                            </select>

                        </div>

                        <div class="pc-filter-actions">

                            <button
                                type="submit"
                                class="pc-btn pc-btn-primary"
                            >
                                <i class="fa-solid fa-filter"></i>
                                Apply
                            </button>

                            <a
                                href="sections.php"
                                class="pc-btn pc-btn-light"
                            >
                                <i class="fa-solid fa-rotate-left"></i>
                                Reset
                            </a>

                        </div>

                    </div>

                </form>

            </div>

        </section>

        <!-- SECTION LIST -->

        <section class="pc-card">

            <div class="pc-card-head">

                <div>
                    <h3>
                        Sections List
                    </h3>

                    <p>
                        <?= number_format($totalSections) ?>
                        section(s) found.
                    </p>
                </div>

                <a
                    href="sections.php#section-editor"
                    class="pc-btn pc-btn-primary pc-btn-small"
                >
                    <i class="fa-solid fa-plus"></i>
                    New Section
                </a>

            </div>

            <?php if (empty($sections)): ?>

                <div class="pc-empty">

                    <div class="pc-empty-icon">
                        <i class="fa-solid fa-layer-group"></i>
                    </div>

                    <h3>
                        No sections found
                    </h3>

                    <p>
                        Is page ke liye abhi koi section available nahi hai.
                        New Section button se section create karein.
                    </p>

                </div>

            <?php else: ?>

                <div class="pc-table-wrap">

                    <table class="pc-table">

                        <thead>

                            <tr>

                                <th>
                                    Section
                                </th>

                                <th>
                                    Page
                                </th>

                                <th>
                                    Type
                                </th>

                                <th>
                                    Background
                                </th>

                                <th>
                                    Order
                                </th>

                                <th>
                                    Status
                                </th>

                                <th>
                                    Updated
                                </th>

                                <th>
                                    Actions
                                </th>

                            </tr>

                        </thead>

                        <tbody>

                        <?php foreach ($sections as $section): ?>

                            <tr>

                                <td>

                                    <div class="pc-section-name">

                                        <div class="pc-section-icon">
                                            <i class="fa-solid fa-cubes"></i>
                                        </div>

                                        <div>

                                            <div class="pc-section-title">

                                                <?= pc_e(
                                                    $section['title']
                                                    ?: ($section['section_type'] ?: 'Untitled Section')
                                                ) ?>

                                            </div>

                                            <?php if (!empty($section['section_key'])): ?>

                                                <div class="pc-section-key">
                                                    <?= pc_e($section['section_key']) ?>
                                                </div>

                                            <?php endif; ?>

                                        </div>

                                    </div>

                                </td>

                                <td>

                                    <div class="pc-page-label">

                                        <?php if (!empty($section['page_title'])): ?>

                                            <?= pc_e($section['page_title']) ?>

                                        <?php else: ?>

                                            <?= pc_e(
                                                pc_page_name(
                                                    $section['page_id'],
                                                    $pages
                                                )
                                            ) ?>

                                        <?php endif; ?>

                                    </div>

                                    <div class="pc-page-id">
                                        ID #<?= (int)$section['page_id'] ?>
                                    </div>

                                </td>

                                <td>

                                    <span class="pc-type">
                                        <?= pc_e($section['section_type']) ?>
                                    </span>

                                </td>

                                <td>

                                    <span class="pc-bg">

                                        <?php
                                        $bgIcon = 'fa-ban';

                                        if ($section['background_type'] === 'color') {
                                            $bgIcon = 'fa-palette';
                                        } elseif ($section['background_type'] === 'image') {
                                            $bgIcon = 'fa-image';
                                        } elseif ($section['background_type'] === 'video') {
                                            $bgIcon = 'fa-video';
                                        }
                                        ?>

                                        <i class="fa-solid <?= $bgIcon ?>"></i>

                                        <?= pc_e(
                                            ucfirst(
                                                $section['background_type']
                                            )
                                        ) ?>

                                    </span>

                                </td>

                                <td>

                                    <form
                                        method="post"
                                        style="display:flex;gap:6px;align-items:center;"
                                    >

                                        <?= pc_csrf_field() ?>

                                        <input
                                            type="hidden"
                                            name="action"
                                            value="quick_sort"
                                        >

                                        <input
                                            type="hidden"
                                            name="id"
                                            value="<?= (int)$section['id'] ?>"
                                        >

                                        <input
                                            type="hidden"
                                            name="redirect_page"
                                            value="<?= (int)$section['page_id'] ?>"
                                        >

                                        <input
                                            type="number"
                                            name="sort_order"
                                            value="<?= (int)$section['sort_order'] ?>"
                                            class="pc-input"
                                            style="width:75px;height:34px;padding:0 8px;"
                                            title="Sort order"
                                        >

                                        <button
                                            type="submit"
                                            class="pc-icon-btn"
                                            title="Save order"
                                        >
                                            <i class="fa-solid fa-check"></i>
                                        </button>

                                    </form>

                                </td>

                                <td>

                                    <?php if ((int)$section['status'] === 1): ?>

                                        <span class="pc-status active">
                                            <span class="pc-dot"></span>
                                            Active
                                        </span>

                                    <?php else: ?>

                                        <span class="pc-status inactive">
                                            <span class="pc-dot"></span>
                                            Inactive
                                        </span>

                                    <?php endif; ?>

                                </td>

                                <td>

                                    <span style="color:#64748b;font-size:12px;">
                                        <?= !empty($section['updated_at'])
                                            ? pc_e(
                                                date(
                                                    'd M Y, h:i A',
                                                    strtotime($section['updated_at'])
                                                )
                                            )
                                            : '—' ?>
                                    </span>

                                </td>

                                <td>

                                    <div class="pc-actions">

                                        <!-- EDIT -->

                                        <a
                                            href="sections.php?edit=<?= (int)$section['id'] ?>"
                                            class="pc-icon-btn"
                                            title="Edit section"
                                        >
                                            <i class="fa-solid fa-pen"></i>
                                        </a>

                                        <!-- STATUS -->

                                        <form
                                            method="post"
                                            onsubmit="return confirm('Section status change karna hai?');"
                                        >

                                            <?= pc_csrf_field() ?>

                                            <input
                                                type="hidden"
                                                name="action"
                                                value="toggle_status"
                                            >

                                            <input
                                                type="hidden"
                                                name="id"
                                                value="<?= (int)$section['id'] ?>"
                                            >

                                            <input
                                                type="hidden"
                                                name="redirect_page"
                                                value="<?= (int)$section['page_id'] ?>"
                                            >

                                            <button
                                                type="submit"
                                                class="pc-icon-btn"
                                                title="Toggle status"
                                            >
                                                <i class="fa-solid fa-power-off"></i>
                                            </button>

                                        </form>

                                        <!-- DELETE -->

                                        <form
                                            method="post"
                                            onsubmit="return confirm('Ye section permanently delete ho jayega. Continue?');"
                                        >

                                            <?= pc_csrf_field() ?>

                                            <input
                                                type="hidden"
                                                name="action"
                                                value="delete"
                                            >

                                            <input
                                                type="hidden"
                                                name="id"
                                                value="<?= (int)$section['id'] ?>"
                                            >

                                            <input
                                                type="hidden"
                                                name="redirect_page"
                                                value="<?= (int)$section['page_id'] ?>"
                                            >

                                            <button
                                                type="submit"
                                                class="pc-icon-btn danger"
                                                title="Delete section"
                                            >
                                                <i class="fa-solid fa-trash"></i>
                                            </button>

                                        </form>

                                    </div>

                                </td>

                            </tr>

                        <?php endforeach; ?>

                        </tbody>

                    </table>

                </div>

            <?php endif; ?>

        </section>

        <!-- =================================================
             ADD / EDIT FORM
        ================================================== -->

        <section
            class="pc-card"
            id="section-editor"
        >

            <div class="pc-card-head">

                <div>

                    <h3>

                        <?php if ((int)$form['id'] > 0): ?>

                            Edit Section #<?= (int)$form['id'] ?>

                        <?php else: ?>

                            Create New Section

                        <?php endif; ?>

                    </h3>

                    <p>
                        Existing <strong>page_sections</strong>
                        table me section data save hoga.
                    </p>

                </div>

                <?php if ((int)$form['id'] > 0): ?>

                    <a
                        href="sections.php"
                        class="pc-btn pc-btn-light pc-btn-small"
                    >
                        <i class="fa-solid fa-plus"></i>
                        New
                    </a>

                <?php endif; ?>

            </div>

            <div class="pc-card-body">

                <form
                    method="post"
                    action="sections.php<?= (int)$form['id'] > 0
                        ? '?edit=' . (int)$form['id']
                        : '' ?>"
                >

                    <?= pc_csrf_field() ?>

                    <input
                        type="hidden"
                        name="action"
                        value="save"
                    >

                    <input
                        type="hidden"
                        name="id"
                        value="<?= (int)$form['id'] ?>"
                    >

                    <!-- BASIC -->

                    <div class="pc-form-section">

                        <div class="pc-form-section-title">
                            <i class="fa-solid fa-sliders"></i>
                            Basic Section Information
                        </div>

                        <div class="pc-form-grid">

                            <div class="pc-field">

                                <label for="form_page_id">
                                    Page <span style="color:#dc2626;">*</span>
                                </label>

                                <select
                                    name="page_id"
                                    id="form_page_id"
                                    class="pc-select"
                                    required
                                >

                                    <option value="">
                                        Select Page
                                    </option>

                                    <?php foreach ($pages as $page): ?>

                                        <option
                                            value="<?= (int)$page['id'] ?>"
                                            <?= (int)$form['page_id'] === (int)$page['id']
                                                ? 'selected'
                                                : '' ?>
                                        >
                                            <?= pc_e($page['title']) ?>

                                            <?php if (!empty($page['slug'])): ?>
                                                — <?= pc_e($page['slug']) ?>
                                            <?php endif; ?>

                                        </option>

                                    <?php endforeach; ?>

                                </select>

                                <div class="pc-help">
                                    Section kis existing page par render hoga.
                                </div>

                            </div>

                            <div class="pc-field">

                                <label for="section_type">
                                    Section Type
                                    <span style="color:#dc2626;">*</span>
                                </label>

                                <input
                                    type="text"
                                    name="section_type"
                                    id="section_type"
                                    class="pc-input"
                                    value="<?= pc_e($form['section_type']) ?>"
                                    placeholder="hero, content, products, gallery..."
                                    required
                                >

                                <div class="pc-help">
                                    Frontend renderer ke according type define karein.
                                </div>

                            </div>

                            <div class="pc-field">

                                <label for="section_key">
                                    Section Key
                                </label>

                                <input
                                    type="text"
                                    name="section_key"
                                    id="section_key"
                                    class="pc-input"
                                    value="<?= pc_e($form['section_key']) ?>"
                                    maxlength="150"
                                    placeholder="home_hero"
                                >

                                <div class="pc-help">
                                    Optional internal identifier.
                                </div>

                            </div>

                            <div class="pc-field">

                                <label for="sort_order">
                                    Sort Order
                                </label>

                                <input
                                    type="number"
                                    name="sort_order"
                                    id="sort_order"
                                    class="pc-input"
                                    value="<?= (int)$form['sort_order'] ?>"
                                    min="0"
                                >

                                <div class="pc-help">
                                    Lower number = section earlier on page.
                                </div>

                            </div>

                            <div class="pc-field full">

                                <label for="title">
                                    Section Title
                                </label>

                                <input
                                    type="text"
                                    name="title"
                                    id="title"
                                    class="pc-input"
                                    value="<?= pc_e($form['title']) ?>"
                                    maxlength="255"
                                    placeholder="Section title"
                                >

                            </div>

                            <div class="pc-field full">

                                <label for="subtitle">
                                    Subtitle
                                </label>

                                <input
                                    type="text"
                                    name="subtitle"
                                    id="subtitle"
                                    class="pc-input"
                                    value="<?= pc_e($form['subtitle']) ?>"
                                    maxlength="500"
                                    placeholder="Optional supporting text"
                                >

                            </div>

                        </div>

                    </div>

                    <!-- CONTENT -->

                    <div class="pc-form-section">

                        <div class="pc-form-section-title">
                            <i class="fa-solid fa-align-left"></i>
                            Section Content
                        </div>

                        <div class="pc-form-grid">

                            <div class="pc-field full">

                                <label for="content">
                                    Content
                                </label>

                                <textarea
                                    name="content"
                                    id="content"
                                    class="pc-textarea"
                                    rows="9"
                                    placeholder="Section HTML/content..."
                                ><?= pc_e($form['content']) ?></textarea>

                                <div class="pc-help">
                                    Existing <code>content</code> column me save hoga.
                                </div>

                            </div>

                            <div class="pc-field full">

                                <label for="settings">
                                    Section Settings
                                </label>

                                <textarea
                                    name="settings"
                                    id="settings"
                                    class="pc-textarea pc-code"
                                    rows="8"
                                    placeholder='Optional section configuration...'
                                ><?= pc_e($form['settings']) ?></textarea>

                                <div class="pc-help">
                                    Ye field database ke existing
                                    <code>settings</code> longtext column ke liye hai.
                                </div>

                            </div>

                        </div>

                    </div>

                    <!-- BACKGROUND -->

                    <div class="pc-form-section">

                        <div class="pc-form-section-title">
                            <i class="fa-solid fa-image"></i>
                            Background
                        </div>

                        <div class="pc-form-grid">

                            <div class="pc-field">

                                <label for="background_type">
                                    Background Type
                                </label>

                                <select
                                    name="background_type"
                                    id="background_type"
                                    class="pc-select"
                                >

                                    <option
                                        value="none"
                                        <?= $form['background_type'] === 'none'
                                            ? 'selected'
                                            : '' ?>
                                    >
                                        None
                                    </option>

                                    <option
                                        value="color"
                                        <?= $form['background_type'] === 'color'
                                            ? 'selected'
                                            : '' ?>
                                    >
                                        Color
                                    </option>

                                    <option
                                        value="image"
                                        <?= $form['background_type'] === 'image'
                                            ? 'selected'
                                            : '' ?>
                                    >
                                        Image
                                    </option>

                                    <option
                                        value="video"
                                        <?= $form['background_type'] === 'video'
                                            ? 'selected'
                                            : '' ?>
                                    >
                                        Video
                                    </option>

                                </select>

                            </div>

                            <div class="pc-field">

                                <label for="background_value">
                                    Background Value
                                </label>

                                <input
                                    type="text"
                                    name="background_value"
                                    id="background_value"
                                    class="pc-input"
                                    value="<?= pc_e($form['background_value']) ?>"
                                    maxlength="1000"
                                    placeholder="Color value, image URL/path, video URL..."
                                >

                                <div class="pc-help">
                                    Existing <code>background_value</code> column.
                                </div>

                            </div>

                        </div>

                    </div>

                    <!-- CUSTOM CODE -->

                    <div class="pc-form-section">

                        <div class="pc-form-section-title">
                            <i class="fa-solid fa-code"></i>
                            Custom Code
                        </div>

                        <div class="pc-form-grid">

                            <div class="pc-field">

                                <label for="custom_css">
                                    Custom CSS
                                </label>

                                <textarea
                                    name="custom_css"
                                    id="custom_css"
                                    class="pc-textarea pc-code"
                                    rows="12"
                                    placeholder=".section-custom { ... }"
                                ><?= pc_e($form['custom_css']) ?></textarea>

                            </div>

                            <div class="pc-field">

                                <label for="custom_js">
                                    Custom JavaScript
                                </label>

                                <textarea
                                    name="custom_js"
                                    id="custom_js"
                                    class="pc-textarea pc-code"
                                    rows="12"
                                    placeholder="document.addEventListener('DOMContentLoaded', function(){ ... });"
                                ><?= pc_e($form['custom_js']) ?></textarea>

                            </div>

                        </div>

                        <div class="pc-help" style="margin-top:12px;">
                            Custom JS admin listing me execute nahi kiya ja raha hai.
                            Ye sirf database me existing <code>custom_js</code>
                            column me save hota hai.
                        </div>

                    </div>

                    <!-- STATUS -->

                    <div class="pc-form-section">

                        <div class="pc-form-section-title">
                            <i class="fa-solid fa-toggle-on"></i>
                            Publishing
                        </div>

                        <div class="pc-form-grid">

                            <div class="pc-field">

                                <label>
                                    Section Status
                                </label>

                                <div class="pc-switch-row">

                                    <span class="pc-switch-label">
                                        Publish Section
                                    </span>

                                    <label class="pc-switch">

                                        <input
                                            type="checkbox"
                                            name="status"
                                            value="1"
                                            <?= (int)$form['status'] === 1
                                                ? 'checked'
                                                : '' ?>
                                        >

                                        <span class="pc-slider"></span>

                                    </label>

                                </div>

                            </div>

                        </div>

                    </div>

                    <!-- FOOTER -->

                    <div class="pc-form-footer">

                        <div
                            style="
                                color:#64748b;
                                font-size:12px;
                            "
                        >

                            <?php if ((int)$form['id'] > 0): ?>

                                Editing section
                                <strong>#<?= (int)$form['id'] ?></strong>

                            <?php else: ?>

                                New section will be added to
                                <strong>page_sections</strong>.

                            <?php endif; ?>

                        </div>

                        <div class="pc-form-actions">

                            <?php if ((int)$form['id'] > 0): ?>

                                <a
                                    href="sections.php"
                                    class="pc-btn pc-btn-light"
                                >
                                    Cancel
                                </a>

                            <?php endif; ?>

                            <button
                                type="submit"
                                class="pc-btn pc-btn-primary"
                            >

                                <i class="fa-solid fa-floppy-disk"></i>

                                <?php if ((int)$form['id'] > 0): ?>

                                    Update Section

                                <?php else: ?>

                                    Save Section

                                <?php endif; ?>

                            </button>

                        </div>

                    </div>

                </form>

            </div>

        </section>

    </div>

</main>

<script>

document.addEventListener('DOMContentLoaded', function () {

    /*
     * Automatically scroll to editor when editing.
     */
    const urlParams = new URLSearchParams(window.location.search);

    if (urlParams.has('edit')) {

        const editor = document.getElementById('section-editor');

        if (editor) {

            setTimeout(function () {

                editor.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });

            }, 150);

        }

    }

    /*
     * Background field helper.
     */
    const backgroundType =
        document.getElementById('background_type');

    const backgroundValue =
        document.getElementById('background_value');

    function updateBackgroundPlaceholder() {

        if (!backgroundType || !backgroundValue) {
            return;
        }

        const type = backgroundType.value;

        if (type === 'color') {

            backgroundValue.placeholder =
                '#f8fafc or rgba(15,118,110,.08)';

        } else if (type === 'image') {

            backgroundValue.placeholder =
                '/uploads/sections/hero.webp';

        } else if (type === 'video') {

            backgroundValue.placeholder =
                '/uploads/sections/background.mp4';

        } else {

            backgroundValue.placeholder =
                'No background value required';

        }
    }

    if (backgroundType) {

        backgroundType.addEventListener(
            'change',
            updateBackgroundPlaceholder
        );

        updateBackgroundPlaceholder();
    }

});

</script>

</body>
</html>