<?php
// admin/features.php — نسخة مُحسّنة مع جدول صفّ واحد + منتقي أيقونات حي
require_once "../config/db.php";
require_once "../includes/auth.php";
include "partials/header.php";
// TODO: حماية جلسة المشرف
// session_start(); if (empty($_SESSION['admin'])) { header('Location: login.php'); exit; }

/* ===== إنشاء الجدول ===== */
db()->exec("
CREATE TABLE IF NOT EXISTS features (
  id INT AUTO_INCREMENT PRIMARY KEY,
  title VARCHAR(200) NOT NULL,
  description TEXT,
  items TEXT,
  icon VARCHAR(80) DEFAULT 'fa-gem',
  sort INT DEFAULT 0,
  status TINYINT(1) DEFAULT 1,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

// بداية الجلسة بشكل آمن
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
$csrf = $_SESSION['csrf'];

/* ===== عمليات ===== */
$msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['csrf']) && hash_equals($_SESSION['csrf'], $_POST['csrf'])) {
  $action = $_POST['action'] ?? '';
  if ($action === 'create') {
    $title = trim($_POST['title'] ?? '');
    $desc  = trim($_POST['description'] ?? '');
    $items = trim($_POST['items'] ?? '');
    $icon  = trim($_POST['icon'] ?? 'fa-gem');           // نخزّن class مختصر لـ FA: fa-gem
    $sort  = (int)($_POST['sort'] ?? 0);
    $status= (int)($_POST['status'] ?? 1);
    if ($title) {
      db()->prepare("INSERT INTO features(title,description,items,icon,sort,status) VALUES (?,?,?,?,?,?)")
        ->execute([$title,$desc,$items,$icon,$sort,$status]);
      $msg = 'تمت إضافة البطاقة.';
    } else $msg = 'الرجاء إدخال العنوان.';
  }
  if ($action === 'update') {
    $id    = (int)($_POST['id'] ?? 0);
    $title = trim($_POST['title'] ?? '');
    $desc  = trim($_POST['description'] ?? '');
    $items = trim($_POST['items'] ?? '');
    $icon  = trim($_POST['icon'] ?? 'fa-gem');
    $sort  = (int)($_POST['sort'] ?? 0);
    $status= (int)($_POST['status'] ?? 1);
    if ($id && $title) {
      db()->prepare("UPDATE features SET title=?, description=?, items=?, icon=?, sort=?, status=? WHERE id=?")
        ->execute([$title,$desc,$items,$icon,$sort,$status,$id]);
      $msg = 'تم تحديث البطاقة.';
    }
  }
}
if (isset($_GET['delete'], $_GET['csrf']) && hash_equals($_SESSION['csrf'], $_GET['csrf'])) {
  db()->prepare("DELETE FROM features WHERE id=?")->execute([(int)$_GET['delete']]);
  $msg = 'تم حذف البطاقة.';
}

/* ===== جلب ===== */
$rows = db()->query("SELECT * FROM features ORDER BY sort, id DESC")->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<title>لوحة التحكم - ما يميزنا</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
  href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
@import url('https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;800&display=swap');
:root{
  --gold:#d4af37; --ink:#eaeaea; --muted:#9aa7b1; --bg:#0b0b0b; --card:#121212;
}
*{box-sizing:border-box}
html,body{background:var(--bg);color:var(--ink);margin:0;font-family:'Cairo',system-ui}
.wrap{width:min(1200px,95%);margin:28px auto}
h1{margin:0 0 16px;font-weight:900}
.card{background:var(--card);border:1px solid rgba(212,175,55,.45);border-radius:14px;padding:16px;box-shadow:0 12px 26px rgba(0,0,0,.35);margin-bottom:18px}
input,select,textarea{width:100%;padding:10px 12px;border-radius:10px;border:1px solid rgba(212,175,55,.35);background:#0f0f0f;color:#fff}
label{display:block;margin:8px 0 6px}
.grid{display:grid;gap:12px;grid-template-columns:1fr 1fr}
@media (max-width:820px){.grid{grid-template-columns:1fr}}
.btn{padding:10px 16px;border-radius:10px;border:0;cursor:pointer;font-weight:800;display:inline-flex;align-items:center;gap:8px}
.btn-gold{background:linear-gradient(145deg,#b68f2a,#d4af37,#c8a951);color:#111}
.btn-dark{background:#1f2937;color:#eaeaea;border:1px solid #374151}
.msg{margin-bottom:10px;color:#b8f7c8;background:#0f2a17;border:1px solid #1d7a41;padding:8px 10px;border-radius:8px}
.small{color:var(--muted);font-size:12px}

/* ===== جدول صفّ واحد ===== */
.tbl{width:100%;border-collapse:separate;border-spacing:0 10px}
.tbl thead th{
  color:var(--gold); font-weight:800; text-align:right; padding:10px;
  border-bottom:1px solid rgba(212,175,55,.25); white-space:nowrap;
}
.tbl tbody tr{
  background:#151515;border:1px solid rgba(212,175,55,.25);
  border-radius:12px; box-shadow:0 8px 18px rgba(0,0,0,.35)
}
.tbl tbody td{
  padding:10px; vertical-align:middle; white-space:nowrap;
}
.tbl tbody tr > td:first-child{border-radius:12px 0 0 12px}
.tbl tbody tr > td:last-child{border-radius:0 12px 12px 0}

.text-clip{max-width:280px;overflow:hidden;text-overflow:ellipsis;display:inline-block;vertical-align:bottom}
.text-clip.lg{max-width:420px}
.chip{display:inline-block;padding:6px 10px;border-radius:999px;font-weight:800;font-size:.85rem;color:#0f0f0f;background:linear-gradient(145deg,#b68f2a,#d4af37,#c8a951)}
.badge{display:inline-flex;align-items:center;gap:8px;padding:6px 10px;border-radius:10px;background:#0b0b0b;color:#eaeaea;border:1px solid rgba(212,175,55,.35)}
.icon-preview{width:48px;height:48px;border-radius:12px;display:inline-grid;place-items:center;background:#0b0b0b;border:1px solid rgba(212,175,55,.35)}
.row-actions{display:flex;gap:6px}
.icon-btn{
  width:38px;height:38px;border-radius:10px;border:0;cursor:pointer;display:inline-grid;place-items:center
}
.icon-btn.view{background:#0b0b0b;color:#eaeaea;border:1px solid rgba(212,175,55,.35)}
.icon-btn.edit{background:linear-gradient(145deg,#f59e0b,#fbbf24);color:#0f0f0f}
.icon-btn.del{background:linear-gradient(145deg,#ef4444,#f87171);color:#0f0f0f}

/* ===== منتقي الأيقونات (Modal) ===== */
.modal{
  position:fixed;inset:0;background:rgba(0,0,0,.55);display:none;align-items:flex-start;justify-content:center;padding:40px 16px;z-index:50
}
.modal.show{display:flex}
.modal-card{
  width:min(900px,100%);background:#121212;border:1px solid rgba(212,175,55,.45);border-radius:16px;
  box-shadow:0 20px 60px rgba(0,0,0,.6);overflow:hidden
}
.modal-head{display:flex;align-items:center;justify-content:space-between;padding:14px 16px;border-bottom:1px solid rgba(212,175,55,.25)}
.modal-head h4{margin:0;color:#eaeaea}
.modal-body{padding:14px 16px}
.icon-search{display:flex;gap:10px;align-items:center;margin-bottom:12px}
.icon-search input{flex:1}
.icon-grid{display:grid;grid-template-columns:repeat(6,1fr);gap:10px}
@media(max-width:820px){.icon-grid{grid-template-columns:repeat(3,1fr)}}
.icon-card{
  border:1px solid rgba(212,175,55,.25);border-radius:12px;padding:16px;background:#0f0f0f;display:grid;place-items:center;cursor:pointer;
  transition:.15s
}
.icon-card:hover{transform:translateY(-2px);border-color:rgba(212,175,55,.6)}
.icon-card.selected{outline:2px solid var(--gold)}
.icon-card i{font-size:22px}
.icon-label{margin-top:8px;font-size:12px;color:#cbd5e1;text-align:center;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.modal-foot{padding:12px 16px;border-top:1px solid rgba(212,175,55,.25);display:flex;justify-content:flex-end;gap:10px}
</style>
</head>
<body>
<div class="wrap">
  <h1><i class="fa-solid fa-star"></i> إدارة ما يميزنا</h1>
  <?php if ($msg): ?><div class="msg"><?= htmlspecialchars($msg) ?></div><?php endif; ?>

  <!-- إضافة / تعديل -->
  <div class="card">
    <h3>إضافة بطاقة</h3>
    <form method="post" id="createForm">
      <input type="hidden" name="csrf" value="<?= $csrf ?>">
      <input type="hidden" name="action" value="create">
      <div class="grid">
        <div>
          <label>العنوان</label>
          <input name="title" required>
        </div>
        <div>
          <label>الأيقونة (Font Awesome class)</label>
          <div style="display:flex;gap:10px;align-items:center">
            <input id="icon-input" name="icon" value="fa-gem" placeholder="fa-shield-halved, fa-gem, ...">
            <button type="button" class="btn btn-dark" id="openIconPicker"><i class="fa-solid fa-icons"></i> اختيار</button>
            <div class="icon-preview" id="iconPreview"><i class="fas fa-gem"></i></div>
          </div>
          <div class="small">اكتب مثل: <b>fa-shield-halved</b> — سيُعرض كـ <b>&lt;i class="fas fa-shield-halved"&gt;</b>.</div>
        </div>
      </div>
      <div>
        <label>الوصف</label>
        <textarea name="description" rows="3"></textarea>
      </div>
      <div>
        <label>العناصر (سطر لكل نقطة)</label>
        <textarea name="items" rows="4" placeholder="النقطة الأولى&#10;النقطة الثانية&#10;..."></textarea>
      </div>
      <div class="grid">
        <div>
          <label>الترتيب</label>
          <input type="number" name="sort" value="0">
        </div>
        <div>
          <label>الحالة</label>
          <select name="status">
            <option value="1">مفعل</option>
            <option value="0">معطل</option>
          </select>
        </div>
      </div>
      <div style="margin-top:12px">
        <button class="btn btn-gold"><i class="fa-solid fa-plus"></i> إضافة</button>
      </div>
    </form>
  </div>

  <!-- القائمة -->
  <div class="card">
    <h3>القائمة</h3>
    <div style="overflow:auto">
      <table class="tbl" aria-label="قائمة ما يميزنا">
        <thead>
          <tr>
            <th>#</th>
            <th>الأيقونة</th>
            <th>العنوان</th>
            <th>الوصف</th>
            <th>العناصر</th>
            <th>الترتيب</th>
            <th>الحالة</th>
            <th>تحكم</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach($rows as $r): ?>
          <tr>
            <td><?= (int)$r['id'] ?></td>
            <td>
              <span class="badge">
                <i class="fas <?= htmlspecialchars($r['icon']) ?>"></i>
                <span class="small"><?= htmlspecialchars($r['icon']) ?></span>
              </span>
            </td>
            <td><span class="text-clip"><?= htmlspecialchars($r['title']) ?></span></td>
            <td><span class="text-clip lg" title="<?= htmlspecialchars($r['description']) ?>"><?= htmlspecialchars($r['description']) ?></span></td>
            <td>
              <?php
                $firstLine = trim(strtok((string)$r['items'], "\n"));
                $more = substr_count((string)$r['items'], "\n");
              ?>
              <span class="text-clip" title="<?= htmlspecialchars($r['items']) ?>">
                <?= htmlspecialchars($firstLine ?: '-') ?><?= $more ? " (+$more)" : '' ?>
              </span>
            </td>
            <td><span class="chip"><?= (int)$r['sort'] ?></span></td>
            <td><span class="chip" style="background:<?= $r['status']?'linear-gradient(145deg,#22c55e,#86efac)':'#30353b'; ?>;color:<?= $r['status']?'#0b1d10':'#e5e7eb' ?>">
              <?= $r['status']?'مفعل':'معطل' ?></span>
            </td>
            <td>
              <div class="row-actions">
                <a class="icon-btn view" href="../index.php#features" target="_blank" title="عرض"><i class="fa fa-eye"></i></a>
                <a class="icon-btn edit" href="?edit=<?= (int)$r['id'] ?>" title="تعديل"><i class="fa fa-pen"></i></a>
                <a class="icon-btn del" href="?delete=<?= (int)$r['id'] ?>&csrf=<?= $csrf ?>" title="حذف"
                   onclick="return confirm('حذف البطاقة نهائيًا؟');"><i class="fa fa-trash"></i></a>
              </div>
            </td>
          </tr>
          <?php endforeach; ?>
          <?php if (!$rows): ?><tr><td colspan="8" style="text-align:center;color:#aaa">لا توجد بيانات</td></tr><?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <?php if (isset($_GET['edit'])):
    $id = (int)$_GET['edit'];
    $row = db()->prepare("SELECT * FROM features WHERE id=?");
    $row->execute([$id]);
    $row = $row->fetch(PDO::FETCH_ASSOC);
    if ($row):
  ?>
  <div class="card">
    <h3>تعديل بطاقة #<?= (int)$row['id'] ?></h3>
    <form method="post" id="editForm">
      <input type="hidden" name="csrf" value="<?= $csrf ?>">
      <input type="hidden" name="action" value="update">
      <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">

      <div class="grid">
        <div>
          <label>العنوان</label>
          <input name="title" value="<?= htmlspecialchars($row['title']) ?>" required>
        </div>
        <div>
          <label>الأيقونة (Font Awesome class)</label>
          <div style="display:flex;gap:10px;align-items:center">
            <input id="icon-input-edit" name="icon" value="<?= htmlspecialchars($row['icon']) ?>">
            <button type="button" class="btn btn-dark" id="openIconPickerEdit"><i class="fa-solid fa-icons"></i> اختيار</button>
            <div class="icon-preview" id="iconPreviewEdit"><i class="fas <?= htmlspecialchars($row['icon']) ?>"></i></div>
          </div>
          <div class="small">أمثلة: fa-gem, fa-shield-halved, fa-certificate, fa-coins …</div>
        </div>
      </div>

      <div>
        <label>الوصف</label>
        <textarea name="description" rows="3"><?= htmlspecialchars($row['description']) ?></textarea>
      </div>
      <div>
        <label>العناصر (سطر لكل نقطة)</label>
        <textarea name="items" rows="4"><?= htmlspecialchars($row['items']) ?></textarea>
      </div>
      <div class="grid">
        <div>
          <label>الترتيب</label>
          <input type="number" name="sort" value="<?= (int)$row['sort'] ?>">
        </div>
        <div>
          <label>الحالة</label>
          <select name="status">
            <option value="1"<?= $row['status']?' selected':'' ?>>مفعل</option>
            <option value="0"<?= !$row['status']?' selected':'' ?>>معطل</option>
          </select>
        </div>
      </div>
      <div style="margin-top:12px">
        <button class="btn btn-gold"><i class="fa-solid fa-save"></i> حفظ</button>
        <a class="btn btn-dark" href="features.php">رجوع</a>
      </div>
    </form>
  </div>
  <?php endif; endif; ?>

</div>

<!-- Modal منتقي الأيقونات -->
<div class="modal" id="iconModal" aria-hidden="true">
  <div class="modal-card">
    <div class="modal-head">
      <h4>اختيار الأيقونة</h4>
      <button class="btn btn-dark" id="closeModal"><i class="fa-solid fa-xmark"></i> إغلاق</button>
    </div>
    <div class="modal-body">
      <div class="icon-search">
        <input type="text" id="iconSearch" placeholder="ابحث باسم الأيقونة... (مثال: gem, shield, crown)">
      </div>
      <div class="icon-grid" id="iconGrid">
        <!-- يتم حقن الأيقونات بالـ JS -->
      </div>
    </div>
    <div class="modal-foot">
      <button class="btn btn-gold" id="useSelected"><i class="fa-solid fa-check"></i> استخدام الأيقونة</button>
    </div>
  </div>
</div>

<script>
// ===== إعدادات منتقي الأيقونات (Font Awesome 6) =====
// قائمة منسّقة لأيقونات مناسبة لمجال الذهب والمجوهرات/الضمان/الجودة/الخدمة
const ICONS = [
  'fa-gem','fa-crown','fa-certificate','fa-shield-halved','fa-shield','fa-medal',
  'fa-hands-bubbles','fa-handshake','fa-star','fa-stars','fa-wand-magic-sparkles','fa-sparkles',
  'fa-award','fa-diamond','fa-ring','fa-coins','fa-scale-balanced','fa-vault','fa-lock','fa-unlock',
  'fa-truck-fast','fa-truck','fa-sack-dollar','fa-bag-shopping','fa-store','fa-building-columns',
  'fa-user-shield','fa-user-check','fa-people-group','fa-headset','fa-circle-check','fa-badge-check',
  'fa-bolt','fa-fire','fa-gauge-high','fa-seedling','fa-globe','fa-recycle','fa-cubes'
];

const modal = document.getElementById('iconModal');
const iconGrid = document.getElementById('iconGrid');
const iconSearch = document.getElementById('iconSearch');
const closeModalBtn = document.getElementById('closeModal');
const useSelectedBtn = document.getElementById('useSelected');

let currentTarget = null; // { inputEl, previewEl }
let selectedIcon = null;

// بناء بطاقات الأيقونات
function renderIcons(filter='') {
  iconGrid.innerHTML = '';
  const f = filter.trim().toLowerCase();
  ICONS.filter(k => !f || k.toLowerCase().includes(f))
       .forEach(k => {
         const card = document.createElement('div');
         card.className = 'icon-card';
         card.dataset.icon = k;
         card.innerHTML = `<i class="fas ${k}"></i><div class="icon-label">${k}</div>`;
         card.addEventListener('click', () => {
           document.querySelectorAll('.icon-card.selected').forEach(x=>x.classList.remove('selected'));
           card.classList.add('selected');
           selectedIcon = k;
         });
         iconGrid.appendChild(card);
       });
}
renderIcons();

iconSearch.addEventListener('input', e => renderIcons(e.target.value));

// فتح المودال (إنشاء)
document.getElementById('openIconPicker')?.addEventListener('click', () => {
  currentTarget = {
    inputEl: document.getElementById('icon-input'),
    previewEl: document.getElementById('iconPreview'),
  };
  selectedIcon = currentTarget.inputEl.value || 'fa-gem';
  renderIcons(iconSearch.value);
  // تمييز المحدد
  [...iconGrid.children].forEach(card => {
    if (card.dataset.icon === selectedIcon) card.classList.add('selected');
  });
  modal.classList.add('show');
});

// فتح المودال (تعديل)
document.getElementById('openIconPickerEdit')?.addEventListener('click', () => {
  currentTarget = {
    inputEl: document.getElementById('icon-input-edit'),
    previewEl: document.getElementById('iconPreviewEdit'),
  };
  selectedIcon = currentTarget.inputEl.value || 'fa-gem';
  renderIcons(iconSearch.value);
  [...iconGrid.children].forEach(card => {
    if (card.dataset.icon === selectedIcon) card.classList.add('selected');
  });
  modal.classList.add('show');
});

// إغلاق/تأكيد
closeModalBtn.addEventListener('click', () => modal.classList.remove('show'));
useSelectedBtn.addEventListener('click', () => {
  if (!currentTarget || !selectedIcon) { modal.classList.remove('show'); return; }
  currentTarget.inputEl.value = selectedIcon;
  currentTarget.previewEl.innerHTML = `<i class="fas ${selectedIcon}"></i>`;
  modal.classList.remove('show');
});

// معاينة حيّة عند الكتابة اليدوية
document.getElementById('icon-input')?.addEventListener('input', (e)=>{
  document.getElementById('iconPreview').innerHTML = `<i class="fas ${e.target.value}"></i>`;
});
document.getElementById('icon-input-edit')?.addEventListener('input', (e)=>{
  document.getElementById('iconPreviewEdit').innerHTML = `<i class="fas ${e.target.value}"></i>`;
});
</script>
</body>
</html>
<?php include "partials/footer.php"; ?>
