<?php
require_once __DIR__ . '/../core/auth.php';
require_login();

$pdo = db();
$success = $error = "";
// الإحصائيات
$totalGroups = $pdo->query("SELECT COUNT(*) FROM groups")->fetchColumn();
$totalPermissions = $pdo->query("SELECT COUNT(*) FROM permissions")->fetchColumn();
/* ==============================
   1. إدارة المجموعات
   ============================== */
if (isset($_POST['action']) && $_POST['action'] === "group") {
    $id   = $_POST['id'] ?? null;
    $name = trim($_POST['name'] ?? '');

    if ($name === '') {
        $error = "❌ برجاء إدخال اسم المجموعة";
    } else {
        try {
            if ($id) {
                $stmt = $pdo->prepare("UPDATE groups SET name=? WHERE id=?");
                $stmt->execute([$name, $id]);
                $success = "✅ تم تعديل المجموعة بنجاح";
            } else {
                $stmt = $pdo->prepare("INSERT INTO groups (name) VALUES (?)");
                $stmt->execute([$name]);
                $success = "✅ تم إضافة المجموعة بنجاح";
            }
        } catch (PDOException $e) {
            $error = "⚠️ خطأ: " . $e->getMessage();
        }
    }
}
if (isset($_GET['delete_group'])) {
    $id = (int) $_GET['delete_group'];
    $pdo->prepare("DELETE FROM groups WHERE id=?")->execute([$id]);
    $success = "🗑️ تم حذف المجموعة";
}

/* ==============================
   2. إدارة الصفحات
   ============================== */
if (isset($_POST['action']) && $_POST['action'] === "page") {
    $id   = $_POST['pid'] ?? null;
    $page = trim($_POST['page'] ?? '');

    if ($page === '') {
        $error = "❌ برجاء إدخال اسم الصفحة";
    } else {
        try {
            if ($id) {
                $stmt = $pdo->prepare("UPDATE permissions SET page=? WHERE id=?");
                $stmt->execute([$page, $id]);
                $success = "✅ تم تعديل الصفحة بنجاح";
            } else {
                $stmt = $pdo->prepare("INSERT INTO permissions (page) VALUES (?)");
                $stmt->execute([$page]);
                $success = "✅ تم إضافة الصفحة بنجاح";
            }
        } catch (PDOException $e) {
            $error = "⚠️ خطأ: " . $e->getMessage();
        }
    }
}
if (isset($_GET['delete_page'])) {
    $id = (int) $_GET['delete_page'];
    $pdo->prepare("DELETE FROM permissions WHERE id=?")->execute([$id]);
    $success = "🗑️ تم حذف الصفحة";
}

/* ==============================
   3. تحديث صلاحيات مجموعة
   ============================== */
if (isset($_POST['action']) && $_POST['action'] === "permissions") {
    $group_id = (int) $_POST['group_id'];
    $pdo->prepare("DELETE FROM group_permissions WHERE group_id=?")->execute([$group_id]);

    if (!empty($_POST['permissions'])) {
        $stmt = $pdo->prepare("INSERT INTO group_permissions (group_id, permission_id) VALUES (?, ?)");
        foreach ($_POST['permissions'] as $pid) {
            $stmt->execute([$group_id, $pid]);
        }
    }
    $success = "✅ تم تحديث صلاحيات المجموعة";
}

/* ==============================
   4. جلب البيانات
   ============================== */
$groups = $pdo->query("SELECT * FROM groups ORDER BY id ASC")->fetchAll();
$pages  = $pdo->query("SELECT * FROM permissions ORDER BY id ASC")->fetchAll();
$group_perms = [];
$stmt = $pdo->query("SELECT * FROM group_permissions");
foreach ($stmt as $row) {
    $group_perms[$row['group_id']][] = $row['permission_id'];
}
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8">
  <title>إدارة المجموعات والصلاحيات</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body { font-family:"Tajawal",sans-serif; background:#f8f9fa; }
    .card { border-radius:12px; box-shadow:0 4px 10px rgba(0,0,0,0.1); margin-bottom:25px; }
    .card-header { background:linear-gradient(135deg,#0f2027,#203a43,#2c5364); color:#fff; font-weight:bold; }
    .btn-custom { border-radius:25px; }
  </style>
</head>
<body>

<div class="container py-4">
<header class="mb-4">
  <div class="d-flex justify-content-between align-items-center p-3 bg-dark text-white shadow-sm">
    <!-- يمين: بيانات المستخدم -->
    <div class="d-flex align-items-center gap-2">
        <img src="uploads/<?= htmlspecialchars($_SESSION['avatar'] ?? 'default.png') ?>" 
            alt="Avatar" 
            class="rounded-circle border border-2 border-light"
            style="width:40px;height:40px;object-fit:cover;">
            
        <span class="fw-bold"><?= htmlspecialchars($_SESSION['admin_username'] ?? 'Admin') ?></span>
        
        <a href="logout.php" class="btn btn-sm btn-outline-light">خروج</a>
    </div>


    <!-- وسط: عنوان الصفحة -->
    <h1 class="h5 m-0">👥 إدارة المجاميع و الصلاحيات</h1>

    <!-- شمال: زر الوضع الليلي -->
    <button id="darkSwitch" class="btn btn-sm btn-success">🌙</button>
  </div>
</header>
<div class="text-end mb-3">
  <a href="dashboard.php" class="btn btn-secondary">
    <i class="fa-solid fa-house"></i> الرئيسية
  </a>
</div>
    <!-- كروت الإحصائيات -->
    <div class="row text-center mb-4">
  <div class="col-md-4 mb-3">
    <div class="card text-white shadow" style="background:linear-gradient(135deg,#3498db,#2c3e50);">
      <div class="card-body">
        <h5><i class="fa-solid fa-users-gear"></i> عدد المجموعات</h5>
        <h2><?= $totalGroups ?></h2>
      </div>
    </div>
  </div>

  <div class="col-md-4 mb-3">
    <div class="card text-white shadow" style="background:linear-gradient(135deg,#1abc9c,#145a32);">
      <div class="card-body">
        <h5><i class="fa-solid fa-key"></i> عدد الصلاحيات</h5>
        <h2><?= $totalPermissions ?></h2>
      </div>
    </div>
  </div>


</div>
  <?php if ($success): ?>
    <div class="alert alert-success text-center"><?= $success ?></div>
  <?php elseif ($error): ?>
    <div class="alert alert-danger text-center"><?= $error ?></div>
  <?php endif; ?>

  <!-- قسم المجموعات -->
  <div class="card">
    <div class="card-header">👥 إدارة مجموعات الصلاحيات</div>
    <div class="card-body">
      <form method="post" class="row g-3 mb-4">
        <input type="hidden" name="action" value="group">
        <input type="hidden" name="id" id="group_id">
        <div class="col-md-8">
          <input type="text" name="name" id="group_name" class="form-control" placeholder="اسم المجموعة">
        </div>
        <div class="col-md-4 text-end">
          <button type="submit" class="btn btn-primary btn-custom px-4">💾 حفظ</button>
        </div>
      </form>

      <table class="table table-bordered text-center align-middle">
        <thead class="table-dark"><tr><th>#</th><th>اسم المجموعة</th><th>إجراءات</th></tr></thead>
        <tbody>
        <?php foreach ($groups as $g): ?>
          <tr>
            <td><?= $g['id'] ?></td>
            <td><?= htmlspecialchars($g['name']) ?></td>
            <td>
              <button class="btn btn-sm btn-warning" onclick="editGroup(<?= $g['id'] ?>,'<?= htmlspecialchars($g['name']) ?>')">✏️ تعديل</button>
              <a href="?delete_group=<?= $g['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('هل أنت متأكد من الحذف؟')">🗑️ حذف</a>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>

  <!-- قسم الصفحات -->
  <div class="card">
    <div class="card-header">📄 إدارة الصفحات (Permissions)</div>
    <div class="card-body">
      <form method="post" class="row g-3 mb-4">
        <input type="hidden" name="action" value="page">
        <input type="hidden" name="pid" id="page_id">
        <div class="col-md-8">
          <input type="text" name="page" id="page_name" class="form-control" placeholder="اسم الصفحة مثل items.php">
        </div>
        <div class="col-md-4 text-end">
          <button type="submit" class="btn btn-success btn-custom px-4">💾 حفظ</button>
        </div>
      </form>

      <table class="table table-bordered text-center align-middle">
        <thead class="table-dark"><tr><th>#</th><th>الصفحة</th><th>إجراءات</th></tr></thead>
        <tbody>
        <?php foreach ($pages as $p): ?>
          <tr>
            <td><?= $p['id'] ?></td>
            <td><?= htmlspecialchars($p['page']) ?></td>
            <td>
              <button class="btn btn-sm btn-warning" onclick="editPage(<?= $p['id'] ?>,'<?= htmlspecialchars($p['page']) ?>')">✏️ تعديل</button>
              <a href="?delete_page=<?= $p['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('هل أنت متأكد من الحذف؟')">🗑️ حذف</a>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>

  <!-- قسم صلاحيات المجموعات -->
  <div class="card">
    <div class="card-header">🔐 تخصيص صلاحيات المجموعات</div>
    <div class="card-body">
      <?php foreach ($groups as $g): ?>
        <form method="post" class="mb-4 border p-3 rounded bg-white shadow-sm">
          <input type="hidden" name="action" value="permissions">
          <input type="hidden" name="group_id" value="<?= $g['id'] ?>">
          <h5 class="mb-3"><?= htmlspecialchars($g['name']) ?></h5>
          <div class="row">
            <?php foreach ($pages as $p): ?>
              <div class="col-md-3 mb-2">
                <div class="form-check">
                  <input class="form-check-input" type="checkbox" 
                         name="permissions[]" value="<?= $p['id'] ?>"
                         id="perm<?= $g['id'].'_'.$p['id'] ?>"
                         <?= in_array($p['id'], $group_perms[$g['id']] ?? []) ? 'checked' : '' ?>>
                  <label class="form-check-label" for="perm<?= $g['id'].'_'.$p['id'] ?>">
                    <?= htmlspecialchars($p['page']) ?>
                  </label>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
          <button type="submit" class="btn btn-primary mt-2">💾 حفظ الصلاحيات</button>
        </form>
      <?php endforeach; ?>
    </div>
  </div>

</div>

<script>
  function editGroup(id,name){
    document.getElementById("group_id").value = id;
    document.getElementById("group_name").value = name;
  }
  function editPage(id,page){
    document.getElementById("page_id").value = id;
    document.getElementById("page_name").value = page;
  }
</script>
</body>
</html>
