<?php
// ---------------- عملیات Ajax ----------------
// 🔸 تغییر وضعیت فعال/غیرفعال
if (isset($_POST['toggle_active'])) {
    $id = (int)$_POST['toggle_active'];
    $pdo->prepare("UPDATE Category SET IsActive = NOT IsActive WHERE CategoryID = ?")->execute([$id]);
    $status = $pdo->query("SELECT IsActive FROM Category WHERE CategoryID = $id")->fetchColumn();
    exit(json_encode(['status' => 'ok', 'is_active' => $status]));
}

// 🔸 حذف
if (isset($_POST['delete_id'])) {
    $id = (int)$_POST['delete_id'];
    $pdo->prepare("DELETE FROM Category WHERE CategoryID = ?")->execute([$id]);
    $pdo->prepare("DELETE FROM CategoryTranslation WHERE CategoryID = ?")->execute([$id]);
    $pdo->prepare("DELETE FROM ItemDetail WHERE CategoryID = ?")->execute([$id]);
    exit(json_encode(['status' => 'deleted']));
}

// 🔸 ذخیره ویرایش
if (isset($_POST['save_edit'])) {
    $id   = (int)$_POST['category_id'];
    $name = trim($_POST['name']);
    $desc = trim($_POST['description']);
    $price = trim($_POST['price']);
    $lang = $_POST['lang'];

    // --- بروزرسانی ترجمه ---
    $stmt = $pdo->prepare("
        UPDATE CategoryTranslation
        SET Name = ?, Description = ?
        WHERE CategoryID = ? AND LanguageCode = ?
    ");
    $stmt->execute([$name, $desc, $id, $lang]);

    // --- بروزرسانی یا درج قیمت ---
    // چک کن آیا رکورد موجود است
    $check = $pdo->prepare("SELECT COUNT(*) FROM ItemDetail WHERE CategoryID = ?");
    $check->execute([$id]);
    $exists = $check->fetchColumn();

    if ($exists) {
        // بروزرسانی
        $stmt2 = $pdo->prepare("UPDATE ItemDetail SET Price = ? WHERE CategoryID = ?");
        $stmt2->execute([$price, $id]);
    } else {
        // درج جدید
        $stmt2 = $pdo->prepare("INSERT INTO ItemDetail (CategoryID, Price) VALUES (?, ?)");
        $stmt2->execute([$id, $price]);
    }

    exit(json_encode(['status' => 'updated']));
}


// 🔸 جستجو (Ajax)
if (isset($_POST['search_query'])) {
    $query = "%" . trim($_POST['search_query']) . "%";
    $lang = $_POST['lang'] ?? 'fa';
    $stmt = $pdo->prepare("
        SELECT 
            c.CategoryID,
            c.IsActive,
            t.Name,
            t.Description,
            i.Price
        FROM Category c
        LEFT JOIN CategoryTranslation t ON c.CategoryID = t.CategoryID AND t.LanguageCode = :lang
        LEFT JOIN ItemDetail i ON c.CategoryID = i.CategoryID
        WHERE t.Name LIKE :q OR t.Description LIKE :q
        ORDER BY c.Level, c.SortOrder
    ");
    $stmt->execute(['lang' => $lang, 'q' => $query]);
    $results = $stmt->fetchAll();
    exit(json_encode($results));
}

// ---------------- زبان انتخابی ----------------
$lang = $_GET['lang'] ?? 'fa';

// ---------------- دریافت داده‌ها ----------------
$stmt = $pdo->prepare("
    SELECT 
        c.CategoryID,
        c.IsActive,
        t.Name,
        t.Description,
        i.Price
    FROM Category c
    LEFT JOIN CategoryTranslation t ON c.CategoryID = t.CategoryID AND t.LanguageCode = :lang
    LEFT JOIN ItemDetail i ON c.CategoryID = i.CategoryID
    ORDER BY c.Level, c.SortOrder
");
$stmt->execute(['lang' => $lang]);
$categories = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<title>📂 مدیریت مجموعه‌ها</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
<style>
    body { background: #f5f6fa; font-family: "Vazirmatn", sans-serif; }
    .container { margin-top: 40px; }
    table { background: white; border-radius: 8px; overflow: hidden; }
    .btn-action { margin: 0 3px; }
    .badge-clickable { cursor: pointer; }
</style>
</head>
<body class="container">

<h1 class="mb-3">📂 مدیریت مجموعه‌ها و زیرمجموعه‌ها</h1>

<div class="lang-menu mb-4">
    <strong>🌐 انتخاب زبان:</strong>
    <a href="?lang=fa" class="btn btn-sm <?= $lang == 'fa' ? 'btn-primary' : 'btn-outline-primary' ?>">فارسی</a>
    <a href="?lang=en" class="btn btn-sm <?= $lang == 'en' ? 'btn-primary' : 'btn-outline-primary' ?>">English</a>
    <a href="?lang=tr" class="btn btn-sm <?= $lang == 'tr' ? 'btn-primary' : 'btn-outline-primary' ?>">Türkçe</a>
</div>

<!-- فیلد جستجو -->
<div class="mb-3">
    <input type="text" id="searchBox" class="form-control" placeholder="🔍 جستجو بر اساس نام یا توضیحات...">
</div>

<!-- جدول اصلی -->
<table id="mainTable" class="table table-bordered table-striped align-middle">
    <thead class="table-dark text-center">
        <tr>
            <th>نام مجموعه</th>
            <th>توضیحات</th>
            <th>قیمت</th>
            <th>وضعیت</th>
            <th>عملیات</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($categories as $cat): ?>
            <tr data-id="<?= $cat['CategoryID'] ?>" data-lang="<?= $lang ?>">
                <td><?= htmlspecialchars($cat['Name'] ?: '---') ?></td>
                <td><?= htmlspecialchars($cat['Description'] ?: '') ?></td>
                <td><?= htmlspecialchars($cat['Price'] ?: '0') ?></td>
                <td class="text-center">
                    <span class="badge <?= $cat['IsActive'] ? 'bg-success' : 'bg-danger' ?> badge-clickable toggle-active">
                        <?= $cat['IsActive'] ? 'فعال' : 'غیرفعال' ?>
                    </span>
                </td>
                <td class="text-center">
                    <button class="btn btn-sm btn-warning btn-action edit-btn">ویرایش</button>
                    <button class="btn btn-sm btn-danger btn-action delete-btn">حذف</button>
                </td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<!-- جدول نتایج جستجو -->
<div id="searchResults" style="display:none;">
    <h4 class="mt-5 mb-3">🔎 نتایج جستجو</h4>
    <table id="searchResultsTable" class="table table-bordered table-striped align-middle">
        <thead class="table-secondary text-center">
            <tr>
                <th>نام مجموعه</th>
                <th>توضیحات</th>
                <th>قیمت</th>
                <th>وضعیت</th>
                <th>عملیات</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>

<!-- Modal ویرایش -->
<div class="modal fade" id="editModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title">✏️ ویرایش مجموعه</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <form id="editForm">
          <input type="hidden" name="category_id" id="edit_id">
          <input type="hidden" name="lang" id="edit_lang">
          <div class="mb-3">
            <label class="form-label">نام مجموعه</label>
            <input type="text" class="form-control" name="name" id="edit_name" required>
          </div>
          <div class="mb-3">
            <label class="form-label">توضیحات</label>
            <textarea class="form-control" name="description" id="edit_description" rows="3"></textarea>
          </div>
          <div class="mb-3">
            <label class="form-label">قیمت (تومان)</label>
            <input type="text" class="form-control" name="price" id="edit_price" required>
          </div>
          <button type="submit" class="btn btn-success">💾 ذخیره</button>
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">انصراف</button>
        </form>
      </div>
    </div>
  </div>
</div>

<script>
$(document).ready(function() {
    const mainTable = $('#mainTable').DataTable({
        pageLength: 10,
        language: { url: "//cdn.datatables.net/plug-ins/1.13.4/i18n/fa.json" }
    });

    const searchTable = $('#searchResultsTable').DataTable({
        pageLength: 5,
        language: { url: "//cdn.datatables.net/plug-ins/1.13.4/i18n/fa.json" }
    });

    // 🔍 جستجو
    $('#searchBox').on('input', function() {
        let q = $(this).val().trim();
        if (q.length < 2) {
            $('#searchResults').hide();
            return;
        }
        $.post('', { search_query: q, lang: '<?= $lang ?>' }, function(data) {
            searchTable.clear();
            if (data.length > 0) {
                data.forEach(row => {
                    searchTable.row.add([
                        row.Name ?? '---',
                        row.Description ?? '',
                        row.Price ?? '0',
                        `<span class="badge ${row.IsActive == 1 ? 'bg-success' : 'bg-danger'} badge-clickable toggle-active" data-id="${row.CategoryID}">${row.IsActive == 1 ? 'فعال' : 'غیرفعال'}</span>`,
                        `
                        <button class="btn btn-sm btn-warning btn-action edit-btn" data-id="${row.CategoryID}" data-lang="<?= $lang ?>">ویرایش</button>
                        <button class="btn btn-sm btn-danger btn-action delete-btn" data-id="${row.CategoryID}">حذف</button>
                        `
                    ]);
                });
                searchTable.draw();
                $('#searchResults').show();
            } else {
                $('#searchResults').hide();
            }
        }, 'json');
    });

    // 🔸 فعال / غیرفعال
    $(document).on('click', '.toggle-active', function() {
        let id = $(this).data('id') || $(this).closest('tr').data('id');
        let badge = $(this);
        $.post('', { toggle_active: id }, function(res) {
            if (res.status === 'ok') {
                if (res.is_active == 1) {
                    badge.removeClass('bg-danger').addClass('bg-success').text('فعال');
                } else {
                    badge.removeClass('bg-success').addClass('bg-danger').text('غیرفعال');
                }
            }
        }, 'json');
    });

    // 🔸 حذف
    $(document).on('click', '.delete-btn', function() {
        if (!confirm('❗ آیا از حذف این مجموعه مطمئن هستید؟')) return;
        let id = $(this).data('id') || $(this).closest('tr').data('id');
        $.post('', { delete_id: id }, function(res) {
            if (res.status === 'deleted') {
                mainTable.rows(`[data-id="${id}"]`).remove().draw();
                searchTable.rows().every(function() {
                    if ($(this.node()).find('[data-id="'+id+'"]').length) this.remove();
                });
                searchTable.draw();
            }
        }, 'json');
    });

    // 🔸 باز کردن پاپ‌آپ ویرایش
    $(document).on('click', '.edit-btn', function() {
        let row = $(this).closest('tr');
        let id = $(this).data('id') || row.data('id');
        let lang = $(this).data('lang') || row.data('lang');
        $('#edit_id').val(id);
        $('#edit_lang').val(lang);
        $('#edit_name').val(row.find('td:eq(0)').text().trim());
        $('#edit_description').val(row.find('td:eq(1)').text().trim());
        $('#edit_price').val(row.find('td:eq(2)').text().trim());
        $('#editModal').modal('show');
    });

    // 🔸 ذخیره ویرایش
    $('#editForm').on('submit', function(e) {
        e.preventDefault();
        $.post('', $(this).serialize() + '&save_edit=1', function(res) {
            if (res.status === 'updated') {
                alert('✅ بروزرسانی با موفقیت انجام شد');
                location.reload();
            }
        }, 'json');
    });
});
</script>

</body>
</html>
