<?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_item'])) {
    $id = (int)$_GET['delete_item'];
    $pdo->prepare("DELETE FROM Items WHERE Code=?")->execute([$id]);
    header("Location: ".$_SERVER['PHP_SELF']); exit;
}

/* إضافة أو تعديل صنف */
if (isset($_POST['save_item'])) {
    $id   = $_POST['ItemId'] ?? 0;
    $IName  = $_POST['IName'] ?? '';
    $IEName = $_POST['IEName'] ?: null;
    $Cat_Code = $_POST['Cat_Code'] ?? 0;
    $PriceTW = $_POST['PriceTW'] ?: 0;
    $PriceSala = $_POST['PriceSala'] ?: 0;
    $PriceDR = $_POST['PriceDR'] ?: 0;
    $pricecar = $_POST['pricecar'] ?: 0;
    $itemdesc = $_POST['itemdesc'] ?: null;
    $israw = isset($_POST['israw']) ? 1 : 0;
    $ISManufactory = isset($_POST['ISManufactory']) ? 1 : 0;
    $btn_BG_Color = $_POST['btn_BG_Color'] ?: null;
    $btn_Font_Color = $_POST['btn_Font_Color'] ?: null;
    $Image = uploadImage("itemimg");

    if ($id) {
        $sql = "UPDATE Items SET IName=:IName, IEName=:IEName, Cat_Code=:Cat_Code, PriceTW=:PriceTW,
                PriceSala=:PriceSala, PriceDR=:PriceDR, pricecar=:pricecar, itemdesc=:itemdesc,
                israw=:israw, ISManufactory=:ISManufactory, btn_BG_Color=:btn_BG_Color,
                btn_Font_Color=:btn_Font_Color".($Image ? ", itemimg=:itemimg" : "")." WHERE Code=:id";
        $params = compact("IName","IEName","Cat_Code","PriceTW","PriceSala","PriceDR","pricecar",
                          "itemdesc","israw","ISManufactory","btn_BG_Color","btn_Font_Color","id");
        if ($Image) $params["itemimg"]=$Image;
        $pdo->prepare($sql)->execute($params);
    } else {
        $pdo->prepare("INSERT INTO Items (IName, IEName, Cat_Code, PriceTW, PriceSala, PriceDR, pricecar, itemimg, itemdesc, israw, ISManufactory, btn_BG_Color, btn_Font_Color) 
                       VALUES (:IName,:IEName,:Cat_Code,:PriceTW,:PriceSala,:PriceDR,:pricecar,:itemimg,:itemdesc,:israw,:ISManufactory,:btn_BG_Color,:btn_Font_Color)")
            ->execute([
                ":IName"=>$IName,":IEName"=>$IEName,":Cat_Code"=>$Cat_Code,":PriceTW"=>$PriceTW,
                ":PriceSala"=>$PriceSala,":PriceDR"=>$PriceDR,":pricecar"=>$pricecar,
                ":itemimg"=>$Image,":itemdesc"=>$itemdesc,":israw"=>$israw,
                ":ISManufactory"=>$ISManufactory,":btn_BG_Color"=>$btn_BG_Color,":btn_Font_Color"=>$btn_Font_Color
            ]);
    }
    header("Location: ".$_SERVER['PHP_SELF']); exit;
}

/* جلب بيانات للتعديل */
$editItem = null;
if (isset($_GET['edit_item'])) {
    $stmt=$pdo->prepare("SELECT * FROM Items WHERE Code=?");
    $stmt->execute([$_GET['edit_item']]);
    $editItem=$stmt->fetch();
}

/* جلب المجموعات */
$categories = $pdo->query("SELECT Code, CName FROM Categories ORDER BY SortOrder IS NULL, SortOrder, Code")->fetchAll();

/* جلب الأصناف */
$items = $pdo->query("SELECT i.*, c.CName as CatName 
                      FROM Items i 
                      JOIN Categories c ON i.Cat_Code = c.Code
                      ORDER BY i.Code DESC")->fetchAll();
// إجمالي الأقسام
$totalGroupsCount = $pdo->query("SELECT COUNT(*) FROM ItemsGroups")->fetchColumn();
// إجمالي المجموعات
$totalCategoriesCount = $pdo->query("SELECT COUNT(*) FROM Categories")->fetchColumn();
// إجمالي الأصناف
$totalItemsCount = $pdo->query("SELECT COUNT(*) FROM Items")->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">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" rel="stylesheet">
  <style>
 /* تحسين شكل الأزرار */
.btn {
  border-radius: 30px;
  transition: all 0.3s ease-in-out;
}
.btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.2);
}

/* الكروت */
.card {
  border: none;
  border-radius: 18px;
  transition: all 0.3s ease-in-out;
}
.card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0,0,0,0.15);
}

/* رأس الصفحة */
header {
  background: linear-gradient(135deg,#0f2027,#203a43,#2c5364);
  border-bottom: 5px solid #1abc9c;
  padding:25px;
  text-align:center;
  color:#fff;
  margin-bottom:40px;
  position:relative;
  box-shadow:0 5px 20px rgba(0,0,0,0.3);
}
header h1 {
  font-size: 28px;
  font-weight: bold;
  letter-spacing: 1px;
}

/* الجدول */
table thead tr {
  background: linear-gradient(135deg,#2c3e50,#34495e)!important;
  color: #fff;
  font-size: 15px;
}
table tbody tr:hover {
  background: #f9f9f9;
  transition: 0.3s;
}

/* صورة الصنف */
img.thumb {
  border-radius: 12px;
  object-fit: cover;
  border: 2px solid #ddd;
  transition: 0.3s;
}
img.thumb:hover {
  transform: scale(1.2) rotate(2deg);
  border-color: #3498db;
}

/* الحقول */
.form-control, .form-select {
  border-radius: 10px;
  border: 1px solid #ddd;
  transition: border-color 0.3s ease;
}
.form-control:focus, .form-select:focus {
  border-color: #3498db;
  box-shadow: 0 0 5px rgba(52,152,219,0.5);
}

/* شبكة الكروت */
#itemsGrid .item-card {
  border-radius: 16px;
  background: #fff;
  transition: all 0.4s ease;
  opacity: 0;
  transform: translateY(30px);
}
#itemsGrid .item-card.show {
  opacity: 1;
  transform: translateY(0);
}
#itemsGrid .item-card:hover {
  transform: translateY(-6px) scale(1.02);
  box-shadow: 0 8px 20px rgba(0,0,0,0.15);
}

/* الوضع الليلي */
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;
}
body.dark table tbody tr:hover {
  background:#2a2a2a;
}
body.dark #itemsGrid .item-card {
  background: #1e1e1e;
  color: #ddd;
}
.form-check.form-switch .form-check-input {
  width: 3em;
  height: 1.5em;
  cursor: pointer;
}
.form-check.form-switch .form-check-input:checked {
  background-color: #1abc9c;
  border-color: #16a085;
}
.form-check-label {
  font-weight: 600;
  margin-right: 8px;
}
  </style>


</head>
<body>

<header class="d-flex justify-content-between align-items-center px-4 py-3 shadow-sm">
  <!-- بيانات المستخدم -->
  <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"><i class="fa-solid fa-burger 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-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-folder-open"></i> عدد الأقسام</h5>
        <h2><?= $totalGroupsCount ?></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-list"></i> عدد المجموعات</h5>
        <h2><?= $totalCategoriesCount ?></h2>
      </div>
    </div>
  </div>

  <!-- الأصناف -->
  <div class="col-md-4 mb-3">
    <div class="card text-white shadow" style="background:linear-gradient(135deg,#e67e22,#d35400);">
      <div class="card-body">
        <h5><i class="fa-solid fa-utensils"></i> عدد الأصناف</h5>
        <h2><?= $totalItemsCount ?></h2>
      </div>
    </div>
  </div>
</div>

  <!-- إضافة / تعديل صنف -->
  <div class="card">
  <div class="card-header bg-primary text-white"><?= $editItem ? "تعديل الصنف" : "إضافة صنف" ?></div>
  <div class="card-body">
    <form method="POST" enctype="multipart/form-data" class="row g-3">
      <input type="hidden" name="ItemId" value="<?= $editItem['Code'] ?? '' ?>">

      <div class="col-md-3">
        <input type="text" name="IName" class="form-control" placeholder="اسم الصنف" required value="<?= $editItem['IName'] ?? '' ?>">
      </div>
      <div class="col-md-3">
        <input type="text" name="IEName" class="form-control" placeholder="English Name" value="<?= $editItem['IEName'] ?? '' ?>">
      </div>
      <div class="col-md-3">
        <select name="Cat_Code" class="form-select" required>
          <option value="">اختر المجموعة</option>
          <?php foreach ($categories as $c): ?>
            <option value="<?= $c['Code'] ?>" <?= (isset($editItem['Cat_Code']) && $editItem['Cat_Code']==$c['Code'])?'selected':'' ?>>
              <?= htmlspecialchars($c['CName']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-3">
        <input type="file" name="itemimg" class="form-control">
      </div>

      <div class="col-md-3">
        <input type="number" name="PriceTW" step="0.01" class="form-control" placeholder="سعر تيك أواي" value="<?= $editItem['PriceTW'] ?? '' ?>">
      </div>
      <div class="col-md-3">
        <input type="number" name="PriceSala" step="0.01" class="form-control" placeholder="سعر الصالة" value="<?= $editItem['PriceSala'] ?? '' ?>">
      </div>
      <div class="col-md-3">
        <input type="number" name="PriceDR" step="0.01" class="form-control" placeholder="سعر الدليفري" value="<?= $editItem['PriceDR'] ?? '' ?>">
      </div>
      <div class="col-md-3">
        <input type="number" name="pricecar" step="0.01" class="form-control" placeholder="سعر خدمة السيارات" value="<?= $editItem['pricecar'] ?? '' ?>">
      </div>

      <!-- الوصف في صف كامل -->
      <div class="col-md-12">
        <textarea name="itemdesc" class="form-control" placeholder="وصف الصنف"><?= $editItem['itemdesc'] ?? '' ?></textarea>
      </div>

    <!-- صف التوجلات -->
    <div class="col-md-3">
    <div class="form-check form-switch">
        <input class="form-check-input" type="checkbox" id="israw" name="israw" <?= !empty($editItem['israw'])?'checked':'' ?>>
        <label class="form-check-label" for="israw">خام</label>
    </div>
    </div>

    <div class="col-md-3">
    <div class="form-check form-switch">
        <input class="form-check-input" type="checkbox" id="ISManufactory" name="ISManufactory" <?= !empty($editItem['ISManufactory'])?'checked':'' ?>>
        <label class="form-check-label" for="ISManufactory">مصنع</label>
    </div>
    </div>
      <div class="col-md-2">
        <input type="color" name="btn_BG_Color" class="form-control form-control-color" value="<?= $editItem['btn_BG_Color'] ?? '#ffffff' ?>">
      </div>
      <div class="col-md-2">
        <input type="color" name="btn_Font_Color" class="form-control form-control-color" value="<?= $editItem['btn_Font_Color'] ?? '#000000' ?>">
      </div>

      <div class="col-md-12 text-end">
        <button type="submit" name="save_item" class="btn btn-success">
          <i class="fa-solid fa-floppy-disk"></i> حفظ
        </button>
      </div>
    </form>
  </div>
</div>


  <!-- فلترة -->
  <div class="mb-3">
    <label for="filterCategory" class="form-label fw-bold">🔎 فلترة حسب القسم:</label>
    <select id="filterCategory" class="form-select w-auto d-inline-block">
      <option value="">عرض الكل</option>
      <?php foreach ($categories as $c): ?>
        <option value="<?= htmlspecialchars($c['CName']) ?>"><?= htmlspecialchars($c['CName']) ?></option>
      <?php endforeach; ?>
    </select>
  </div>

<div class="d-flex justify-content-end mb-3">
  <button id="showTable" class="btn btn-dark me-2"><i class="fa-solid fa-table"></i> عرض كجدول</button>
  <button id="showCards" class="btn btn-primary"><i class="fa-solid fa-grip"></i> عرض كبطاقات</button>
</div>

  <!-- جدول الأصناف -->
  <div class="card">
    <div class="card-header bg-dark text-white"><i class="fa-solid fa-list"></i> قائمة الأصناف</div>
    <div class="card-body">
      <table id="itemsTable" 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>
            <th>دليفري</th>
            <th>السيارات</th>
            <th>إجراءات</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($items as $i): ?>
          <tr>
            <td><?= $i['Code'] ?></td>
            <td><?= $i['itemimg'] ? "<img src='uploads/".htmlspecialchars($i['itemimg'])."' width='50' height='50' class='thumb'>" : '—' ?></td>
            <td><?= htmlspecialchars($i['IName']) ?></td>
            <td><?= $i['IEName'] ?: '—' ?></td>
            <td><?= htmlspecialchars($i['CatName']) ?></td>
            <td><?= $i['itemdesc'] ?: '—' ?></td>
            <td><?= number_format($i['PriceTW'], 2) ?></td>
            <td><?= number_format($i['PriceSala'], 2) ?></td>
            <td><?= number_format($i['PriceDR'], 2) ?></td>
            <td><?= number_format($i['PriceCar'], 2) ?></td>
            <td>
              <a href="?edit_item=<?= $i['Code'] ?>" class="btn btn-sm btn-warning"><i class="fa-solid fa-pen"></i></a>
              <a href="?delete_item=<?= $i['Code'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('هل أنت متأكد من الحذف؟')"><i class="fa-solid fa-trash"></i></a>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
<!-- شبكة الكروت -->
<div id="itemsGrid" class="row g-4 d-none">
  <?php foreach ($items as $i): ?>
    <div class="col-md-4 col-lg-3">
      <div class="item-card p-3 shadow-sm h-100">
        <div class="text-center mb-2">
          <?php if ($i['itemimg']): ?>
            <img src="uploads/<?= htmlspecialchars($i['itemimg']) ?>" class="rounded mb-2" style="width:100%; height:160px; object-fit:cover;">
          <?php else: ?>
            <div class="bg-light d-flex align-items-center justify-content-center rounded mb-2" style="height:160px;">
              <i class="fa-solid fa-image fa-2x text-muted"></i>
            </div>
          <?php endif; ?>
        </div>
        <h5 class="fw-bold text-center"><?= htmlspecialchars($i['IName']) ?></h5>
        <p class="text-muted small text-center"><?= $i['IEName'] ?: '—' ?></p>
        <p class="small"><?= $i['itemdesc'] ?: '—' ?></p>
        <div class="d-flex justify-content-between mt-3">
          <span class="badge bg-primary">تيك أواي: <?= number_format($i['PriceTW'], 2) ?></span>
          <span class="badge bg-success">صالة: <?= number_format($i['PriceSala'], 2) ?></span>
        </div>
        <div class="d-flex justify-content-between mt-2">
          <span class="badge bg-warning text-dark">دليفري: <?= number_format($i['PriceDR'], 2) ?></span>
          <span class="badge bg-info text-dark">سيارات: <?= number_format($i['PriceCar'], 2) ?></span>
        </div>
      </div>
    </div>
  <?php endforeach; ?>
</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(){
  var table = $('#itemsTable').DataTable({
    language:{url:"//cdn.datatables.net/plug-ins/1.13.6/i18n/ar.json"},
    dom:'Bfrtip',
    buttons:[
      { extend:'excelHtml5', text:'<i class="fa-solid fa-file-excel"></i> Excel', className:'btn btn-success btn-sm' },
      { extend:'pdfHtml5', text:'<i class="fa-solid fa-file-pdf"></i> 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) { cell.alignment = 'right'; });
              });
            }
          });
        }
      },
      { extend:'print', text:'<i class="fa-solid fa-print"></i> طباعة', className:'btn btn-dark btn-sm' }
    ]
  });

  // فلترة حسب القسم
  $('#filterCategory').on('change', function(){
    var val = $(this).val();
    table.column(4).search(val ? '^'+val+'$' : '', true, false).draw();
  });
});



const body = document.body;
const darkSwitch = document.getElementById("darkSwitch");

// تحميل الوضع من LocalStorage
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 ? "☀️" : "🌙";
});

document.addEventListener("DOMContentLoaded", () => {
      const items = document.querySelectorAll(".item-card");
      items.forEach((el, i) => {
        setTimeout(() => {
          el.classList.add("show");
        }, i * 250); // تأخير متدرج لكل كارت
      });
    });

    // تبديل العرض
const tableView = document.querySelector(".card:has(#itemsTable)");
const gridView = document.getElementById("itemsGrid");
const btnTable = document.getElementById("showTable");
const btnCards = document.getElementById("showCards");

btnTable.addEventListener("click", () => {
  tableView.classList.remove("d-none");
  gridView.classList.add("d-none");
});
btnCards.addEventListener("click", () => {
  tableView.classList.add("d-none");
  gridView.classList.remove("d-none");

  // تشغيل الأنيميشن
  const cards = gridView.querySelectorAll(".item-card");
  cards.forEach((card, i) => {
    setTimeout(() => card.classList.add("show"), i * 150);
  });
});

</script>
</body>
</html>
