<?php
include "session.php";
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);


header("Cache-Control: no-cache, must-revalidate");

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

// ============================================
// معالجة الفئات — POST فقط (ليس GET)
// ============================================

// إضافة / تعديل فئة
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_category'])) {
    try {
        $name        = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');

        if (empty($name)) throw new Exception("اسم الفئة مطلوب");

        $category_id = intval($_POST['category_id'] ?? 0);

        if ($category_id > 0) {
            $pdo->prepare("UPDATE categories SET name=?, description=? WHERE id=?")
                ->execute([$name, $description, $category_id]);
            $_SESSION['message'] = "تم تحديث الفئة بنجاح";
        } else {
            $pdo->prepare("INSERT INTO categories (name, description) VALUES (?,?)")
                ->execute([$name, $description]);
            $_SESSION['message'] = "تم إضافة الفئة بنجاح";
        }
        header("Location: manage_categories.php"); exit;
    } catch (Exception $e) {
        $_SESSION['error_message'] = "خطأ: " . $e->getMessage();
    }
}

// حذف فئة — POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_category'])) {
    try {
        $category_id = intval($_POST['delete_category']);
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM products WHERE category_id=?");
        $stmt->execute([$category_id]);
        if ($stmt->fetchColumn() > 0)
            throw new Exception("لا يمكن حذف الفئة لأنها مرتبطة بمنتجات");

        $pdo->prepare("DELETE FROM categories WHERE id=?")->execute([$category_id]);
        $_SESSION['message'] = "تم حذف الفئة بنجاح";
        header("Location: manage_categories.php"); exit;
    } catch (Exception $e) {
        $_SESSION['error_message'] = "خطأ أثناء الحذف: " . $e->getMessage();
    }
}

// ============================================
// معالجة الخصائص
// ============================================

// إضافة / تعديل خاصية
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_attribute'])) {
    try {
        $name        = trim($_POST['name'] ?? '');
        $input_type  = $_POST['input_type'] ?? 'text';
        $values_list = trim($_POST['values_list'] ?? '');
        $is_required = isset($_POST['is_required']) ? 1 : 0;

        if (empty($name)) throw new Exception("اسم الخاصية مطلوب");
        if ($input_type === 'select' && empty($values_list))
            throw new Exception("قيم الخاصية مطلوبة للنوع قائمة منسدلة");

        $attribute_id = intval($_POST['attribute_id'] ?? 0);

        if ($attribute_id > 0) {
            $pdo->prepare("UPDATE attributes SET name=?, input_type=?, values_list=?, is_required=? WHERE id=?")
                ->execute([$name, $input_type, $values_list, $is_required, $attribute_id]);
            $pdo->prepare("DELETE FROM attribute_values WHERE attribute_id=?")->execute([$attribute_id]);
            $_SESSION['message'] = "تم تحديث الخاصية بنجاح";
        } else {
            $pdo->prepare("INSERT INTO attributes (name, input_type, values_list, is_required) VALUES (?,?,?,?)")
                ->execute([$name, $input_type, $values_list, $is_required]);
            $attribute_id = $pdo->lastInsertId();
            $_SESSION['message'] = "تم إضافة الخاصية بنجاح";
        }

        if ($input_type === 'select' && !empty($values_list)) {
            foreach (explode(',', $values_list) as $val) {
                $val = trim($val);
                if ($val !== '') {
                    $pdo->prepare("INSERT INTO attribute_values (attribute_id, value) VALUES (?,?)")
                        ->execute([$attribute_id, $val]);
                }
            }
        }
        header("Location: manage_categories.php"); exit;
    } catch (Exception $e) {
        $_SESSION['error_message'] = "خطأ: " . $e->getMessage();
    }
}

// حذف خاصية — POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_attribute'])) {
    try {
        $attribute_id = intval($_POST['delete_attribute']);
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM product_attributes WHERE attribute_id=?");
        $stmt->execute([$attribute_id]);
        if ($stmt->fetchColumn() > 0)
            throw new Exception("لا يمكن حذف الخاصية لأنها مرتبطة بمنتجات");

        $pdo->prepare("DELETE FROM attribute_values WHERE attribute_id=?")->execute([$attribute_id]);
        $pdo->prepare("DELETE FROM attributes WHERE id=?")->execute([$attribute_id]);
        $_SESSION['message'] = "تم حذف الخاصية بنجاح";
        header("Location: manage_categories.php"); exit;
    } catch (Exception $e) {
        $_SESSION['error_message'] = "خطأ أثناء الحذف: " . $e->getMessage();
    }
}

// ============================================
// جلب البيانات
// ============================================
$search_cat  = trim($_GET['search_cat']  ?? '');
$search_attr = trim($_GET['search_attr'] ?? '');

// الفئات مع عدد المنتجات
$catSql = "
    SELECT c.*, COUNT(p.id) AS products_count
    FROM categories c
    LEFT JOIN products p ON c.id = p.category_id
    WHERE 1=1
";
$catParams = [];
if (!empty($search_cat)) {
    $catSql .= " AND c.name LIKE :sc";
    $catParams[':sc'] = '%' . $search_cat . '%';
}
$catSql .= " GROUP BY c.id ORDER BY c.name";
$stmt = $pdo->prepare($catSql);
foreach ($catParams as $k => $v) $stmt->bindValue($k, $v);
$stmt->execute();
$categories = $stmt->fetchAll();

// الخصائص
$attrSql = "SELECT * FROM attributes WHERE 1=1";
$attrParams = [];
if (!empty($search_attr)) {
    $attrSql .= " AND name LIKE :sa";
    $attrParams[':sa'] = '%' . $search_attr . '%';
}
$attrSql .= " ORDER BY name";
$stmt = $pdo->prepare($attrSql);
foreach ($attrParams as $k => $v) $stmt->bindValue($k, $v);
$stmt->execute();
$attributes = $stmt->fetchAll();

// قيم الخصائص
$attributeValues = [];
foreach ($attributes as $attr) {
    $stmt = $pdo->prepare("SELECT * FROM attribute_values WHERE attribute_id=?");
    $stmt->execute([$attr['id']]);
    $attributeValues[$attr['id']] = $stmt->fetchAll();
}
?>
<!DOCTYPE html>
<html dir="rtl" lang="ar">
    <?php include __DIR__ . '/darkmode.php'; ?>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>إدارة الفئات والخصائص</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;700;800;900&display=swap" rel="stylesheet">
    <?php include __DIR__ . '/pwa_head.php'; ?>

<style>
:root {
    --primary:      #1E40AF;
    --primary-l:    #3B82F6;
    --primary-d:    #1E3A8A;
    --success:      #059669;
    --success-l:    #D1FAE5;
    --danger:       #DC2626;
    --danger-l:     #FEE2E2;
    --warning:      #D97706;
    --warning-l:    #FEF3C7;
    --info:         #0284C7;
    --info-l:       #E0F2FE;
    --purple:       #7C3AED;
    --purple-l:     #EDE9FE;
    --bg:           #F1F5F9;
    --surface:      #FFFFFF;
    --surface-2:    #F8FAFC;
    --border:       #E2E8F0;
    --text:         #0F172A;
    --text-2:       #475569;
    --text-3:       #94A3B8;
    --shadow-sm:    0 1px 3px rgba(0,0,0,0.06);
    --shadow-md:    0 4px 16px rgba(0,0,0,0.08);
    --shadow-lg:    0 10px 40px rgba(0,0,0,0.12);
    --radius:       14px;
    --radius-sm:    8px;
    --tr:           all 0.22s cubic-bezier(0.4,0,0.2,1);
}
*,*::before,*::after{margin:0;padding:0;box-sizing:border-box;font-family:'Tajawal',sans-serif}
body{background:var(--bg);color:var(--text);padding:20px;min-height:100vh}
::-webkit-scrollbar{width:5px;height:5px}
::-webkit-scrollbar-track{background:#f1f5f9}
::-webkit-scrollbar-thumb{background:var(--primary-l);border-radius:10px}
.container{max-width:1300px;margin:0 auto}

/* HEADER */
.header{
    display:flex;justify-content:space-between;align-items:center;
    padding:18px 24px;background:var(--surface);border-radius:var(--radius);
    box-shadow:var(--shadow-sm);border:1px solid var(--border);
    margin-bottom:22px;animation:fadeDown 0.4s ease;
}
@keyframes fadeDown{from{opacity:0;transform:translateY(-12px)}to{opacity:1;transform:translateY(0)}}
.header h1{color:var(--primary);font-size:21px;font-weight:900;display:flex;align-items:center;gap:10px}
.header h1 .icon-wrap{background:linear-gradient(135deg,var(--primary),var(--primary-l));color:white;width:38px;height:38px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:16px}

/* MESSAGES */
.msg{padding:13px 18px;border-radius:var(--radius-sm);display:flex;align-items:center;gap:10px;font-weight:600;margin-bottom:18px;animation:slideIn 0.3s ease}
@keyframes slideIn{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}
.msg-success{background:var(--success-l);color:var(--success);border:1px solid #A7F3D0}
.msg-error  {background:var(--danger-l);color:var(--danger);border:1px solid #FECACA}

/* CARD */
.card{
    background:var(--surface);border-radius:var(--radius);
    box-shadow:var(--shadow-sm);border:1px solid var(--border);
    padding:20px;margin-bottom:22px;animation:fadeUp 0.4s ease both;
}
@keyframes fadeUp{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}
.card-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:18px;flex-wrap:wrap;gap:12px}
.card-title{font-size:16px;font-weight:900;color:var(--text);display:flex;align-items:center;gap:8px}
.card-title i{color:var(--primary)}

/* SEARCH */
.search-bar{display:flex;border-radius:var(--radius-sm);overflow:hidden;border:1.5px solid var(--border);transition:var(--tr);max-width:280px}
.search-bar:focus-within{border-color:var(--primary-l);box-shadow:0 0 0 3px rgba(59,130,246,0.12)}
.search-bar input{flex:1;padding:9px 13px;border:none;outline:none;font-size:13px;color:var(--text);font-family:'Tajawal',sans-serif}
.search-bar button{padding:0 14px;background:var(--primary);color:white;border:none;cursor:pointer;transition:var(--tr);font-size:13px}
.search-bar button:hover{background:var(--primary-d)}

/* TABLE */
.table-wrap{overflow-x:auto;border-radius:var(--radius-sm);border:1px solid var(--border)}
table{width:100%;border-collapse:collapse;font-size:13px}
th{background:linear-gradient(135deg,var(--primary),var(--primary-d));color:white;padding:13px 14px;text-align:right;font-weight:700;font-size:12px;white-space:nowrap}
th:first-child{border-radius:var(--radius-sm) 0 0 0}
th:last-child{border-radius:0 var(--radius-sm) 0 0}
td{padding:12px 14px;border-bottom:1px solid #F1F5F9;color:var(--text-2);vertical-align:middle}
tr:last-child td{border-bottom:none}
tr{transition:var(--tr)}
tr:hover td{background:#F8FAFC}
td:first-child{font-weight:800;color:var(--text)}

/* EMPTY STATE */
.empty{text-align:center;padding:40px 20px;color:var(--text-3)}
.empty i{font-size:40px;margin-bottom:10px;display:block}
.empty p{font-size:14px}

/* BADGES */
.badge{padding:4px 10px;border-radius:20px;font-size:11px;font-weight:800;display:inline-flex;align-items:center;gap:4px;white-space:nowrap}
.b-primary{background:#EFF6FF;color:var(--primary);border:1px solid #BFDBFE}
.b-success{background:var(--success-l);color:var(--success);border:1px solid #A7F3D0}
.b-danger {background:var(--danger-l);color:var(--danger);border:1px solid #FECACA}
.b-warning{background:var(--warning-l);color:var(--warning);border:1px solid #FDE68A}
.b-purple {background:var(--purple-l);color:var(--purple);border:1px solid #DDD6FE}
.b-info   {background:var(--info-l);color:var(--info);border:1px solid #BAE6FD}

.values-wrap{display:flex;flex-wrap:wrap;gap:4px}

/* COUNT BADGE */
.count-badge{display:inline-flex;align-items:center;justify-content:center;min-width:24px;height:24px;padding:0 6px;border-radius:20px;font-size:12px;font-weight:800}

/* BUTTONS */
.btn{padding:9px 15px;border-radius:var(--radius-sm);font-weight:700;cursor:pointer;transition:var(--tr);text-decoration:none;display:inline-flex;align-items:center;gap:6px;font-size:13px;border:none;letter-spacing:0.2px}
.btn-sm{padding:6px 11px;font-size:12px}
.btn-primary      {background:var(--primary);color:white}
.btn-primary:hover{background:var(--primary-d);transform:translateY(-1px);box-shadow:0 4px 14px rgba(30,64,175,0.3)}
.btn-success      {background:var(--success);color:white}
.btn-success:hover{background:#047857;transform:translateY(-1px)}
.btn-danger       {background:var(--danger);color:white}
.btn-danger:hover {background:#B91C1C;transform:translateY(-1px)}
.btn-gray         {background:var(--surface-2);color:var(--text-2);border:1.5px solid var(--border)}
.btn-gray:hover   {background:var(--border)}

/* ACTION BUTTONS */
.action-btns{display:flex;gap:5px;flex-wrap:nowrap}

/* MODAL */
.modal{display:none;position:fixed;inset:0;z-index:1000;background:rgba(15,23,42,0.55);align-items:center;justify-content:center;backdrop-filter:blur(4px);padding:20px}
.modal-content{background:white;padding:28px;border-radius:var(--radius);width:90%;max-width:560px;max-height:90vh;overflow-y:auto;box-shadow:var(--shadow-lg);animation:modalIn 0.25s ease}
@keyframes modalIn{from{opacity:0;transform:scale(0.96) translateY(-10px)}to{opacity:1;transform:scale(1) translateY(0)}}
.modal-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:22px;padding-bottom:16px;border-bottom:1.5px solid var(--border)}
.modal-title{color:var(--primary);font-size:18px;font-weight:900;display:flex;align-items:center;gap:8px}
.modal-close{width:32px;height:32px;display:flex;align-items:center;justify-content:center;border-radius:50%;font-size:20px;cursor:pointer;color:var(--text-3);background:var(--surface-2);border:1px solid var(--border);transition:var(--tr)}
.modal-close:hover{background:var(--danger-l);color:var(--danger)}
.modal-footer{display:flex;justify-content:flex-end;gap:10px;margin-top:22px;padding-top:16px;border-top:1px solid var(--border)}

/* FORM */
.form-group{margin-bottom:16px}
.form-group label{display:block;margin-bottom:6px;font-weight:700;font-size:13px;color:var(--text)}
.form-group input,.form-group select,.form-group textarea{
    width:100%;padding:11px 14px;border:1.5px solid var(--border);
    border-radius:var(--radius-sm);font-size:14px;transition:var(--tr);
    font-family:'Tajawal',sans-serif;color:var(--text);background:white;
}
.form-group input:focus,.form-group select:focus,.form-group textarea:focus{
    border-color:var(--primary-l);outline:none;box-shadow:0 0 0 3px rgba(59,130,246,0.12);
}
.form-hint{font-size:11px;color:var(--text-3);margin-top:5px}
.checkbox-wrap{display:flex;align-items:center;gap:10px;padding:10px 14px;background:var(--surface-2);border-radius:var(--radius-sm);border:1.5px solid var(--border);cursor:pointer;transition:var(--tr)}
.checkbox-wrap:hover{border-color:var(--primary-l)}
.checkbox-wrap input[type=checkbox]{width:18px;height:18px;cursor:pointer;accent-color:var(--primary)}
.checkbox-wrap span{font-size:14px;font-weight:600;color:var(--text)}

/* VALUES PREVIEW */
#valuesPreview{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px;min-height:10px}

/* TABS */
.tabs{display:flex;gap:4px;background:var(--surface-2);padding:4px;border-radius:10px;border:1px solid var(--border);margin-bottom:0;width:fit-content}
.tab-btn{padding:8px 18px;border-radius:8px;border:none;background:transparent;font-size:13px;font-weight:700;color:var(--text-3);cursor:pointer;transition:var(--tr);font-family:'Tajawal',sans-serif}
.tab-btn.active{background:white;color:var(--primary);box-shadow:var(--shadow-sm)}
.tab-content{display:none}
.tab-content.active{display:block}

@media(max-width:768px){
    body{padding:12px}
    .header{flex-direction:column;align-items:flex-start;gap:12px}
    .card-header{flex-direction:column;align-items:flex-start}
    .search-bar{max-width:100%}
    .action-btns{flex-wrap:wrap}
}
</style>
</head>
<body>
<button onclick="toggleSidebar()" style="position:fixed;top:15px;right:15px;z-index:900;background:var(--primary);color:white;border:none;padding:10px 13px;border-radius:var(--radius-sm);cursor:pointer;display:flex;align-items:center" title="القائمة">
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
</button>
<div class="sidebar-overlay" onclick="toggleSidebar()"></div>
<?php include 'sidebar.php'; ?>
<div class="container">

    <!-- HEADER -->
    <div class="header">
        <h1>
            <span class="icon-wrap"><i class="fas fa-tags"></i></span>
            إدارة الفئات والخصائص
        </h1>
        <a href="index.php" class="btn btn-gray"><i class="fas fa-arrow-right"></i> رجوع</a>
    </div>

    <!-- MESSAGES -->
    <?php if (isset($_SESSION['message'])): ?>
        <div class="msg msg-success"><i class="fas fa-check-circle"></i> <?= htmlspecialchars($_SESSION['message']) ?></div>
        <?php unset($_SESSION['message']); ?>
    <?php endif; ?>
    <?php if (isset($_SESSION['error_message'])): ?>
        <div class="msg msg-error"><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($_SESSION['error_message']) ?></div>
        <?php unset($_SESSION['error_message']); ?>
    <?php endif; ?>

    <!-- ========== الفئات ========== -->
    <div class="card" style="animation-delay:0.05s">
        <div class="card-header">
            <div class="card-title">
                <i class="fas fa-folder-open"></i>
                الفئات
                <span class="badge b-primary"><?= count($categories) ?></span>
            </div>
            <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center">
                <form method="GET" class="search-bar">
                    <?php if (!empty($search_attr)): ?>
                    <input type="hidden" name="search_attr" value="<?= htmlspecialchars($search_attr) ?>">
                    <?php endif; ?>
                    <input type="text" name="search_cat" placeholder="بحث في الفئات..." value="<?= htmlspecialchars($search_cat) ?>">
                    <button type="submit"><i class="fas fa-search"></i></button>
                </form>
                <button class="btn btn-primary" onclick="openCatModal()">
                    <i class="fas fa-plus"></i> إضافة فئة
                </button>
            </div>
        </div>

        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th>#</th>
                        <th>اسم الفئة</th>
                        <th>الوصف</th>
                        <th>المنتجات</th>
                        <th>تاريخ الإضافة</th>
                        <th>الإجراءات</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($categories)): ?>
                    <tr><td colspan="6">
                        <div class="empty"><i class="fas fa-folder-open"></i><p>لا توجد فئات<?= !empty($search_cat) ? ' تطابق البحث' : '' ?></p></div>
                    </td></tr>
                <?php else: ?>
                    <?php foreach ($categories as $cat): ?>
                    <tr>
                        <td>#<?= $cat['id'] ?></td>
                        <td><?= htmlspecialchars($cat['name']) ?></td>
                        <td style="color:var(--text-3);font-size:12px"><?= htmlspecialchars($cat['description'] ?? '---') ?></td>
                        <td>
                            <?php if ($cat['products_count'] > 0): ?>
                                <span class="count-badge b-success"><?= $cat['products_count'] ?> منتج</span>
                            <?php else: ?>
                                <span class="count-badge b-warning">0</span>
                            <?php endif; ?>
                        </td>
                        <td style="font-size:12px;color:var(--text-3);white-space:nowrap">
                            <?= isset($cat['created_at']) ? date('Y-m-d', strtotime($cat['created_at'])) : '---' ?>
                        </td>
                        <td>
                            <div class="action-btns">
                                <button class="btn btn-success btn-sm"
                                    onclick="openCatModal(<?= $cat['id'] ?>, '<?= htmlspecialchars($cat['name'], ENT_QUOTES) ?>', '<?= htmlspecialchars($cat['description'] ?? '', ENT_QUOTES) ?>')">
                                    <i class="fas fa-edit"></i> تعديل
                                </button>
                                <form method="POST" style="display:inline" onsubmit="return confirm('حذف الفئة «<?= htmlspecialchars($cat['name'], ENT_QUOTES) ?>»؟')">
                                    <input type="hidden" name="delete_category" value="<?= $cat['id'] ?>">
                                    <button type="submit" class="btn btn-danger btn-sm"
                                        <?= $cat['products_count'] > 0 ? 'disabled title="مرتبطة بمنتجات"' : '' ?>>
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </form>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- ========== الخصائص ========== -->
    <div class="card" style="animation-delay:0.1s">
        <div class="card-header">
            <div class="card-title">
                <i class="fas fa-sliders-h"></i>
                الخصائص
                <span class="badge b-purple"><?= count($attributes) ?></span>
            </div>
            <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center">
                <form method="GET" class="search-bar">
                    <?php if (!empty($search_cat)): ?>
                    <input type="hidden" name="search_cat" value="<?= htmlspecialchars($search_cat) ?>">
                    <?php endif; ?>
                    <input type="text" name="search_attr" placeholder="بحث في الخصائص..." value="<?= htmlspecialchars($search_attr) ?>">
                    <button type="submit"><i class="fas fa-search"></i></button>
                </form>
                <button class="btn btn-primary" onclick="openAttrModal()">
                    <i class="fas fa-plus"></i> إضافة خاصية
                </button>
            </div>
        </div>

        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th>#</th>
                        <th>اسم الخاصية</th>
                        <th>نوع الإدخال</th>
                        <th>إلزامي</th>
                        <th>القيم الممكنة</th>
                        <th>الإجراءات</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($attributes)): ?>
                    <tr><td colspan="6">
                        <div class="empty"><i class="fas fa-sliders-h"></i><p>لا توجد خصائص<?= !empty($search_attr) ? ' تطابق البحث' : '' ?></p></div>
                    </td></tr>
                <?php else: ?>
                    <?php foreach ($attributes as $attr): ?>
                    <tr>
                        <td>#<?= $attr['id'] ?></td>
                        <td><?= htmlspecialchars($attr['name']) ?></td>
                        <td>
                            <?php if ($attr['input_type'] === 'select'): ?>
                                <span class="badge b-primary"><i class="fas fa-list"></i> قائمة منسدلة</span>
                            <?php else: ?>
                                <span class="badge b-info"><i class="fas fa-font"></i> حقل نصي</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($attr['is_required']): ?>
                                <span class="badge b-danger"><i class="fas fa-asterisk"></i> إلزامي</span>
                            <?php else: ?>
                                <span class="badge b-success">اختياري</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($attr['input_type'] === 'select' && !empty($attributeValues[$attr['id']])): ?>
                                <div class="values-wrap">
                                    <?php foreach (array_slice($attributeValues[$attr['id']], 0, 5) as $v): ?>
                                        <span class="badge b-purple"><?= htmlspecialchars($v['value']) ?></span>
                                    <?php endforeach; ?>
                                    <?php if (count($attributeValues[$attr['id']]) > 5): ?>
                                        <span class="badge b-warning">+<?= count($attributeValues[$attr['id']]) - 5 ?></span>
                                    <?php endif; ?>
                                </div>
                            <?php else: ?>
                                <span style="color:var(--text-3);font-size:12px">---</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="action-btns">
                                <button class="btn btn-success btn-sm"
                                    onclick="openAttrModal(<?= $attr['id'] ?>,'<?= htmlspecialchars($attr['name'],ENT_QUOTES) ?>','<?= $attr['input_type'] ?>','<?= htmlspecialchars($attr['values_list']??'',ENT_QUOTES) ?>',<?= $attr['is_required'] ?>)">
                                    <i class="fas fa-edit"></i> تعديل
                                </button>
                                <form method="POST" style="display:inline" onsubmit="return confirm('حذف الخاصية «<?= htmlspecialchars($attr['name'],ENT_QUOTES) ?>»؟')">
                                    <input type="hidden" name="delete_attribute" value="<?= $attr['id'] ?>">
                                    <button type="submit" class="btn btn-danger btn-sm">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </form>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

</div><!-- /container -->

<!-- ========== MODAL الفئة ========== -->
<div id="catModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <div class="modal-title"><i class="fas fa-folder"></i> <span id="catModalTitle">إضافة فئة جديدة</span></div>
            <button class="modal-close" onclick="closeCatModal()">×</button>
        </div>
        <form method="POST">
            <input type="hidden" name="category_id" id="catId">
            <div class="form-group">
                <label>اسم الفئة <span style="color:var(--danger)">*</span></label>
                <input type="text" name="name" id="catName" required placeholder="مثال: إلكترونيات">
            </div>
            <div class="form-group">
                <label>الوصف <span style="color:var(--text-3);font-weight:400">(اختياري)</span></label>
                <textarea name="description" id="catDesc" rows="3" placeholder="وصف مختصر للفئة..."></textarea>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-gray" onclick="closeCatModal()">إلغاء</button>
                <button type="submit" name="save_category" class="btn btn-success"><i class="fas fa-save"></i> حفظ</button>
            </div>
        </form>
    </div>
</div>

<!-- ========== MODAL الخاصية ========== -->
<div id="attrModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <div class="modal-title"><i class="fas fa-sliders-h"></i> <span id="attrModalTitle">إضافة خاصية جديدة</span></div>
            <button class="modal-close" onclick="closeAttrModal()">×</button>
        </div>
        <form method="POST">
            <input type="hidden" name="attribute_id" id="attrId">
            <div class="form-group">
                <label>اسم الخاصية <span style="color:var(--danger)">*</span></label>
                <input type="text" name="name" id="attrName" required placeholder="مثال: اللون، المقاس">
            </div>
            <div class="form-group">
                <label>نوع الإدخال</label>
                <select name="input_type" id="attrInputType" onchange="toggleValues()">
                    <option value="text">حقل نصي</option>
                    <option value="select">قائمة منسدلة</option>
                </select>
            </div>
            <div class="form-group" id="valuesGroup" style="display:none">
                <label>القيم الممكنة <span style="color:var(--danger)">*</span></label>
                <textarea name="values_list" id="attrValues" rows="3"
                    placeholder="أحمر,أخضر,أزرق,أصفر"
                    oninput="updatePreview()"></textarea>
                <div class="form-hint">افصل القيم بفاصلة ( , )</div>
                <div id="valuesPreview"></div>
            </div>
            <div class="form-group">
                <label class="checkbox-wrap" for="attrRequired">
                    <input type="checkbox" name="is_required" id="attrRequired">
                    <span>إلزامي — يجب على العميل اختياره</span>
                </label>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-gray" onclick="closeAttrModal()">إلغاء</button>
                <button type="submit" name="save_attribute" class="btn btn-success"><i class="fas fa-save"></i> حفظ</button>
            </div>
        </form>
    </div>
</div>

<script>
// ===== CATEGORY MODAL =====
function openCatModal(id=null, name='', desc='') {
    document.getElementById('catModalTitle').textContent = id ? 'تعديل الفئة' : 'إضافة فئة جديدة';
    document.getElementById('catId').value   = id || '';
    document.getElementById('catName').value = name;
    document.getElementById('catDesc').value = desc;
    document.getElementById('catModal').style.display = 'flex';
}
function closeCatModal() { document.getElementById('catModal').style.display = 'none'; }

// ===== ATTRIBUTE MODAL =====
function openAttrModal(id=null, name='', inputType='text', values='', required=false) {
    document.getElementById('attrModalTitle').textContent = id ? 'تعديل الخاصية' : 'إضافة خاصية جديدة';
    document.getElementById('attrId').value        = id || '';
    document.getElementById('attrName').value      = name;
    document.getElementById('attrInputType').value = inputType;
    document.getElementById('attrValues').value    = values;
    document.getElementById('attrRequired').checked = !!required;
    toggleValues();
    updatePreview();
    document.getElementById('attrModal').style.display = 'flex';
}
function closeAttrModal() { document.getElementById('attrModal').style.display = 'none'; }

function toggleValues() {
    const isSelect = document.getElementById('attrInputType').value === 'select';
    document.getElementById('valuesGroup').style.display = isSelect ? 'block' : 'none';
}

function updatePreview() {
    const raw = document.getElementById('attrValues').value;
    const preview = document.getElementById('valuesPreview');
    if (!raw.trim()) { preview.innerHTML = ''; return; }
    const vals = raw.split(',').map(v => v.trim()).filter(v => v);
    const colors = ['b-primary','b-purple','b-success','b-info','b-warning'];
    preview.innerHTML = vals.map((v,i) =>
        `<span class="badge ${colors[i % colors.length]}">${escHtml(v)}</span>`
    ).join('');
}

function escHtml(t) {
    var d = document.createElement('div');
    d.textContent = t;
    return d.innerHTML;
}

// إغلاق عند النقر خارج الـ modal
window.onclick = function(e) {
    if (e.target.id === 'catModal')  closeCatModal();
    if (e.target.id === 'attrModal') closeAttrModal();
};

// Escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') { closeCatModal(); closeAttrModal(); }
});
</script>
</body>
</html>