<?php
require_once __DIR__ . '/../core/auth.php'; 
require_login(); // منع الدخول لغير المسجلين 
$pdo = db();

/* رفع الصور */
function uploadImage($fileInput, $uploadDir = "uploads/") {
    if (isset($_FILES[$fileInput]) && $_FILES[$fileInput]['error'] == 0) {
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
        $fileName = time() . "_" . basename($_FILES[$fileInput]['name']);
        $target = $uploadDir . $fileName;
        move_uploaded_file($_FILES[$fileInput]['tmp_name'], $target);
        return $fileName;
    }
    return null;
}

/* حذف قسم */
if (isset($_GET['delete_group'])) {
    $id = (int)$_GET['delete_group'];
    $pdo->prepare("DELETE FROM ItemsGroups WHERE Code=?")->execute([$id]);
    header("Location: ".$_SERVER['PHP_SELF']); exit;
}

/* حذف مجموعة */
if (isset($_GET['delete_category'])) {
    $id = (int)$_GET['delete_category'];
    $pdo->prepare("DELETE FROM Categories WHERE Code=?")->execute([$id]);
    header("Location: ".$_SERVER['PHP_SELF']); exit;
}

/* إضافة أو تعديل قسم */
if (isset($_POST['save_group'])) {
    $id   = $_POST['GroupId'] ?? 0;
    $GName  = $_POST['GName'] ?? '';
    $GEName = $_POST['GEName'] ?: null;
    $SortOrder = $_POST['SortOrder'] ?: null;
    $IsHidden = isset($_POST['IsHidden']) ? 1 : 0;
    $Image = uploadImage("GroupImage");

    if ($id) {
        $sql = "UPDATE ItemsGroups SET GName=:GName, GEName=:GEName, SortOrder=:SortOrder, IsHidden=:IsHidden".
               ($Image ? ", Image=:Image" : "")." WHERE Code=:id";
        $params = [':GName'=>$GName,':GEName'=>$GEName,':SortOrder'=>$SortOrder,':IsHidden'=>$IsHidden,':id'=>$id];
        if ($Image) $params[':Image']=$Image;
        $pdo->prepare($sql)->execute($params);
    } else {
        $pdo->prepare("INSERT INTO ItemsGroups (GName, GEName, SortOrder, Image, IsHidden) 
                       VALUES (:GName, :GEName, :SortOrder, :Image, :IsHidden)")
            ->execute([':GName'=>$GName, ':GEName'=>$GEName, ':SortOrder'=>$SortOrder, ':Image'=>$Image, ':IsHidden'=>$IsHidden]);
    }
    header("Location: ".$_SERVER['PHP_SELF']); exit;
}

/* إضافة أو تعديل مجموعة */
if (isset($_POST['save_category'])) {
    $id   = $_POST['CategoryId'] ?? 0;
    $CName  = $_POST['CName'] ?? '';
    $CEName = $_POST['CEName'] ?: null;
    $SortOrder = $_POST['SortOrder'] ?: null;
    $Group_Code = $_POST['Group_Code'] ?? 0;
    $IsHidden = isset($_POST['IsHidden']) ? 1 : 0;
    $Image = uploadImage("CategoryImage");

    if ($id) {
        $sql = "UPDATE Categories SET CName=:CName, CEName=:CEName, SortOrder=:SortOrder, Group_Code=:Group_Code, IsHidden=:IsHidden".
               ($Image ? ", Image=:Image" : "")." WHERE Code=:id";
        $params = [':CName'=>$CName,':CEName'=>$CEName,':SortOrder'=>$SortOrder,':Group_Code'=>$Group_Code,':IsHidden'=>$IsHidden,':id'=>$id];
        if ($Image) $params[':Image']=$Image;
        $pdo->prepare($sql)->execute($params);
    } else {
        $pdo->prepare("INSERT INTO Categories (CName, CEName, SortOrder, Image, Group_Code, IsHidden) 
                       VALUES (:CName,:CEName,:SortOrder,:Image,:Group_Code,:IsHidden)")
            ->execute([':CName'=>$CName, ':CEName'=>$CEName, ':SortOrder'=>$SortOrder, ':Image'=>$Image, ':Group_Code'=>$Group_Code, ':IsHidden'=>$IsHidden]);
    }
    header("Location: ".$_SERVER['PHP_SELF']); exit;
}

/* جلب بيانات للتعديل */
$editGroup = null; 
$editCategory = null;

if (isset($_GET['edit_group'])) {
    $stmt=$pdo->prepare("SELECT * FROM ItemsGroups WHERE Code=?");
    $stmt->execute([$_GET['edit_group']]);
    $editGroup=$stmt->fetch();
}
if (isset($_GET['edit_category'])) {
    $stmt=$pdo->prepare("SELECT * FROM Categories WHERE Code=?");
    $stmt->execute([$_GET['edit_category']]);
    $editCategory=$stmt->fetch();
}

/* جلب البيانات */
$groups = $pdo->query("
    SELECT g.*, COUNT(c.Code) AS CategoryCount
    FROM ItemsGroups g
    LEFT JOIN Categories c ON g.Code = c.Group_Code
    GROUP BY g.Code
    ORDER BY g.SortOrder IS NULL, g.SortOrder, g.Code
")->fetchAll();

$categories=$pdo->query("SELECT c.*, g.GName FROM Categories c JOIN ItemsGroups g ON g.Code=c.Group_Code 
                         ORDER BY c.SortOrder IS NULL, c.SortOrder, c.Code")->fetchAll();
$totalGroupsCount = $pdo->query("SELECT COUNT(*) FROM ItemsGroups")->fetchColumn();
$totalCategoriesCount = $pdo->query("SELECT COUNT(*) FROM Categories")->fetchColumn();
?>
<!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">
  <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
  <link href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css" rel="stylesheet">
  <style>
    body {
      font-family:"Tajawal",sans-serif;
      background: linear-gradient(135deg,#1e3c72,#2a5298);
      min-height:100vh;
      transition: background 0.3s, color 0.3s;
    }
    header {
      background: linear-gradient(135deg,#0f2027,#203a43,#2c5364);
      padding:25px;
      text-align:center;
      color:#fff;
      margin-bottom:40px;
      border-bottom:5px solid #1abc9c;
      position:relative;
      box-shadow:0 5px 20px rgba(0,0,0,0.3);
    }
    header h1 { font-weight:bold; font-size:28px; letter-spacing:1px; }
    #darkSwitch {
      position:absolute; left:20px; top:20px;
      background:#1abc9c; color:#fff; border:none;
      border-radius:30px; padding:8px 18px;
      cursor:pointer; font-weight:bold;
      transition:all 0.3s;
    }
    #darkSwitch:hover { background:#16a085; }
    .card {
      border-radius:15px;
      overflow:hidden;
      box-shadow:0 6px 20px rgba(0,0,0,0.15);
      margin-bottom:25px;
      background:#fff;
      transition:transform .2s;
    }
    .card:hover { transform:translateY(-5px); }
    .card-header.bg-primary { background: linear-gradient(135deg,#2980b9,#2c3e50)!important; }
    .card-header.bg-success { background: linear-gradient(135deg,#27ae60,#145a32)!important; }
    table thead tr {
      background: linear-gradient(135deg,#2c3e50,#34495e)!important;
      color:#fff; font-weight:bold;
    }
    table tbody tr:hover { background-color:#f9f9f9; transition:background 0.2s; }
    img.thumb { border-radius:8px; object-fit:cover; border:2px solid #eee; }
    .btn-success.btn-sm { background:#27ae60; border:none; }
    .btn-success.btn-sm:hover { background:#1e8449; }
    .btn-danger.btn-sm { background:#c0392b; border:none; }
    .btn-danger.btn-sm:hover { background:#922b21; }
    .btn-dark.btn-sm { background:#2c3e50; border:none; }
    .btn-dark.btn-sm:hover { background:#1a252f; }
    /* 🌙 الوضع الليلي */
    body.dark { background:#121212; color:#eee; }
    body.dark header { background:linear-gradient(135deg,#000,#333); border-bottom-color:#16a085; }
    body.dark .card { background:#1e1e1e; color:#ddd; }
    body.dark table { color:#fff; }
    body.dark thead tr { background:#333!important; }
  </style>
</head>
<body>
<header class="d-flex justify-content-between align-items-center px-4 py-3 shadow-sm"
        style="background: linear-gradient(135deg,#1e3c72,#2a5298); color:#fff;">

  <!-- بيانات المستخدم -->
  <div class="user-info d-flex align-items-center gap-3">
    <!-- صورة بروفايل -->
    <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;">

    <!-- اسم المستخدم -->
    <div class="badge bg-light text-dark px-3 py-2 shadow-sm rounded-pill">
      مرحباً، <strong><?= htmlspecialchars($_SESSION['admin_username']) ?></strong>
    </div>

    <!-- زر تسجيل الخروج -->
    <a href="logout.php" class="btn btn-outline-light btn-sm shadow-sm">
      <i class="fa-solid fa-right-from-bracket"></i> تسجيل خروج
    </a>
  </div>

  <!-- العنوان -->
  <h1 class="m-0 text-center flex-grow-1 fw-bold" style="font-size: 1.6rem;">
    <i class="fa-solid fa-layer-group me-2"></i> لوحة إدارة الأقسام والمجموعات
  </h1>

  <!-- زر الوضع الليلي -->
  <button id="darkSwitch" class="btn btn-sm btn-light shadow-sm">
    🌙
  </button>
</header>


<div class="container">

<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-6 mb-3">
      <div class="card text-white" style="background:linear-gradient(135deg,#3498db,#2c3e50);">
        <div class="card-body">
          <h5>📂 عدد الأقسام</h5><h2><?= $totalGroupsCount ?></h2>
        </div>
      </div>
    </div>
    <div class="col-md-6 mb-3">
      <div class="card text-white" style="background:linear-gradient(135deg,#1abc9c,#145a32);">
        <div class="card-body">
          <h5>📋 عدد المجموعات</h5><h2><?= $totalCategoriesCount ?></h2>
        </div>
      </div>
    </div>
  </div>

  <!-- الأقسام -->
  <div class="card mb-4">
    <div class="card-header bg-primary text-white">📂 <?= $editGroup ? "تعديل القسم" : "إضافة قسم" ?></div>
    <div class="card-body">
      <form method="POST" enctype="multipart/form-data" class="row g-3 mb-4">
        <input type="hidden" name="GroupId" value="<?= $editGroup['Code'] ?? '' ?>">
        <div class="col-md-2"><input type="text" name="GName" class="form-control" placeholder="الاسم العربي" required value="<?= $editGroup['GName'] ?? '' ?>"></div>
        <div class="col-md-2"><input type="text" name="GEName" class="form-control" placeholder="الاسم الإنجليزي" value="<?= $editGroup['GEName'] ?? '' ?>"></div>
        <div class="col-md-2"><input type="number" name="SortOrder" class="form-control" placeholder="ترتيب" value="<?= $editGroup['SortOrder'] ?? '' ?>"></div>
        <div class="col-md-2"><input type="file" name="GroupImage" class="form-control"></div>
        <div class="col-md-2"><input type="checkbox" name="IsHidden" class="form-check-input" <?= !empty($editGroup['IsHidden'])?'checked':'' ?>> إخفاء</div>
        <div class="col-md-2"><button type="submit" name="save_group" class="btn btn-success w-100">💾</button></div>
      </form>

      <table id="groupsTable" class="table table-bordered align-middle text-center">
        <thead><tr><th>#</th><th>العربي</th><th>الإنجليزي</th><th>ترتيب</th><th>صورة</th><th>المجموعات</th><th>الحالة</th><th>إجراءات</th></tr></thead>
        <tbody>
          <?php foreach ($groups as $g): ?>
          <tr>
            <td><?= $g['Code'] ?></td>
            <td><?= htmlspecialchars($g['GName']) ?></td>
            <td><?= $g['GEName'] ?: '—' ?></td>
            <td><?= $g['SortOrder'] ?: '—' ?></td>
            <td><?= $g['Image'] ? "<img src='uploads/".htmlspecialchars($g['Image'])."' width='40' height='40' class='thumb'>" : '—' ?></td>
            <td><?= $g['CategoryCount'] ?></td>
            <td><?= $g['IsHidden'] ? 'مخفي' : 'ظاهر' ?></td>
            <td>
              <a href="?edit_group=<?= $g['Code'] ?>" class="btn btn-sm btn-warning">✏️</a>
              <a href="?delete_group=<?= $g['Code'] ?>" 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 bg-success text-white">📋 <?= $editCategory ? "تعديل المجموعة" : "إضافة مجموعة" ?></div>
    <div class="card-body">
      <form method="POST" enctype="multipart/form-data" class="row g-3 mb-4">
        <input type="hidden" name="CategoryId" value="<?= $editCategory['Code'] ?? '' ?>">
        <div class="col-md-2"><input type="text" name="CName" class="form-control" placeholder="الاسم العربي" required value="<?= $editCategory['CName'] ?? '' ?>"></div>
        <div class="col-md-2"><input type="text" name="CEName" class="form-control" placeholder="الاسم الإنجليزي" value="<?= $editCategory['CEName'] ?? '' ?>"></div>
        <div class="col-md-2"><input type="number" name="SortOrder" class="form-control" placeholder="ترتيب" value="<?= $editCategory['SortOrder'] ?? '' ?>"></div>
        <div class="col-md-2">
          <select name="Group_Code" class="form-select" required>
            <option value="">اختر القسم</option>
            <?php foreach ($groups as $g): ?>
              <option value="<?= $g['Code'] ?>" <?= (isset($editCategory['Group_Code']) && $editCategory['Group_Code']==$g['Code'])?'selected':'' ?>>
                <?= htmlspecialchars($g['GName']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-2"><input type="file" name="CategoryImage" class="form-control"></div>
        <div class="col-md-1"><input type="checkbox" name="IsHidden" class="form-check-input" <?= !empty($editCategory['IsHidden'])?'checked':'' ?>> إخفاء</div>
        <div class="col-md-1"><button type="submit" name="save_category" class="btn btn-success w-100">💾</button></div>
      </form>

      <table id="categoriesTable" class="table table-bordered align-middle text-center">
        <thead><tr><th>#</th><th>العربي</th><th>الإنجليزي</th><th>ترتيب</th><th>صورة</th><th>القسم</th><th>الحالة</th><th>إجراءات</th></tr></thead>
        <tbody>
          <?php foreach ($categories as $c): ?>
          <tr>
            <td><?= $c['Code'] ?></td>
            <td><?= htmlspecialchars($c['CName']) ?></td>
            <td><?= $c['CEName'] ?: '—' ?></td>
            <td><?= $c['SortOrder'] ?: '—' ?></td>
            <td><?= $c['Image'] ? "<img src='uploads/".htmlspecialchars($c['Image'])."' width='40' height='40' class='thumb'>" : '—' ?></td>
            <td><?= htmlspecialchars($c['GName']) ?></td>
            <td><?= $c['IsHidden'] ? 'مخفي' : 'ظاهر' ?></td>
            <td>
              <a href="?edit_category=<?= $c['Code'] ?>" class="btn btn-sm btn-warning">✏️</a>
              <a href="?delete_category=<?= $c['Code'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('حذف المجموعة؟')">🗑️</a>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>

</div>

<!-- مكتبات -->
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="js/vfs_fonts.js"></script>
<script>
pdfMake.fonts = { Tajawal:{ normal:'Tajawal-Regular.ttf', bold:'Tajawal-Bold.ttf', italics:'Tajawal-Regular.ttf', bolditalics:'Tajawal-Bold.ttf' } };
$(function(){
  $('#groupsTable,#categoriesTable').DataTable({
    language:{url:"//cdn.datatables.net/plug-ins/1.13.6/i18n/ar.json"},
    dom:'Bfrtip',
    buttons:[
      { extend:'excelHtml5', text:'📊 Excel', className:'btn btn-success btn-sm' },
      { extend:'pdfHtml5', text:'📄 PDF', className:'btn btn-danger btn-sm',
        customize: function (doc) {
          doc.defaultStyle = { font: 'Tajawal', alignment: 'right', fontSize: 12 };
          doc.pageMargins = [40,40,40,40];
          doc.content.forEach(function(node) {
            if (node.table) {
              node.table.body.forEach(function(row) {
                row.forEach(function(cell) {
                  if (typeof cell.text === 'string') {
                    cell.text = cell.text.split(' ').reverse().join(' ');
                  }
                  cell.alignment = 'right';
                });
              });
            }
          });
        }
      },
      { extend:'print', text:'🖨️ طباعة', className:'btn btn-dark btn-sm' }
    ]
  });
});
/* Dark Mode */
const body=document.body, darkSwitch=document.getElementById("darkSwitch");
if(localStorage.getItem("darkMode")==="true"){ body.classList.add("dark"); darkSwitch.textContent="☀️"; }
darkSwitch.addEventListener("click",()=>{ body.classList.toggle("dark"); const isDark=body.classList.contains("dark"); localStorage.setItem("darkMode",isDark); darkSwitch.textContent=isDark?"☀️":"🌙"; });
</script>
</body>
</html>
