<?php
/**
 * vendor_panel/categories.php
 * จัดการหมวดหมู่ย่อยของร้านค้า (Vendor Categories)
 */
session_start();
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/middleware.php';

requireVendor();

$vendorId = getCurrentVendorId();
$db       = getDBConnection();
$error    = '';

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

// ── TOGGLE active ─────────────────────────────────────────
if (isset($_GET['action']) && $_GET['action'] === 'toggle' && isset($_GET['id'])) {
    $cid = (int)$_GET['id'];
    requireCategoryOwnership($cid);
    $db->prepare("UPDATE vendor_categories SET is_active = 1 - is_active WHERE id=? AND vendor_id=?")
       ->execute([$cid, $vendorId]);
    header('Location: categories.php'); exit;
}

// ── SAVE ──────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCSRFToken($_POST['csrf_token'] ?? '');
    $catId       = (int)($_POST['cat_id']       ?? 0);
    $name        = sanitize($_POST['name']        ?? '');
    $parentCatId = (int)($_POST['category_id']   ?? 0) ?: null;
    $description = sanitize($_POST['description'] ?? '');
    $sortOrder   = (int)($_POST['sort_order']     ?? 0);
    $slug        = strtolower(preg_replace('/[^a-z0-9]+/i', '-', $name)) . '-' . substr(md5(uniqid()), 0, 5);

    if (empty($name)) {
        $error = 'กรุณากรอกชื่อหมวดหมู่';
    } else {
        if ($catId > 0) {
            requireCategoryOwnership($catId);
            $db->prepare("UPDATE vendor_categories SET category_id=?,name=?,description=?,sort_order=? WHERE id=? AND vendor_id=?")
               ->execute([$parentCatId, $name, $description, $sortOrder, $catId, $vendorId]);
            $_SESSION['flash_success'] = 'แก้ไขหมวดหมู่เรียบร้อยแล้ว';
        } else {
            $db->prepare("INSERT INTO vendor_categories (vendor_id,category_id,name,slug,description,sort_order) VALUES (?,?,?,?,?,?)")
               ->execute([$vendorId, $parentCatId, $name, $slug, $description, $sortOrder]);
            $_SESSION['flash_success'] = 'เพิ่มหมวดหมู่ใหม่เรียบร้อยแล้ว';
        }
        header('Location: categories.php'); exit;
    }
}

// ── DATA ─────────────────────────────────────────────────
$mainCategoriesStmt = $db->query("SELECT id, name, icon FROM categories WHERE is_active=1 ORDER BY sort_order");
$mainCategories     = $mainCategoriesStmt ? ($mainCategoriesStmt->fetchAll() ?: []) : [];

$myCategoriesStmt   = $db->prepare("
    SELECT vc.*, c.name AS parent_name, c.icon AS parent_icon,
           COUNT(p.id) AS product_count
    FROM vendor_categories vc
    LEFT JOIN categories c ON vc.category_id = c.id
    LEFT JOIN products p ON p.vendor_category_id = vc.id
    WHERE vc.vendor_id = ?
    GROUP BY vc.id
    ORDER BY vc.sort_order, vc.created_at
");
$myCategoriesStmt->execute([$vendorId]);
$myCategories = $myCategoriesStmt->fetchAll() ?: [];

// ── โหลด vendor_header (ส่ง HTML) หลังประมวลผลเสร็จ ──
require_once __DIR__ . '/vendor_header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h4 class="fw-bold mb-0">🏷️ หมวดหมู่ร้านค้าของฉัน</h4>
    <small class="text-muted">หมวดหมู่ย่อยที่คุณสร้างเองสำหรับจัดกลุ่มสินค้า</small>
  </div>
  <button class="btn btn-vendor-primary px-4" data-bs-toggle="modal" data-bs-target="#catModal" onclick="resetCatForm()">
    + เพิ่มหมวดหมู่ใหม่
  </button>
</div>

<?php if ($error): ?>
  <div class="alert alert-danger rounded-3"><?php echo $error; ?></div>
<?php endif; ?>

<!-- Info Box -->
<div class="alert alert-info rounded-3 d-flex align-items-start gap-2 mb-4" style="font-size:.85rem">
  <span style="font-size:1.1rem">💡</span>
  <div>
    <strong>วิธีใช้:</strong> หมวดหมู่เหล่านี้เป็นหมวดหมู่ <em>ย่อยของร้านคุณ</em>
    ผูกกับ <strong>หมวดหมู่หลักของเว็บ</strong> (เลือกได้ด้านล่าง)
    แล้วนำไปใช้ตอนเพิ่มสินค้า
  </div>
</div>

<!-- Categories Grid -->
<?php if (empty($myCategories)): ?>
  <div class="v-card text-center py-5">
    <div style="font-size:3rem">🏷️</div>
    <div class="text-muted mt-2 mb-3">ยังไม่มีหมวดหมู่</div>
    <button class="btn btn-vendor-primary px-4" data-bs-toggle="modal" data-bs-target="#catModal" onclick="resetCatForm()">
      + สร้างหมวดหมู่แรก
    </button>
  </div>
<?php else: ?>
  <div class="row g-3">
    <?php foreach ($myCategories as $cat): ?>
      <div class="col-md-4 col-sm-6">
        <div class="v-card p-0 h-100 <?php echo !$cat['is_active'] ? 'opacity-60' : ''; ?>">
          <div class="p-3 border-bottom d-flex align-items-center justify-content-between">
            <div>
              <div class="fw-semibold"><?php echo htmlspecialchars($cat['name']); ?></div>
              <?php if ($cat['parent_name']): ?>
                <small class="text-muted"><?php echo htmlspecialchars($cat['parent_icon'].' '.$cat['parent_name']); ?></small>
              <?php else: ?>
                <small class="text-muted">ไม่ผูกหมวดหมู่หลัก</small>
              <?php endif; ?>
            </div>
            <span class="badge <?php echo $cat['is_active'] ? 'badge-status-active' : 'badge-status-inactive'; ?> rounded-pill px-2">
              <?php echo $cat['is_active'] ? 'เปิด' : 'ปิด'; ?>
            </span>
          </div>
          <div class="p-3">
            <?php if ($cat['description']): ?>
              <p class="text-muted mb-2" style="font-size:.82rem"><?php echo htmlspecialchars($cat['description']); ?></p>
            <?php endif; ?>
            <div class="d-flex align-items-center justify-content-between">
              <span class="text-muted" style="font-size:.8rem">🏷️ <?php echo $cat['product_count']; ?> สินค้า</span>
              <div class="btn-group btn-group-sm">
                <button class="btn btn-outline-primary rounded-start-pill"
                  onclick='openEditCat(<?php echo json_encode($cat); ?>)'>✏️</button>
                <a href="?action=toggle&id=<?php echo $cat['id']; ?>"
                   class="btn btn-outline-secondary"><?php echo $cat['is_active'] ? '⛔' : '✅'; ?></a>
                <a href="?action=delete&id=<?php echo $cat['id']; ?>"
                   class="btn btn-outline-danger rounded-end-pill"
                   onclick="return confirm('ลบหมวดหมู่นี้?')">🗑️</a>
              </div>
            </div>
          </div>
        </div>
      </div>
    <?php endforeach; ?>
  </div>
<?php endif; ?>

<!-- ── CATEGORY MODAL ─────────────────────────────────── -->
<div class="modal fade" id="catModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content rounded-4">
      <form method="POST">
        <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
        <input type="hidden" name="cat_id" id="cat_id">
        <div class="modal-header border-0 pb-0">
          <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">
          <div class="mb-3">
            <label class="form-label fw-semibold">ชื่อหมวดหมู่ <span class="text-danger">*</span></label>
            <input type="text" name="name" id="cat_name" class="form-control" required placeholder="เช่น เสื้อ Oversize, สินค้าใหม่">
          </div>
          <div class="mb-3">
            <label class="form-label fw-semibold">ผูกกับหมวดหมู่หลัก</label>
            <select name="category_id" id="cat_parent" class="form-select">
              <option value="">-- ไม่ผูก --</option>
              <?php foreach ($mainCategories as $mc): ?>
                <option value="<?php echo $mc['id']; ?>"><?php echo htmlspecialchars($mc['icon'].' '.$mc['name']); ?></option>
              <?php endforeach; ?>
            </select>
            <div class="form-text">เลือกหมวดหมู่หลักเพื่อให้สินค้าปรากฏถูกที่</div>
          </div>
          <div class="mb-3">
            <label class="form-label fw-semibold">คำอธิบาย</label>
            <textarea name="description" id="cat_desc" class="form-control" rows="2" placeholder="อธิบายหมวดหมู่..."></textarea>
          </div>
          <div class="mb-3">
            <label class="form-label fw-semibold">ลำดับการแสดง</label>
            <input type="number" name="sort_order" id="cat_sort" class="form-control" value="0" min="0">
          </div>
        </div>
        <div class="modal-footer border-0">
          <button type="button" class="btn btn-light rounded-pill" data-bs-dismiss="modal">ยกเลิก</button>
          <button type="submit" class="btn btn-vendor-primary rounded-pill px-4">💾 บันทึก</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
function resetCatForm() {
  document.getElementById('catModalTitle').textContent = '+ เพิ่มหมวดหมู่ใหม่';
  ['cat_id','cat_name','cat_desc'].forEach(id => document.getElementById(id).value = '');
  document.getElementById('cat_parent').value = '';
  document.getElementById('cat_sort').value = 0;
}
function openEditCat(c) {
  document.getElementById('catModalTitle').textContent = '✏️ แก้ไขหมวดหมู่';
  document.getElementById('cat_id').value     = c.id;
  document.getElementById('cat_name').value   = c.name;
  document.getElementById('cat_parent').value = c.category_id || '';
  document.getElementById('cat_desc').value   = c.description || '';
  document.getElementById('cat_sort').value   = c.sort_order || 0;
  new bootstrap.Modal(document.getElementById('catModal')).show();
}
</script>

<?php require_once __DIR__ . '/vendor_footer.php'; ?>
