<?php
// ============================================================
//  admin_design.php — لوحة تحكم التصميم الكاملة
// ============================================================

require_once __DIR__ . '/../db.php';

$msg = '';
$msg_type = '';

// ============================================================
//  معالجة الحفظ
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // --- حفظ design_settings ---
    if ($action === 'save_settings') {
        try {
            $stmt = $pdo->prepare("UPDATE design_settings SET setting_value=? WHERE setting_key=?");
            foreach ($_POST['settings'] as $key => $val) {
                $stmt->execute([trim($val), $key]);
            }
            $msg = '✅ تم حفظ الإعدادات بنجاح!';
            $msg_type = 'success';
        } catch (Exception $e) {
            $msg = '❌ خطأ: ' . $e->getMessage();
            $msg_type = 'error';
        }
    }

    // --- حفظ button_settings ---
    if ($action === 'save_buttons') {
        try {
            $stmt = $pdo->prepare("UPDATE button_settings SET
                background_color=?, text_color=?, hover_background=?, border_radius=?,
                padding_vertical=?, padding_horizontal=?, font_size=?, font_weight=?,
                box_shadow=?, animation_type=?, is_glow_enabled=?, glow_color=?,
                button_text=?, icon_class=?
                WHERE button_type=?");
            foreach ($_POST['buttons'] as $type => $b) {
                $stmt->execute([
                    $b['background_color'] ?? '#1E40AF',
                    $b['text_color']       ?? '#ffffff',
                    $b['hover_background'] ?? '#1E3A8A',
                    $b['border_radius']    ?? '8px',
                    $b['padding_vertical'] ?? '12px',
                    $b['padding_horizontal'] ?? '20px',
                    $b['font_size']        ?? '15px',
                    $b['font_weight']      ?? '700',
                    $b['box_shadow']       ?? '',
                    $b['animation_type']   ?? 'none',
                    isset($b['is_glow_enabled']) ? 1 : 0,
                    $b['glow_color']       ?? '#1E40AF',
                    $b['button_text']      ?? '',
                    $b['icon_class']       ?? '',
                    $type
                ]);
            }
            $msg = '✅ تم حفظ إعدادات الأزرار!';
            $msg_type = 'success';
        } catch (Exception $e) {
            $msg = '❌ خطأ: ' . $e->getMessage();
            $msg_type = 'error';
        }
    }

    // --- حفظ page_sections ---
    if ($action === 'save_sections') {
        try {
            $stmtV = $pdo->prepare("UPDATE page_sections SET is_visible=0 WHERE page=?");
            $stmtV->execute([$_POST['page_target']]);
            $stmtU = $pdo->prepare("UPDATE page_sections SET is_visible=?, position=? WHERE page=? AND section_key=?");
            foreach ($_POST['sections'] as $key => $s) {
                $stmtU->execute([
                    isset($s['visible']) ? 1 : 0,
                    (int)($s['position'] ?? 0),
                    $_POST['page_target'],
                    $key
                ]);
            }
            $msg = '✅ تم حفظ ترتيب الأقسام!';
            $msg_type = 'success';
        } catch (Exception $e) {
            $msg = '❌ خطأ: ' . $e->getMessage();
            $msg_type = 'error';
        }
    }

    // --- حفظ custom CSS ---
    if ($action === 'save_css') {
        try {
            $pdo->prepare("DELETE FROM custom_css WHERE page=?")->execute([$_POST['css_page']]);
            if (!empty($_POST['css_rules'])) {
                $stmt = $pdo->prepare("INSERT INTO custom_css (page,css_selector,css_property,css_value,priority,is_active,label) VALUES(?,?,?,?,?,1,?)");
                foreach ($_POST['css_rules'] as $rule) {
                    if (!empty($rule['selector']) && !empty($rule['property']) && !empty($rule['value'])) {
                        $stmt->execute([$_POST['css_page'], $rule['selector'], $rule['property'], $rule['value'], (int)($rule['priority']??0), $rule['label']??'']);
                    }
                }
            }
            $msg = '✅ تم حفظ CSS المخصص!';
            $msg_type = 'success';
        } catch (Exception $e) {
            $msg = '❌ خطأ: ' . $e->getMessage();
            $msg_type = 'error';
        }
    }

    // --- تطبيق قالب ---
    if ($action === 'apply_template') {
        try {
            $tpl = $pdo->prepare("SELECT settings FROM design_templates WHERE id=?")->execute([$_POST['template_id']]);
            $tpl = $pdo->prepare("SELECT settings FROM design_templates WHERE id=?");
            $tpl->execute([$_POST['template_id']]);
            $template = $tpl->fetch();
            if ($template) {
                $s = json_decode($template['settings'], true);
                $stmt = $pdo->prepare("UPDATE design_settings SET setting_value=? WHERE setting_key=?");
                foreach ($s as $k => $v) $stmt->execute([$v, $k]);
                $msg = '✅ تم تطبيق القالب!';
                $msg_type = 'success';
            }
        } catch (Exception $e) {
            $msg = '❌ خطأ: ' . $e->getMessage();
            $msg_type = 'error';
        }
    }

    // --- إضافة قالب جديد ---
    if ($action === 'save_template') {
        try {
            $allSettings = $pdo->query("SELECT setting_key, setting_value FROM design_settings")->fetchAll();
            $snap = [];
            foreach ($allSettings as $s) $snap[$s['setting_key']] = $s['setting_value'];
            $pdo->prepare("INSERT INTO design_templates (name,description,preview_color,settings,is_default) VALUES(?,?,?,?,0)")
                ->execute([$_POST['tpl_name'], $_POST['tpl_desc'], $_POST['tpl_color'], json_encode($snap, JSON_UNESCAPED_UNICODE)]);
            $msg = '✅ تم حفظ القالب الجديد!';
            $msg_type = 'success';
        } catch (Exception $e) {
            $msg = '❌ خطأ: ' . $e->getMessage();
            $msg_type = 'error';
        }
    }

    // --- حذف قالب ---
    if ($action === 'delete_template') {
        try {
            $pdo->prepare("DELETE FROM design_templates WHERE id=? AND is_default=0")->execute([$_POST['template_id']]);
            $msg = '✅ تم حذف القالب!';
            $msg_type = 'success';
        } catch (Exception $e) {
            $msg = '❌ ' . $e->getMessage();
            $msg_type = 'error';
        }
    }

    // --- إعادة تعيين القيم الافتراضية ---
    if ($action === 'reset_defaults') {
        try {
            $pdo->query("UPDATE design_settings SET setting_value = default_value");
            $msg = '✅ تم إعادة التعيين للقيم الافتراضية!';
            $msg_type = 'success';
        } catch (Exception $e) {
            $msg = '❌ ' . $e->getMessage();
            $msg_type = 'error';
        }
    }
}

// ============================================================
//  جلب البيانات
// ============================================================
$settings_raw = $pdo->query("SELECT * FROM design_settings ORDER BY category, id")->fetchAll();
$settings = [];
foreach ($settings_raw as $s) $settings[$s['setting_key']] = $s;

$buttons_raw = $pdo->query("SELECT * FROM button_settings ORDER BY id")->fetchAll();
$buttons = [];
foreach ($buttons_raw as $b) $buttons[$b['button_type']] = $b;

$sections_index = $pdo->query("SELECT * FROM page_sections WHERE page='index' ORDER BY position")->fetchAll();
$sections_det   = $pdo->query("SELECT * FROM page_sections WHERE page='det' ORDER BY position")->fetchAll();

$css_rules_all   = $pdo->query("SELECT * FROM custom_css WHERE page='all'   ORDER BY priority DESC")->fetchAll();
$css_rules_index = $pdo->query("SELECT * FROM custom_css WHERE page='index' ORDER BY priority DESC")->fetchAll();
$css_rules_det   = $pdo->query("SELECT * FROM custom_css WHERE page='det'   ORDER BY priority DESC")->fetchAll();

$templates = $pdo->query("SELECT * FROM design_templates ORDER BY is_default DESC, id ASC")->fetchAll();

// تجميع الإعدادات حسب الفئة
$settings_by_cat = [];
foreach ($settings_raw as $s) {
    $settings_by_cat[$s['category']][] = $s;
}

function sv($settings, $key, $default = '') {
    return isset($settings[$key]) ? htmlspecialchars($settings[$key]['setting_value'] ?? $default) : $default;
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>🎨 لوحة تحكم التصميم</title>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;700;800;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
<style>
/* =====================================================
   VARIABLES & RESET
===================================================== */
:root {
    --bg:       #0D1117;
    --bg2:      #161B22;
    --bg3:      #1C2128;
    --border:   #30363D;
    --border2:  #21262D;
    --p:        #2F81F7;
    --p-d:      #1A6BD0;
    --p-glow:   rgba(47,129,247,0.25);
    --accent:   #F78166;
    --success:  #3FB950;
    --warning:  #D29922;
    --text:     #E6EDF3;
    --text2:    #8B949E;
    --text3:    #484F58;
    --r:        12px;
    --r-sm:     8px;
    --tr:       all 0.2s cubic-bezier(0.4,0,0.2,1);
    --sh:       0 8px 32px rgba(0,0,0,0.4);
    --sh-p:     0 4px 16px rgba(47,129,247,0.3);
}
*,*::before,*::after { margin:0;padding:0;box-sizing:border-box; }
body {
    background: var(--bg);
    color: var(--text);
    font-family: 'Tajawal', sans-serif;
    font-size: 14px;
    line-height: 1.6;
    min-height: 100vh;
}
::-webkit-scrollbar { width:6px; height:6px; }
::-webkit-scrollbar-track { background: var(--bg2); }
::-webkit-scrollbar-thumb { background: var(--border); border-radius:10px; }
::-webkit-scrollbar-thumb:hover { background: var(--p); }
a { color:var(--p); text-decoration:none; }

/* =====================================================
   LAYOUT
===================================================== */
.layout { display:flex; min-height:100vh; }

/* SIDEBAR */
.sidebar {
    width: 260px;
    background: var(--bg2);
    border-left: 1px solid var(--border2);
    position: sticky;
    top: 0;
    height: 100vh;
    overflow-y: auto;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
}
.sidebar-logo {
    padding: 24px 20px 20px;
    border-bottom: 1px solid var(--border2);
}
.sidebar-logo h1 {
    font-size: 17px;
    font-weight: 900;
    color: var(--text);
    display: flex;
    align-items: center;
    gap: 10px;
}
.sidebar-logo span {
    background: linear-gradient(135deg,var(--p),#79C0FF);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}
.sidebar-logo p { font-size:12px; color:var(--text2); margin-top:4px; }

.nav-section { padding: 16px 12px 8px; }
.nav-section-label {
    font-size: 10px;
    font-weight: 800;
    color: var(--text3);
    text-transform: uppercase;
    letter-spacing: 1.5px;
    padding: 0 8px;
    margin-bottom: 6px;
}
.nav-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 12px;
    border-radius: var(--r-sm);
    color: var(--text2);
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    transition: var(--tr);
    border: none;
    background: none;
    width: 100%;
    text-align: right;
}
.nav-item:hover { background: var(--bg3); color: var(--text); }
.nav-item.active { background: rgba(47,129,247,0.15); color: var(--p); }
.nav-item i { width:18px; text-align:center; font-size:14px; }
.nav-badge {
    margin-right: auto;
    background: var(--p);
    color: white;
    font-size: 10px;
    font-weight: 800;
    padding: 2px 7px;
    border-radius: 10px;
}

.sidebar-footer {
    margin-top: auto;
    padding: 16px;
    border-top: 1px solid var(--border2);
    display: flex;
    flex-direction: column;
    gap: 8px;
}
.sidebar-footer a, .sidebar-footer button {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 9px 12px;
    border-radius: var(--r-sm);
    font-size: 13px;
    font-weight: 600;
    color: var(--text2);
    transition: var(--tr);
    border: 1px solid var(--border2);
    background: none;
    cursor: pointer;
    width: 100%;
    text-align: right;
    font-family: 'Tajawal', sans-serif;
}
.sidebar-footer a:hover { background:rgba(47,129,247,0.1); color:var(--p); border-color:var(--p); }
.sidebar-footer button:hover { background:rgba(239,68,68,0.1); color:#f87171; border-color:#f87171; }

/* MAIN */
.main {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-width: 0;
}

/* TOPBAR */
.topbar {
    background: var(--bg2);
    border-bottom: 1px solid var(--border2);
    padding: 0 28px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: sticky;
    top: 0;
    z-index: 100;
}
.topbar-title { font-size:16px; font-weight:800; color:var(--text); }
.topbar-title span { color:var(--p); }
.topbar-actions { display:flex; gap:10px; align-items:center; }
.btn-preview {
    display: inline-flex;
    align-items: center;
    gap: 7px;
    background: rgba(47,129,247,0.1);
    color: var(--p);
    border: 1px solid rgba(47,129,247,0.3);
    padding: 8px 16px;
    border-radius: var(--r-sm);
    font-size: 13px;
    font-weight: 700;
    cursor: pointer;
    transition: var(--tr);
    font-family: 'Tajawal', sans-serif;
    text-decoration: none;
}
.btn-preview:hover { background: rgba(47,129,247,0.2); border-color:var(--p); }

/* CONTENT */
.content { padding: 28px; flex: 1; }

/* TAB PANELS */
.tab-panel { display: none; animation: fadeIn .25s ease; }
.tab-panel.active { display: block; }
@keyframes fadeIn { from{opacity:0;transform:translateY(8px)} to{opacity:1;transform:translateY(0)} }

/* TOAST */
.toast {
    position: fixed;
    top: 20px;
    left: 50%;
    transform: translateX(-50%) translateY(-80px);
    background: var(--bg3);
    border: 1px solid var(--border);
    padding: 14px 24px;
    border-radius: var(--r);
    font-size: 14px;
    font-weight: 700;
    display: flex;
    align-items: center;
    gap: 10px;
    box-shadow: var(--sh);
    z-index: 9999;
    transition: transform .35s cubic-bezier(0.34,1.56,0.64,1);
    white-space: nowrap;
}
.toast.show { transform: translateX(-50%) translateY(0); }
.toast.success { border-color:var(--success); color:var(--success); }
.toast.error   { border-color:var(--accent);  color:var(--accent); }

/* =====================================================
   CARDS & SECTIONS
===================================================== */
.card {
    background: var(--bg2);
    border: 1px solid var(--border2);
    border-radius: var(--r);
    overflow: hidden;
    margin-bottom: 20px;
}
.card-head {
    padding: 16px 20px;
    border-bottom: 1px solid var(--border2);
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
}
.card-head h3 {
    font-size: 14px;
    font-weight: 800;
    color: var(--text);
    display: flex;
    align-items: center;
    gap: 8px;
}
.card-head h3 i { color: var(--p); }
.card-body { padding: 20px; }

/* =====================================================
   FORM ELEMENTS
===================================================== */
.form-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 16px; }
.form-grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
.form-grid-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 16px; }

.field { display: flex; flex-direction: column; gap: 6px; }
.field label {
    font-size: 12px;
    font-weight: 700;
    color: var(--text2);
    text-transform: uppercase;
    letter-spacing: 0.5px;
}
.field input[type=text],
.field input[type=number],
.field textarea,
.field select {
    background: var(--bg3);
    border: 1px solid var(--border);
    border-radius: var(--r-sm);
    color: var(--text);
    padding: 10px 14px;
    font-size: 13px;
    font-family: 'Tajawal', sans-serif;
    transition: var(--tr);
    outline: none;
    width: 100%;
}
.field input[type=text]:focus,
.field input[type=number]:focus,
.field textarea:focus,
.field select:focus {
    border-color: var(--p);
    box-shadow: 0 0 0 3px var(--p-glow);
}
.field textarea { resize: vertical; min-height: 80px; }
.field select { cursor: pointer; }
.field select option { background: var(--bg3); }

/* COLOR FIELD */
.color-field { display: flex; align-items: center; gap: 8px; }
.color-field input[type=color] {
    width: 36px;
    height: 36px;
    border: 1px solid var(--border);
    border-radius: var(--r-sm);
    background: var(--bg3);
    padding: 2px;
    cursor: pointer;
    flex-shrink: 0;
}
.color-field input[type=text] {
    flex: 1;
    font-family: monospace;
    font-size: 13px;
}

/* TOGGLE */
.toggle-wrap { display: flex; align-items: center; gap: 10px; }
.toggle {
    position: relative;
    width: 42px;
    height: 22px;
    flex-shrink: 0;
}
.toggle input { opacity: 0; width: 0; height: 0; }
.toggle-slider {
    position: absolute;
    inset: 0;
    background: var(--border);
    border-radius: 11px;
    cursor: pointer;
    transition: var(--tr);
}
.toggle-slider::before {
    content: '';
    position: absolute;
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background: white;
    top: 3px;
    right: 3px;
    transition: var(--tr);
}
.toggle input:checked + .toggle-slider { background: var(--p); }
.toggle input:checked + .toggle-slider::before { transform: translateX(-20px); }
.toggle-label { font-size: 13px; font-weight: 600; color: var(--text2); }

/* BUTTONS */
.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 7px;
    padding: 10px 18px;
    border-radius: var(--r-sm);
    font-size: 13px;
    font-weight: 700;
    cursor: pointer;
    transition: var(--tr);
    border: none;
    font-family: 'Tajawal', sans-serif;
    white-space: nowrap;
}
.btn-primary { background: var(--p); color: white; }
.btn-primary:hover { background: var(--p-d); box-shadow: var(--sh-p); }
.btn-secondary { background: var(--bg3); color: var(--text2); border: 1px solid var(--border); }
.btn-secondary:hover { background: var(--border2); color: var(--text); }
.btn-danger { background: rgba(248,113,113,0.1); color: #f87171; border: 1px solid rgba(248,113,113,0.3); }
.btn-danger:hover { background: rgba(248,113,113,0.2); }
.btn-success { background: rgba(63,185,80,0.1); color: var(--success); border: 1px solid rgba(63,185,80,0.3); }
.btn-success:hover { background: rgba(63,185,80,0.2); }
.btn-sm { padding: 6px 12px; font-size: 12px; }
.btn-lg { padding: 13px 24px; font-size: 15px; }
.btn-full { width: 100%; }

/* SAVE BAR */
.save-bar {
    position: sticky;
    bottom: 0;
    background: var(--bg2);
    border-top: 1px solid var(--border2);
    padding: 14px 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    z-index: 50;
}
.save-bar-info { font-size: 12px; color: var(--text2); }

/* =====================================================
   CATEGORY TABS (داخل الإعدادات)
===================================================== */
.cat-tabs {
    display: flex;
    gap: 4px;
    padding: 4px;
    background: var(--bg3);
    border-radius: var(--r);
    margin-bottom: 20px;
    flex-wrap: wrap;
}
.cat-tab {
    padding: 8px 16px;
    border-radius: var(--r-sm);
    font-size: 13px;
    font-weight: 700;
    cursor: pointer;
    transition: var(--tr);
    color: var(--text2);
    border: none;
    background: none;
    font-family: 'Tajawal', sans-serif;
}
.cat-tab.active { background: var(--p); color: white; box-shadow: var(--sh-p); }
.cat-tab:hover:not(.active) { background: var(--border2); color: var(--text); }

.cat-panel { display: none; }
.cat-panel.active { display: block; }

/* =====================================================
   SECTIONS DRAG
===================================================== */
.sections-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
}
.section-item {
    display: flex;
    align-items: center;
    gap: 12px;
    background: var(--bg3);
    border: 1px solid var(--border2);
    border-radius: var(--r-sm);
    padding: 12px 16px;
    cursor: grab;
    transition: var(--tr);
    user-select: none;
}
.section-item:hover { border-color: var(--border); }
.section-item.dragging { opacity: 0.5; border-color: var(--p); }
.section-item.drag-over { border-color: var(--p); background: rgba(47,129,247,0.05); }
.drag-handle { color: var(--text3); font-size: 16px; cursor: grab; }
.section-name { flex: 1; font-size: 13px; font-weight: 700; color: var(--text); }
.section-key { font-size: 11px; color: var(--text3); font-family: monospace; margin-right: 8px; }
.section-pos { width: 60px; }
.section-pos input {
    width: 100%;
    background: var(--bg2);
    border: 1px solid var(--border);
    border-radius: 6px;
    color: var(--text);
    padding: 5px 8px;
    font-size: 12px;
    text-align: center;
    font-family: 'Tajawal', sans-serif;
}

/* =====================================================
   CSS EDITOR
===================================================== */
.css-rule {
    background: var(--bg3);
    border: 1px solid var(--border2);
    border-radius: var(--r-sm);
    padding: 14px 16px;
    margin-bottom: 10px;
    position: relative;
}
.css-rule-grid { display: grid; grid-template-columns: 1fr 1fr 1fr 60px; gap: 10px; align-items: end; }
.css-delete {
    background: rgba(248,113,113,0.1);
    color: #f87171;
    border: 1px solid rgba(248,113,113,0.2);
    width: 36px;
    height: 36px;
    border-radius: var(--r-sm);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: var(--tr);
    font-size: 14px;
}
.css-delete:hover { background: rgba(248,113,113,0.2); }

/* =====================================================
   TEMPLATES
===================================================== */
.templates-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 14px;
}
.template-card {
    background: var(--bg3);
    border: 2px solid var(--border2);
    border-radius: var(--r);
    overflow: hidden;
    transition: var(--tr);
    cursor: pointer;
}
.template-card:hover { border-color: var(--p); transform: translateY(-2px); }
.template-card.is-default { border-color: var(--success); }
.template-preview {
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28px;
    position: relative;
}
.template-preview::after {
    content: '';
    position: absolute;
    inset: 0;
    background: linear-gradient(135deg, rgba(255,255,255,0.1), transparent);
}
.template-info { padding: 12px 14px; }
.template-name { font-size: 13px; font-weight: 800; color: var(--text); margin-bottom: 4px; }
.template-desc { font-size: 11px; color: var(--text2); margin-bottom: 10px; }
.template-actions { display: flex; gap: 6px; }
.default-badge {
    font-size: 10px;
    font-weight: 800;
    background: rgba(63,185,80,0.15);
    color: var(--success);
    padding: 2px 8px;
    border-radius: 10px;
    border: 1px solid rgba(63,185,80,0.3);
}

/* =====================================================
   BUTTON PREVIEW
===================================================== */
.btn-preview-box {
    background: var(--bg3);
    border: 1px solid var(--border2);
    border-radius: var(--r);
    padding: 20px;
    text-align: center;
    margin-bottom: 16px;
}
.btn-preview-box p { font-size: 11px; color: var(--text2); margin-top: 10px; }

/* =====================================================
   HERO PREVIEW
===================================================== */
.hero-preview {
    border-radius: var(--r);
    overflow: hidden;
    margin-bottom: 20px;
    border: 1px solid var(--border2);
}
.hero-preview-inner {
    padding: 24px 28px;
    color: white;
    transition: var(--tr);
}

/* =====================================================
   PAGE TABS (index / det)
===================================================== */
.page-tabs {
    display: flex;
    gap: 4px;
    margin-bottom: 20px;
    background: var(--bg3);
    padding: 4px;
    border-radius: var(--r);
    width: fit-content;
}
.page-tab {
    padding: 8px 20px;
    border-radius: var(--r-sm);
    font-size: 13px;
    font-weight: 700;
    cursor: pointer;
    transition: var(--tr);
    color: var(--text2);
    border: none;
    background: none;
    font-family: 'Tajawal', sans-serif;
}
.page-tab.active { background: var(--p); color: white; }
.page-tab:hover:not(.active) { color: var(--text); }

/* =====================================================
   STATS BAR
===================================================== */
.stats-bar {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 14px;
    margin-bottom: 24px;
}
.stat-card {
    background: var(--bg2);
    border: 1px solid var(--border2);
    border-radius: var(--r);
    padding: 18px 20px;
    display: flex;
    align-items: center;
    gap: 14px;
}
.stat-icon {
    width: 44px;
    height: 44px;
    border-radius: var(--r-sm);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    flex-shrink: 0;
}
.stat-info p { font-size: 11px; color: var(--text2); font-weight: 600; }
.stat-info h3 { font-size: 22px; font-weight: 900; color: var(--text); line-height: 1.2; }

/* =====================================================
   RESPONSIVE
===================================================== */
@media (max-width: 900px) {
    .sidebar { display: none; }
    .stats-bar { grid-template-columns: repeat(2,1fr); }
    .form-grid-2, .form-grid-3 { grid-template-columns: 1fr; }
    .css-rule-grid { grid-template-columns: 1fr 1fr; }
}
@media (max-width: 600px) {
    .content { padding: 16px; }
    .topbar { padding: 0 16px; }
    .stats-bar { grid-template-columns: 1fr 1fr; }
}
</style>
</head>
<body>

<!-- Toast -->
<div class="toast <?php echo $msg_type; ?>" id="toast">
    <?php echo $msg_type === 'success' ? '<i class="fas fa-check-circle"></i>' : '<i class="fas fa-exclamation-circle"></i>'; ?>
    <?php echo htmlspecialchars($msg); ?>
</div>

<div class="layout">

<!-- ===================================================
     SIDEBAR
=================================================== -->
<aside class="sidebar">
    <div class="sidebar-logo">
        <h1><i class="fas fa-palette"></i> <span>Design</span> Panel</h1>
        <p>لوحة تحكم التصميم الديناميكي</p>
    </div>

    <div class="nav-section">
        <div class="nav-section-label">الرئيسية</div>
        <button class="nav-item active" onclick="showTab('overview')">
            <i class="fas fa-chart-pie"></i> نظرة عامة
        </button>
    </div>

    <div class="nav-section">
        <div class="nav-section-label">التصميم</div>
        <button class="nav-item" onclick="showTab('settings')">
            <i class="fas fa-sliders-h"></i> الألوان والمتغيرات
            <span class="nav-badge"><?php echo count($settings_raw); ?></span>
        </button>
        <button class="nav-item" onclick="showTab('buttons')">
            <i class="fas fa-hand-pointer"></i> الأزرار
            <span class="nav-badge"><?php echo count($buttons_raw); ?></span>
        </button>
        <button class="nav-item" onclick="showTab('hero')">
            <i class="fas fa-star"></i> نصوص Hero
        </button>
    </div>

    <div class="nav-section">
        <div class="nav-section-label">الهيكل</div>
        <button class="nav-item" onclick="showTab('sections')">
            <i class="fas fa-layer-group"></i> الأقسام والترتيب
        </button>
        <button class="nav-item" onclick="showTab('css')">
            <i class="fas fa-code"></i> CSS مخصص
        </button>
    </div>

    <div class="nav-section">
        <div class="nav-section-label">القوالب</div>
        <button class="nav-item" onclick="showTab('templates')">
            <i class="fas fa-th-large"></i> القوالب الجاهزة
            <span class="nav-badge"><?php echo count($templates); ?></span>
        </button>
    </div>

    <div class="sidebar-footer">
        <a href="index33.php" target="_blank"><i class="fas fa-eye"></i> معاينة الرئيسية</a>
        <a href="det33.php?id=1" target="_blank"><i class="fas fa-box"></i> معاينة المنتج</a>
        <form method="POST" onsubmit="return confirm('إعادة تعيين كل الألوان للقيم الافتراضية؟')">
            <input type="hidden" name="action" value="reset_defaults">
            <button type="submit"><i class="fas fa-undo"></i> إعادة التعيين</button>
        </form>
    </div>
</aside>

<!-- ===================================================
     MAIN
=================================================== -->
<div class="main">

    <!-- TOPBAR -->
    <div class="topbar">
        <div class="topbar-title">لوحة تحكم <span>التصميم</span></div>
        <div class="topbar-actions">
            <a href="index33.php" target="_blank" class="btn-preview">
                <i class="fas fa-external-link-alt"></i> معاينة
            </a>
        </div>
    </div>

    <div class="content">

<!-- ===================================================
     TAB: OVERVIEW
=================================================== -->
<div class="tab-panel active" id="tab-overview">
    <div class="stats-bar">
        <div class="stat-card">
            <div class="stat-icon" style="background:rgba(47,129,247,0.15);color:var(--p)">
                <i class="fas fa-palette"></i>
            </div>
            <div class="stat-info">
                <p>إعدادات التصميم</p>
                <h3><?php echo count($settings_raw); ?></h3>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon" style="background:rgba(63,185,80,0.15);color:var(--success)">
                <i class="fas fa-hand-pointer"></i>
            </div>
            <div class="stat-info">
                <p>الأزرار المُخصصة</p>
                <h3><?php echo count($buttons_raw); ?></h3>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon" style="background:rgba(247,129,102,0.15);color:var(--accent)">
                <i class="fas fa-layer-group"></i>
            </div>
            <div class="stat-info">
                <p>الأقسام الإجمالية</p>
                <h3><?php echo count($sections_index) + count($sections_det); ?></h3>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon" style="background:rgba(210,153,34,0.15);color:var(--warning)">
                <i class="fas fa-th-large"></i>
            </div>
            <div class="stat-info">
                <p>القوالب الجاهزة</p>
                <h3><?php echo count($templates); ?></h3>
            </div>
        </div>
    </div>

    <!-- Quick color preview -->
    <div class="card">
        <div class="card-head">
            <h3><i class="fas fa-eye"></i> معاينة الألوان الحالية</h3>
            <button class="btn btn-secondary btn-sm" onclick="showTab('settings')">
                <i class="fas fa-edit"></i> تعديل
            </button>
        </div>
        <div class="card-body">
            <div style="display:flex;gap:12px;flex-wrap:wrap;margin-bottom:20px;">
                <?php
                $colorKeys = ['color_primary','color_primary_light','color_primary_dark','color_accent','color_danger','color_success','color_bg','color_surface','color_text'];
                foreach ($colorKeys as $ck):
                    if (!isset($settings[$ck])) continue;
                    $val = $settings[$ck]['setting_value'];
                    $lbl = $settings[$ck]['label'];
                    if (str_starts_with($val,'#') || str_starts_with($val,'rgb')):
                ?>
                <div style="text-align:center">
                    <div style="width:52px;height:52px;border-radius:12px;background:<?php echo htmlspecialchars($val); ?>;border:1px solid var(--border);box-shadow:0 2px 8px rgba(0,0,0,0.3);margin-bottom:6px;"></div>
                    <div style="font-size:10px;color:var(--text2);font-weight:600"><?php echo htmlspecialchars($lbl); ?></div>
                    <div style="font-size:10px;color:var(--text3);font-family:monospace"><?php echo htmlspecialchars($val); ?></div>
                </div>
                <?php endif; endforeach; ?>
            </div>

            <!-- Quick actions -->
            <div style="display:flex;gap:10px;flex-wrap:wrap">
                <button class="btn btn-primary" onclick="showTab('settings')">
                    <i class="fas fa-sliders-h"></i> تعديل الألوان
                </button>
                <button class="btn btn-secondary" onclick="showTab('templates')">
                    <i class="fas fa-th-large"></i> تطبيق قالب
                </button>
                <button class="btn btn-secondary" onclick="showTab('sections')">
                    <i class="fas fa-layer-group"></i> إدارة الأقسام
                </button>
                <a href="index33.php" target="_blank" class="btn btn-secondary">
                    <i class="fas fa-eye"></i> معاينة index33
                </a>
                <a href="det33.php?id=1" target="_blank" class="btn btn-secondary">
                    <i class="fas fa-eye"></i> معاينة det33
                </a>
            </div>
        </div>
    </div>

    <!-- Current hero preview -->
    <div class="card">
        <div class="card-head">
            <h3><i class="fas fa-star"></i> معاينة Hero الحالي</h3>
            <button class="btn btn-secondary btn-sm" onclick="showTab('hero')">تعديل</button>
        </div>
        <div class="card-body" style="padding:0">
            <div class="hero-preview-inner" style="background:<?php echo sv($settings,'hero_bg'); ?>">
                <div style="display:inline-flex;align-items:center;gap:8px;background:rgba(255,255,255,0.15);padding:5px 12px;border-radius:20px;font-size:11px;font-weight:700;margin-bottom:12px;border:1px solid rgba(255,255,255,0.25)">
                    <i class="fas fa-bolt"></i> <?php echo sv($settings,'hero_badge_text'); ?>
                </div>
                <h2 style="font-size:22px;font-weight:900;margin-bottom:8px;line-height:1.3">
                    <?php echo $settings['hero_title']['setting_value'] ?? ''; ?>
                </h2>
                <p style="font-size:13px;opacity:0.85;margin-bottom:14px">
                    <?php echo sv($settings,'hero_subtitle'); ?>
                </p>
                <div style="display:flex;gap:10px">
                    <span style="background:white;color:#1E40AF;padding:8px 16px;border-radius:8px;font-size:12px;font-weight:800">
                        <?php echo sv($settings,'hero_btn_primary_text'); ?>
                    </span>
                    <span style="background:rgba(255,255,255,0.15);color:white;padding:8px 16px;border-radius:8px;font-size:12px;font-weight:700;border:1px solid rgba(255,255,255,0.3)">
                        <?php echo sv($settings,'hero_btn_sec_text'); ?>
                    </span>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ===================================================
     TAB: SETTINGS (الألوان والمتغيرات)
=================================================== -->
<div class="tab-panel" id="tab-settings">
    <form method="POST" id="settingsForm">
        <input type="hidden" name="action" value="save_settings">

        <?php
        $catLabels = [
            'general'    => ['🎨 الألوان الرئيسية', 'fas fa-palette'],
            'typography' => ['✏️ الخطوط', 'fas fa-font'],
            'header'     => ['🔝 الهيدر', 'fas fa-heading'],
            'hero'       => ['⭐ Hero', 'fas fa-star'],
            'cards'      => ['🃏 البطاقات', 'fas fa-th-large'],
            'footer'     => ['🔻 الفوتر', 'fas fa-shoe-prints'],
        ];
        $catKeys = array_keys($settings_by_cat);
        ?>

        <!-- Category Tabs -->
        <div class="cat-tabs">
            <?php foreach ($catKeys as $i => $cat):
                $lbl = $catLabels[$cat][0] ?? ucfirst($cat);
            ?>
            <button type="button" class="cat-tab <?php echo $i===0?'active':''; ?>"
                    onclick="showCat('<?php echo $cat; ?>', this)">
                <?php echo $lbl; ?>
            </button>
            <?php endforeach; ?>
        </div>

        <?php foreach ($settings_by_cat as $cat => $catSettings):
            $first = array_key_first($settings_by_cat) === $cat;
        ?>
        <div class="cat-panel <?php echo $first?'active':''; ?>" id="cat-<?php echo $cat; ?>">
            <div class="card">
                <div class="card-head">
                    <h3>
                        <i class="<?php echo $catLabels[$cat][1] ?? 'fas fa-cog'; ?>"></i>
                        <?php echo $catLabels[$cat][0] ?? ucfirst($cat); ?>
                    </h3>
                    <span style="font-size:11px;color:var(--text2)"><?php echo count($catSettings); ?> إعداد</span>
                </div>
                <div class="card-body">
                    <div class="form-grid">
                        <?php foreach ($catSettings as $s):
                            $key = $s['setting_key'];
                            $val = $s['setting_value'] ?? $s['default_value'] ?? '';
                            $lbl = $s['label'] ?? $key;
                            $type = $s['setting_type'];
                        ?>
                        <div class="field">
                            <label><?php echo htmlspecialchars($lbl); ?></label>
                            <?php if ($type === 'color'): ?>
                            <div class="color-field">
                                <input type="color" value="<?php echo htmlspecialchars($val); ?>"
                                       oninput="this.nextElementSibling.value=this.value;updatePreview()">
                                <input type="text" name="settings[<?php echo $key; ?>]"
                                       value="<?php echo htmlspecialchars($val); ?>"
                                       oninput="this.previousElementSibling.value=this.value;updatePreview()"
                                       style="font-family:monospace">
                            </div>
                            <?php elseif ($type === 'boolean'): ?>
                            <div class="toggle-wrap">
                                <label class="toggle">
                                    <input type="hidden" name="settings[<?php echo $key; ?>]" value="0">
                                    <input type="checkbox" name="settings[<?php echo $key; ?>]"
                                           value="1" <?php echo $val=='1'?'checked':''; ?>
                                           onchange="updatePreview()">
                                    <span class="toggle-slider"></span>
                                </label>
                                <span class="toggle-label"><?php echo $val=='1'?'مفعّل':'معطّل'; ?></span>
                            </div>
                            <?php else: ?>
                            <textarea name="settings[<?php echo $key; ?>]"
                                      rows="<?php echo strlen($val)>80?3:1; ?>"
                                      oninput="updatePreview()"><?php echo htmlspecialchars($val); ?></textarea>
                            <?php endif; ?>
                            <span style="font-size:10px;color:var(--text3);font-family:monospace"><?php echo $key; ?></span>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>

        <div class="save-bar">
            <span class="save-bar-info"><i class="fas fa-info-circle"></i> التغييرات تُطبَّق فور الحفظ على الصفحتين</span>
            <div style="display:flex;gap:10px">
                <button type="button" class="btn btn-secondary" onclick="resetForm()">
                    <i class="fas fa-undo"></i> تراجع
                </button>
                <button type="submit" class="btn btn-primary btn-lg">
                    <i class="fas fa-save"></i> حفظ التغييرات
                </button>
            </div>
        </div>
    </form>
</div>

<!-- ===================================================
     TAB: BUTTONS
=================================================== -->
<div class="tab-panel" id="tab-buttons">
    <form method="POST">
        <input type="hidden" name="action" value="save_buttons">
        <?php foreach ($buttons_raw as $btn):
            $type = $btn['button_type'];
        ?>
        <div class="card">
            <div class="card-head">
                <h3><i class="fas fa-hand-pointer"></i> <?php echo htmlspecialchars($btn['label'] ?? $type); ?></h3>
                <span style="font-size:11px;color:var(--text3);font-family:monospace"><?php echo $type; ?></span>
            </div>
            <div class="card-body">
                <!-- Preview -->
                <div class="btn-preview-box" id="preview-<?php echo $type; ?>">
                    <button type="button" id="btn-live-<?php echo $type; ?>" style="
                        background:<?php echo htmlspecialchars($btn['background_color']); ?>;
                        color:<?php echo htmlspecialchars($btn['text_color']); ?>;
                        border:none;
                        padding:<?php echo htmlspecialchars($btn['padding_vertical']); ?> <?php echo htmlspecialchars($btn['padding_horizontal']); ?>;
                        border-radius:<?php echo htmlspecialchars($btn['border_radius']); ?>;
                        font-size:<?php echo htmlspecialchars($btn['font_size']); ?>;
                        font-weight:<?php echo htmlspecialchars($btn['font_weight']); ?>;
                        box-shadow:<?php echo htmlspecialchars($btn['box_shadow']); ?>;
                        cursor:pointer;font-family:'Tajawal',sans-serif;
                        display:inline-flex;align-items:center;gap:8px;">
                        <?php if (!empty($btn['icon_class'])): ?>
                        <i class="<?php echo htmlspecialchars($btn['icon_class']); ?>"></i>
                        <?php endif; ?>
                        <?php echo htmlspecialchars($btn['button_text'] ?? 'الزر'); ?>
                    </button>
                    <p>معاينة حية — تتغير مع التعديل</p>
                </div>

                <div class="form-grid">
                    <div class="field">
                        <label>نص الزر</label>
                        <input type="text" name="buttons[<?php echo $type; ?>][button_text]"
                               value="<?php echo htmlspecialchars($btn['button_text'] ?? ''); ?>"
                               oninput="updateBtnPreview('<?php echo $type; ?>')">
                    </div>
                    <div class="field">
                        <label>أيقونة (Font Awesome class)</label>
                        <input type="text" name="buttons[<?php echo $type; ?>][icon_class]"
                               value="<?php echo htmlspecialchars($btn['icon_class'] ?? ''); ?>"
                               placeholder="fas fa-shopping-bag"
                               oninput="updateBtnPreview('<?php echo $type; ?>')">
                    </div>
                    <div class="field">
                        <label>لون الخلفية</label>
                        <div class="color-field">
                            <input type="color" value="<?php echo str_starts_with($btn['background_color'],'#')?$btn['background_color']:'#1E40AF'; ?>"
                                   oninput="document.querySelector('[name=\'buttons[<?php echo $type; ?>][background_color]\']').value=this.value;updateBtnPreview('<?php echo $type; ?>')">
                            <input type="text" name="buttons[<?php echo $type; ?>][background_color]"
                                   value="<?php echo htmlspecialchars($btn['background_color']); ?>"
                                   oninput="updateBtnPreview('<?php echo $type; ?>')" style="font-family:monospace">
                        </div>
                    </div>
                    <div class="field">
                        <label>لون النص</label>
                        <div class="color-field">
                            <input type="color" value="<?php echo $btn['text_color']; ?>"
                                   oninput="document.querySelector('[name=\'buttons[<?php echo $type; ?>][text_color]\']').value=this.value;updateBtnPreview('<?php echo $type; ?>')">
                            <input type="text" name="buttons[<?php echo $type; ?>][text_color]"
                                   value="<?php echo htmlspecialchars($btn['text_color']); ?>"
                                   oninput="updateBtnPreview('<?php echo $type; ?>')" style="font-family:monospace">
                        </div>
                    </div>
                    <div class="field">
                        <label>لون الخلفية عند Hover</label>
                        <input type="text" name="buttons[<?php echo $type; ?>][hover_background]"
                               value="<?php echo htmlspecialchars($btn['hover_background']); ?>"
                               style="font-family:monospace">
                    </div>
                    <div class="field">
                        <label>نصف القطر (border-radius)</label>
                        <input type="text" name="buttons[<?php echo $type; ?>][border_radius]"
                               value="<?php echo htmlspecialchars($btn['border_radius']); ?>"
                               oninput="updateBtnPreview('<?php echo $type; ?>')">
                    </div>
                    <div class="field">
                        <label>حشوة رأسية (padding top/bottom)</label>
                        <input type="text" name="buttons[<?php echo $type; ?>][padding_vertical]"
                               value="<?php echo htmlspecialchars($btn['padding_vertical']); ?>"
                               oninput="updateBtnPreview('<?php echo $type; ?>')">
                    </div>
                    <div class="field">
                        <label>حشوة أفقية (padding left/right)</label>
                        <input type="text" name="buttons[<?php echo $type; ?>][padding_horizontal]"
                               value="<?php echo htmlspecialchars($btn['padding_horizontal']); ?>"
                               oninput="updateBtnPreview('<?php echo $type; ?>')">
                    </div>
                    <div class="field">
                        <label>حجم الخط</label>
                        <input type="text" name="buttons[<?php echo $type; ?>][font_size]"
                               value="<?php echo htmlspecialchars($btn['font_size']); ?>"
                               oninput="updateBtnPreview('<?php echo $type; ?>')">
                    </div>
                    <div class="field">
                        <label>وزن الخط (font-weight)</label>
                        <select name="buttons[<?php echo $type; ?>][font_weight]">
                            <?php foreach (['400','500','600','700','800','900'] as $fw): ?>
                            <option value="<?php echo $fw; ?>" <?php echo $btn['font_weight']==$fw?'selected':''; ?>><?php echo $fw; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="field">
                        <label>الظل (box-shadow)</label>
                        <input type="text" name="buttons[<?php echo $type; ?>][box_shadow]"
                               value="<?php echo htmlspecialchars($btn['box_shadow']); ?>"
                               oninput="updateBtnPreview('<?php echo $type; ?>')" style="font-family:monospace">
                    </div>
                    <div class="field">
                        <label>نوع الأنيميشن</label>
                        <select name="buttons[<?php echo $type; ?>][animation_type]">
                            <?php foreach (['none'=>'بدون','pulse'=>'نبض','glow'=>'توهج','bounce'=>'ارتداد'] as $av => $al): ?>
                            <option value="<?php echo $av; ?>" <?php echo $btn['animation_type']==$av?'selected':''; ?>><?php echo $al; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div style="margin-top:14px;display:flex;align-items:center;gap:12px">
                    <label class="toggle">
                        <input type="checkbox" name="buttons[<?php echo $type; ?>][is_glow_enabled]"
                               value="1" <?php echo $btn['is_glow_enabled']?'checked':''; ?>>
                        <span class="toggle-slider"></span>
                    </label>
                    <span class="toggle-label">تفعيل التوهج (Glow)</span>
                    <input type="text" name="buttons[<?php echo $type; ?>][glow_color]"
                           value="<?php echo htmlspecialchars($btn['glow_color']); ?>"
                           style="width:120px;font-family:monospace;padding:6px 10px;background:var(--bg3);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:12px">
                </div>
            </div>
        </div>
        <?php endforeach; ?>

        <div class="save-bar">
            <span class="save-bar-info"><i class="fas fa-info-circle"></i> تُطبَّق على index33.php و det33.php</span>
            <button type="submit" class="btn btn-primary btn-lg">
                <i class="fas fa-save"></i> حفظ الأزرار
            </button>
        </div>
    </form>
</div>

<!-- ===================================================
     TAB: HERO
=================================================== -->
<div class="tab-panel" id="tab-hero">
    <form method="POST">
        <input type="hidden" name="action" value="save_settings">

        <!-- Live preview -->
        <div class="card">
            <div class="card-head"><h3><i class="fas fa-eye"></i> معاينة Hero حية</h3></div>
            <div style="padding:0;overflow:hidden;border-radius:0 0 var(--r) var(--r)">
                <div id="heroBgPreview" style="background:<?php echo sv($settings,'hero_bg'); ?>;padding:28px 32px;color:white;transition:all .3s ease">
                    <div style="display:inline-flex;align-items:center;gap:8px;background:rgba(255,255,255,0.15);padding:5px 14px;border-radius:20px;font-size:12px;font-weight:700;margin-bottom:14px;border:1px solid rgba(255,255,255,0.25)">
                        <i class="fas fa-bolt"></i>
                        <span id="prev-badge"><?php echo sv($settings,'hero_badge_text'); ?></span>
                    </div>
                    <h2 id="prev-title" style="font-size:24px;font-weight:900;margin-bottom:10px;line-height:1.4">
                        <?php echo $settings['hero_title']['setting_value'] ?? ''; ?>
                    </h2>
                    <p id="prev-subtitle" style="font-size:14px;opacity:0.85;margin-bottom:16px">
                        <?php echo sv($settings,'hero_subtitle'); ?>
                    </p>
                    <div style="display:flex;gap:10px;flex-wrap:wrap">
                        <span id="prev-btn1" style="background:white;color:#1E40AF;padding:10px 20px;border-radius:8px;font-size:13px;font-weight:800;display:inline-flex;align-items:center;gap:6px">
                            <i class="fas fa-shopping-bag"></i>
                            <span id="prev-btn1-txt"><?php echo sv($settings,'hero_btn_primary_text'); ?></span>
                        </span>
                        <span id="prev-btn2" style="background:rgba(255,255,255,0.15);color:white;padding:10px 20px;border-radius:8px;font-size:13px;font-weight:700;border:1px solid rgba(255,255,255,0.3)">
                            <span id="prev-btn2-txt"><?php echo sv($settings,'hero_btn_sec_text'); ?></span>
                        </span>
                        <span id="prev-emoji" style="font-size:36px">
                            <?php echo sv($settings,'hero_emoji'); ?>
                        </span>
                    </div>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-head"><h3><i class="fas fa-edit"></i> تعديل نصوص Hero</h3></div>
            <div class="card-body">
                <div class="form-grid">
                    <div class="field">
                        <label>نص الشارة الصغيرة</label>
                        <input type="text" name="settings[hero_badge_text]"
                               value="<?php echo sv($settings,'hero_badge_text'); ?>"
                               oninput="document.getElementById('prev-badge').textContent=this.value">
                    </div>
                    <div class="field">
                        <label>نص زر "تسوّق الآن"</label>
                        <input type="text" name="settings[hero_btn_primary_text]"
                               value="<?php echo sv($settings,'hero_btn_primary_text'); ?>"
                               oninput="document.getElementById('prev-btn1-txt').textContent=this.value">
                    </div>
                    <div class="field">
                        <label>نص الزر الثانوي</label>
                        <input type="text" name="settings[hero_btn_sec_text]"
                               value="<?php echo sv($settings,'hero_btn_sec_text'); ?>"
                               oninput="document.getElementById('prev-btn2-txt').textContent=this.value">
                    </div>
                    <div class="field">
                        <label>أيقونة Emoji</label>
                        <input type="text" name="settings[hero_emoji]"
                               value="<?php echo sv($settings,'hero_emoji'); ?>"
                               oninput="document.getElementById('prev-emoji').textContent=this.value">
                    </div>
                    <div class="field" style="grid-column:1/-1">
                        <label>العنوان الرئيسي (يدعم HTML كـ &lt;span&gt;، &lt;br&gt;)</label>
                        <textarea name="settings[hero_title]" rows="3"
                                  oninput="document.getElementById('prev-title').innerHTML=this.value"><?php echo htmlspecialchars($settings['hero_title']['setting_value'] ?? ''); ?></textarea>
                        <span style="font-size:11px;color:var(--text2)">💡 استخدم &lt;span&gt;نص مميز&lt;/span&gt; لتلوين جزء من العنوان</span>
                    </div>
                    <div class="field" style="grid-column:1/-1">
                        <label>النص الوصفي تحت العنوان</label>
                        <textarea name="settings[hero_subtitle]" rows="2"
                                  oninput="document.getElementById('prev-subtitle').textContent=this.value"><?php echo htmlspecialchars(sv($settings,'hero_subtitle')); ?></textarea>
                    </div>
                    <div class="field" style="grid-column:1/-1">
                        <label>خلفية Hero (gradient أو لون)</label>
                        <textarea name="settings[hero_bg]" rows="2"
                                  oninput="document.getElementById('heroBgPreview').style.background=this.value"
                                  style="font-family:monospace;font-size:12px"><?php echo htmlspecialchars(sv($settings,'hero_bg')); ?></textarea>
                        <span style="font-size:11px;color:var(--text2)">💡 مثال: <code style="color:var(--p)">linear-gradient(135deg,#1E3A8A,#1E40AF)</code></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Also include other non-hero settings as hidden -->
        <?php foreach ($settings_raw as $s):
            if ($s['category'] === 'hero') continue;
        ?>
        <input type="hidden" name="settings[<?php echo $s['setting_key']; ?>]" value="<?php echo htmlspecialchars($s['setting_value'] ?? ''); ?>">
        <?php endforeach; ?>

        <div class="save-bar">
            <span class="save-bar-info"><i class="fas fa-info-circle"></i> التغييرات تُطبَّق فور الحفظ</span>
            <button type="submit" class="btn btn-primary btn-lg">
                <i class="fas fa-save"></i> حفظ Hero
            </button>
        </div>
    </form>
</div>

<!-- ===================================================
     TAB: SECTIONS
=================================================== -->
<div class="tab-panel" id="tab-sections">
    <div class="page-tabs">
        <button class="page-tab active" onclick="showPageSections('index',this)">
            <i class="fas fa-home"></i> index33.php
        </button>
        <button class="page-tab" onclick="showPageSections('det',this)">
            <i class="fas fa-box"></i> det33.php
        </button>
    </div>

    <!-- index sections -->
    <div id="secs-index">
        <form method="POST">
            <input type="hidden" name="action" value="save_sections">
            <input type="hidden" name="page_target" value="index">
            <div class="card">
                <div class="card-head">
                    <h3><i class="fas fa-layer-group"></i> أقسام index33.php</h3>
                    <span style="font-size:11px;color:var(--text2)">اسحب لإعادة الترتيب</span>
                </div>
                <div class="card-body">
                    <div class="sections-list" id="drag-index">
                        <?php foreach ($sections_index as $sec): ?>
                        <div class="section-item" draggable="true" data-key="<?php echo $sec['section_key']; ?>">
                            <span class="drag-handle"><i class="fas fa-grip-vertical"></i></span>
                            <span class="section-name"><?php echo htmlspecialchars($sec['label']); ?></span>
                            <span class="section-key"><?php echo $sec['section_key']; ?></span>
                            <div class="section-pos">
                                <input type="number" name="sections[<?php echo $sec['section_key']; ?>][position]"
                                       value="<?php echo $sec['position']; ?>" min="0" max="99">
                            </div>
                            <label class="toggle">
                                <input type="checkbox" name="sections[<?php echo $sec['section_key']; ?>][visible]"
                                       value="1" <?php echo $sec['is_visible']?'checked':''; ?>>
                                <span class="toggle-slider"></span>
                            </label>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <div class="save-bar">
                <span class="save-bar-info">💡 الإخفاء لا يحذف القسم، بإمكانك إظهاره مجدداً</span>
                <button type="submit" class="btn btn-primary btn-lg">
                    <i class="fas fa-save"></i> حفظ الترتيب
                </button>
            </div>
        </form>
    </div>

    <!-- det sections -->
    <div id="secs-det" style="display:none">
        <form method="POST">
            <input type="hidden" name="action" value="save_sections">
            <input type="hidden" name="page_target" value="det">
            <div class="card">
                <div class="card-head">
                    <h3><i class="fas fa-layer-group"></i> أقسام det33.php</h3>
                    <span style="font-size:11px;color:var(--text2)">اسحب لإعادة الترتيب</span>
                </div>
                <div class="card-body">
                    <div class="sections-list" id="drag-det">
                        <?php foreach ($sections_det as $sec): ?>
                        <div class="section-item" draggable="true" data-key="<?php echo $sec['section_key']; ?>">
                            <span class="drag-handle"><i class="fas fa-grip-vertical"></i></span>
                            <span class="section-name"><?php echo htmlspecialchars($sec['label']); ?></span>
                            <span class="section-key"><?php echo $sec['section_key']; ?></span>
                            <div class="section-pos">
                                <input type="number" name="sections[<?php echo $sec['section_key']; ?>][position]"
                                       value="<?php echo $sec['position']; ?>" min="0" max="99">
                            </div>
                            <label class="toggle">
                                <input type="checkbox" name="sections[<?php echo $sec['section_key']; ?>][visible]"
                                       value="1" <?php echo $sec['is_visible']?'checked':''; ?>>
                                <span class="toggle-slider"></span>
                            </label>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <div class="save-bar">
                <span class="save-bar-info">💡 الإخفاء لا يحذف القسم</span>
                <button type="submit" class="btn btn-primary btn-lg">
                    <i class="fas fa-save"></i> حفظ الترتيب
                </button>
            </div>
        </form>
    </div>
</div>

<!-- ===================================================
     TAB: CSS EDITOR
=================================================== -->
<div class="tab-panel" id="tab-css">
    <div class="page-tabs">
        <button class="page-tab active" onclick="showCssPage('all',this)">كلتا الصفحتين</button>
        <button class="page-tab" onclick="showCssPage('index',this)">index33 فقط</button>
        <button class="page-tab" onclick="showCssPage('det',this)">det33 فقط</button>
    </div>

    <?php
    $cssPages = [
        'all'   => ['title'=>'CSS مشترك للصفحتين', 'rules'=>$css_rules_all],
        'index' => ['title'=>'CSS خاص بـ index33.php', 'rules'=>$css_rules_index],
        'det'   => ['title'=>'CSS خاص بـ det33.php', 'rules'=>$css_rules_det],
    ];
    foreach ($cssPages as $cp => $cpData):
    ?>
    <div id="css-<?php echo $cp; ?>" <?php echo $cp!=='all'?'style="display:none"':''; ?>>
        <form method="POST">
            <input type="hidden" name="action" value="save_css">
            <input type="hidden" name="css_page" value="<?php echo $cp; ?>">
            <div class="card">
                <div class="card-head">
                    <h3><i class="fas fa-code"></i> <?php echo $cpData['title']; ?></h3>
                    <button type="button" class="btn btn-secondary btn-sm" onclick="addCssRule('<?php echo $cp; ?>')">
                        <i class="fas fa-plus"></i> إضافة قاعدة
                    </button>
                </div>
                <div class="card-body">
                    <div id="css-rules-<?php echo $cp; ?>">
                        <?php if (empty($cpData['rules'])): ?>
                        <div style="text-align:center;padding:40px;color:var(--text3)">
                            <i class="fas fa-code" style="font-size:32px;display:block;margin-bottom:12px;opacity:0.3"></i>
                            لا توجد قواعد CSS بعد — اضغط "+ إضافة قاعدة"
                        </div>
                        <?php else: ?>
                        <?php foreach ($cpData['rules'] as $rule): ?>
                        <div class="css-rule">
                            <div class="css-rule-grid">
                                <div class="field">
                                    <label>CSS Selector</label>
                                    <input type="text" name="css_rules[][selector]"
                                           value="<?php echo htmlspecialchars($rule['css_selector']); ?>"
                                           placeholder=".product-card:hover" style="font-family:monospace;font-size:12px">
                                </div>
                                <div class="field">
                                    <label>CSS Property</label>
                                    <input type="text" name="css_rules[][property]"
                                           value="<?php echo htmlspecialchars($rule['css_property']); ?>"
                                           placeholder="background-color" style="font-family:monospace;font-size:12px">
                                </div>
                                <div class="field">
                                    <label>CSS Value</label>
                                    <input type="text" name="css_rules[][value]"
                                           value="<?php echo htmlspecialchars($rule['css_value']); ?>"
                                           placeholder="#FF0000" style="font-family:monospace;font-size:12px">
                                </div>
                                <button type="button" class="css-delete" onclick="this.closest('.css-rule').remove()">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </div>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <div class="save-bar">
                <span class="save-bar-info">💡 يتم حقن هذا CSS في &lt;style&gt; آخر الصفحة</span>
                <button type="submit" class="btn btn-primary btn-lg">
                    <i class="fas fa-save"></i> حفظ CSS
                </button>
            </div>
        </form>
    </div>
    <?php endforeach; ?>
</div>

<!-- ===================================================
     TAB: TEMPLATES
=================================================== -->
<div class="tab-panel" id="tab-templates">
    <div class="card">
        <div class="card-head">
            <h3><i class="fas fa-th-large"></i> القوالب الجاهزة</h3>
        </div>
        <div class="card-body">
            <div class="templates-grid">
                <?php foreach ($templates as $tpl): ?>
                <div class="template-card <?php echo $tpl['is_default']?'is-default':''; ?>">
                    <div class="template-preview" style="background:linear-gradient(135deg,<?php echo htmlspecialchars($tpl['preview_color']); ?>,<?php echo htmlspecialchars($tpl['preview_color']); ?>88)">
                        🎨
                    </div>
                    <div class="template-info">
                        <div class="template-name">
                            <?php echo htmlspecialchars($tpl['name']); ?>
                            <?php if ($tpl['is_default']): ?>
                            <span class="default-badge">افتراضي</span>
                            <?php endif; ?>
                        </div>
                        <div class="template-desc"><?php echo htmlspecialchars($tpl['description'] ?? ''); ?></div>
                        <div class="template-actions">
                            <form method="POST" style="display:inline">
                                <input type="hidden" name="action" value="apply_template">
                                <input type="hidden" name="template_id" value="<?php echo $tpl['id']; ?>">
                                <button type="submit" class="btn btn-success btn-sm"
                                        onclick="return confirm('تطبيق قالب: <?php echo addslashes($tpl['name']); ?>؟')">
                                    <i class="fas fa-check"></i> تطبيق
                                </button>
                            </form>
                            <?php if (!$tpl['is_default']): ?>
                            <form method="POST" style="display:inline">
                                <input type="hidden" name="action" value="delete_template">
                                <input type="hidden" name="template_id" value="<?php echo $tpl['id']; ?>">
                                <button type="submit" class="btn btn-danger btn-sm"
                                        onclick="return confirm('حذف القالب نهائياً؟')">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </form>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- Save current as template -->
    <div class="card">
        <div class="card-head">
            <h3><i class="fas fa-plus-circle"></i> حفظ الإعدادات الحالية كقالب جديد</h3>
        </div>
        <div class="card-body">
            <form method="POST">
                <input type="hidden" name="action" value="save_template">
                <div class="form-grid-3">
                    <div class="field">
                        <label>اسم القالب</label>
                        <input type="text" name="tpl_name" placeholder="مثال: تصميم الصيف" required>
                    </div>
                    <div class="field">
                        <label>وصف مختصر</label>
                        <input type="text" name="tpl_desc" placeholder="وصف القالب">
                    </div>
                    <div class="field">
                        <label>لون المعاينة</label>
                        <div class="color-field">
                            <input type="color" value="#1E40AF" oninput="this.nextElementSibling.value=this.value">
                            <input type="text" name="tpl_color" value="#1E40AF" style="font-family:monospace">
                        </div>
                    </div>
                </div>
                <button type="submit" class="btn btn-primary" style="margin-top:14px">
                    <i class="fas fa-save"></i> حفظ كقالب جديد
                </button>
            </form>
        </div>
    </div>
</div>

<!-- END CONTENT -->
    </div><!-- .content -->
</div><!-- .main -->
</div><!-- .layout -->

<script>
// =====================================================
//  TAB NAVIGATION
// =====================================================
function showTab(name) {
    document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
    document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active'));
    document.getElementById('tab-' + name)?.classList.add('active');
    document.querySelectorAll('.nav-item').forEach(n => {
        if (n.getAttribute('onclick')?.includes("'" + name + "'")) n.classList.add('active');
    });
    window.scrollTo({top:0, behavior:'smooth'});
}

// =====================================================
//  CATEGORY TABS (settings)
// =====================================================
function showCat(cat, btn) {
    document.querySelectorAll('.cat-panel').forEach(p => p.classList.remove('active'));
    document.querySelectorAll('.cat-tab').forEach(t => t.classList.remove('active'));
    document.getElementById('cat-' + cat)?.classList.add('active');
    btn.classList.add('active');
}

// =====================================================
//  PAGE SECTIONS TABS
// =====================================================
function showPageSections(page, btn) {
    ['index','det'].forEach(p => {
        document.getElementById('secs-' + p).style.display = p === page ? 'block' : 'none';
    });
    btn.closest('.page-tabs').querySelectorAll('.page-tab').forEach(t => t.classList.remove('active'));
    btn.classList.add('active');
}

// =====================================================
//  CSS PAGE TABS
// =====================================================
function showCssPage(page, btn) {
    ['all','index','det'].forEach(p => {
        document.getElementById('css-' + p).style.display = p === page ? 'block' : 'none';
    });
    btn.closest('.page-tabs').querySelectorAll('.page-tab').forEach(t => t.classList.remove('active'));
    btn.classList.add('active');
}

// =====================================================
//  ADD CSS RULE
// =====================================================
function addCssRule(page) {
    const container = document.getElementById('css-rules-' + page);
    // Remove empty state message if present
    const emptyMsg = container.querySelector('div[style*="text-align:center"]');
    if (emptyMsg) emptyMsg.remove();

    const div = document.createElement('div');
    div.className = 'css-rule';
    div.innerHTML = `
        <div class="css-rule-grid">
            <div class="field">
                <label>CSS Selector</label>
                <input type="text" name="css_rules[][selector]" placeholder=".product-card" style="font-family:monospace;font-size:12px">
            </div>
            <div class="field">
                <label>CSS Property</label>
                <input type="text" name="css_rules[][property]" placeholder="border-radius" style="font-family:monospace;font-size:12px">
            </div>
            <div class="field">
                <label>CSS Value</label>
                <input type="text" name="css_rules[][value]" placeholder="20px" style="font-family:monospace;font-size:12px">
            </div>
            <button type="button" class="css-delete" onclick="this.closest('.css-rule').remove()">
                <i class="fas fa-trash"></i>
            </button>
        </div>`;
    container.appendChild(div);
    div.querySelector('input').focus();
}

// =====================================================
//  BUTTON LIVE PREVIEW
// =====================================================
function updateBtnPreview(type) {
    const btn = document.getElementById('btn-live-' + type);
    if (!btn) return;
    const get = (name) => {
        const el = document.querySelector(`[name="buttons[${type}][${name}]"]`);
        return el ? el.value : '';
    };
    btn.style.background      = get('background_color');
    btn.style.color           = get('text_color');
    btn.style.borderRadius    = get('border_radius');
    btn.style.padding         = `${get('padding_vertical')} ${get('padding_horizontal')}`;
    btn.style.fontSize        = get('font_size');
    btn.style.fontWeight      = get('font_weight');
    btn.style.boxShadow       = get('box_shadow');
    const iconClass = get('icon_class');
    const txt       = get('button_text');
    btn.innerHTML = (iconClass ? `<i class="${iconClass}"></i> ` : '') + txt;
}

// =====================================================
//  DRAG & DROP FOR SECTIONS
// =====================================================
function initDrag(listId) {
    const list = document.getElementById(listId);
    if (!list) return;
    let dragSrc = null;

    list.querySelectorAll('.section-item').forEach(item => {
        item.addEventListener('dragstart', e => {
            dragSrc = item;
            setTimeout(() => item.classList.add('dragging'), 0);
            e.dataTransfer.effectAllowed = 'move';
        });
        item.addEventListener('dragend', () => {
            item.classList.remove('dragging');
            list.querySelectorAll('.section-item').forEach(i => i.classList.remove('drag-over'));
            // Update position inputs
            list.querySelectorAll('.section-item').forEach((i, idx) => {
                const posInput = i.querySelector('input[type=number]');
                if (posInput) posInput.value = idx + 1;
            });
        });
        item.addEventListener('dragover', e => {
            e.preventDefault();
            e.dataTransfer.dropEffect = 'move';
            if (item !== dragSrc) {
                list.querySelectorAll('.section-item').forEach(i => i.classList.remove('drag-over'));
                item.classList.add('drag-over');
            }
        });
        item.addEventListener('drop', e => {
            e.preventDefault();
            if (dragSrc && dragSrc !== item) {
                const items = [...list.querySelectorAll('.section-item')];
                const srcIdx  = items.indexOf(dragSrc);
                const destIdx = items.indexOf(item);
                if (srcIdx < destIdx) item.after(dragSrc);
                else item.before(dragSrc);
            }
        });
    });
}
initDrag('drag-index');
initDrag('drag-det');

// =====================================================
//  TOAST ON LOAD
// =====================================================
<?php if ($msg): ?>
window.addEventListener('load', () => {
    const t = document.getElementById('toast');
    t.classList.add('show');
    setTimeout(() => t.classList.remove('show'), 4000);
});
<?php endif; ?>

// =====================================================
//  LIVE PREVIEW (update CSS vars in page for quick demo)
// =====================================================
function updatePreview() {
    // just visual feedback; actual changes are on save
}

function resetForm() {
    if (confirm('التراجع عن التغييرات غير المحفوظة؟')) location.reload();
}
</script>
</body>
</html>