<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/auth.php';

requireAdmin();
$db = getDBConnection();

// Delete category
if (isset($_GET['action']) && $_GET['action'] === 'delete') {
    $id = (int)$_GET['id'];
    $stmt = $db->prepare("DELETE FROM categories WHERE id = ?");
    $stmt->execute([$id]);
    $_SESSION['flash_success'] = 'ลบหมวดหมู่เรียบร้อยแล้ว';
    header('Location: categories.php');
    exit;
}

// Add/Edit category
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCSRFToken($_POST['csrf_token'] ?? '');
    $catId = (int)($_POST['category_id'] ?? 0);
    $name = sanitize($_POST['name'] ?? '');
    $icon = sanitize($_POST['icon'] ?? '👕');
    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name))) . '-' . rand(10,99);

    if (!empty($name)) {
        if ($catId > 0) {
            $stmt = $db->prepare("UPDATE categories SET name = ?, icon = ? WHERE id = ?");
            $stmt->execute([$name, $icon, $catId]);
            $_SESSION['flash_success'] = 'แก้ไขหมวดหมู่เรียบร้อยแล้ว';
        } else {
            $stmt = $db->prepare("INSERT INTO categories (name, slug, icon) VALUES (?, ?, ?)");
            $stmt->execute([$name, $slug, $icon]);
            $_SESSION['flash_success'] = 'เพิ่มหมวดหมู่ใหม่เรียบร้อยแล้ว';
        }
        header('Location: categories.php');
        exit;
    }
}

$categories = $db->query("SELECT c.*, COUNT(p.id) as product_count FROM categories c LEFT JOIN products p ON c.id = p.category_id GROUP BY c.id ORDER BY c.id ASC")->fetchAll();

require_once __DIR__ . '/../../includes/admin_header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <h3 class="fw-bold mb-0">🏷️ จัดการหมวดหมู่สินค้า</h3>
  <button class="btn btn-primary-custom rounded-pill" data-bs-toggle="modal" data-bs-target="#catModal" onclick="resetCatForm()">+ เพิ่มหมวดหมู่ใหม่</button>
</div>

<div class="card card-custom p-4">
  <table class="table table-hover align-middle">
    <thead>
      <tr>
        <th>ไอคอน</th>
        <th>ชื่อหมวดหมู่</th>
        <th>จำนวนสินค้า</th>
        <th>วันที่สร้าง</th>
        <th>จัดการ</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($categories as $c): ?>
        <tr>
          <td class="fs-4"><?php echo sanitize($c['icon']); ?></td>
          <td class="fw-bold"><?php echo sanitize($c['name']); ?></td>
          <td><span class="badge bg-info text-dark"><?php echo $c['product_count']; ?> ชิ้น</span></td>
          <td><?php echo date('d/m/Y', strtotime($c['created_at'])); ?></td>
          <td>
            <button class="btn btn-sm btn-edit-custom rounded-pill me-1" onclick='editCat(<?php echo json_encode($c); ?>)'>✏️ แก้ไข</button>
            <a href="categories.php?action=delete&id=<?php echo $c['id']; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('ยืนยันการลบหมวดหมู่นี้?')">🗑️ ลบ</a>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

<!-- Modal Category Form -->
<div class="modal fade" id="catModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <form method="POST" action="">
        <div class="modal-header">
          <h5 class="modal-title fw-bold" id="catModalTitle">เพิ่มหมวดหมู่ใหม่</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
          <input type="hidden" name="category_id" id="cat_id">

          <div class="mb-3">
            <label class="form-label">ชื่อหมวดหมู่ *</label>
            <input type="text" name="name" id="cat_name" class="form-control" required placeholder="เช่น เสื้อยืด (T-Shirt)">
          </div>

          <div class="mb-3">
            <label class="form-label">อีโมจิไอคอน</label>
            <input type="text" name="icon" id="cat_icon" class="form-control" value="👕">
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary rounded-pill" data-bs-dismiss="modal">ยกเลิก</button>
          <button type="submit" class="btn btn-primary-custom rounded-pill">บันทึกหมวดหมู่ ✨</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
function resetCatForm() {
    document.getElementById('catModalTitle').innerText = 'เพิ่มหมวดหมู่ใหม่';
    document.getElementById('cat_id').value = '';
    document.getElementById('cat_name').value = '';
    document.getElementById('cat_icon').value = '👕';
}

function editCat(c) {
    document.getElementById('catModalTitle').innerText = 'แก้ไขหมวดหมู่';
    document.getElementById('cat_id').value = c.id;
    document.getElementById('cat_name').value = c.name;
    document.getElementById('cat_icon').value = c.icon;
    new bootstrap.Modal(document.getElementById('catModal')).show();
}
</script>

<?php require_once __DIR__ . '/../../includes/admin_footer.php'; ?>
