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

requireAdmin();
$db = getDBConnection();

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

// Add/Edit brand
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCSRFToken($_POST['csrf_token'] ?? '');
    $brandId = (int)($_POST['brand_id'] ?? 0);
    $name = sanitize($_POST['name'] ?? '');
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    
    // Handle Logo Upload (Simplified)
    $logo_path = $_POST['existing_logo'] ?? '';
    // If we had file upload logic here, we'd process $_FILES['logo']

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

$brands = $db->query("SELECT b.*, COUNT(p.id) as product_count FROM brands b LEFT JOIN products p ON b.id = p.brand_id GROUP BY b.id ORDER BY b.name 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="#brandModal" onclick="resetBrandForm()">+ เพิ่มแบรนด์ใหม่</button>
</div>

<div class="card card-custom p-4">
  <table class="table table-hover align-middle">
    <thead>
      <tr>
        <th>ID</th>
        <th>โลโก้</th>
        <th>ชื่อแบรนด์</th>
        <th>สถานะ</th>
        <th>จำนวนสินค้า</th>
        <th>จัดการ</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($brands as $b): ?>
        <tr>
          <td><?php echo $b['id']; ?></td>
          <td>
            <?php if(!empty($b['logo_path'])): ?>
                <img src="<?php echo htmlspecialchars($b['logo_path']); ?>" width="40" height="40" class="rounded-circle object-cover">
            <?php else: ?>
                <div class="bg-light rounded-circle d-flex justify-content-center align-items-center fw-bold text-muted" style="width: 40px; height: 40px;">?</div>
            <?php endif; ?>
          </td>
          <td class="fw-bold"><?php echo sanitize($b['name']); ?></td>
          <td>
            <?php if ($b['is_active']): ?>
                <span class="badge bg-success">เปิดใช้งาน</span>
            <?php else: ?>
                <span class="badge bg-secondary">ปิดใช้งาน</span>
            <?php endif; ?>
          </td>
          <td><span class="badge bg-info text-dark"><?php echo $b['product_count']; ?> ชิ้น</span></td>
          <td>
            <button class="btn btn-sm btn-edit-custom rounded-pill me-1" onclick='editBrand(<?php echo json_encode($b); ?>)'>✏️ แก้ไข</button>
            <a href="brands.php?action=delete&id=<?php echo $b['id']; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('ยืนยันการลบแบรนด์นี้?')">🗑️ ลบ</a>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

<!-- Modal Brand Form -->
<div class="modal fade" id="brandModal" 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="brandModalTitle">เพิ่มแบรนด์ใหม่</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="brand_id" id="brand_id">

          <div class="mb-3">
            <label class="form-label">ชื่อแบรนด์ *</label>
            <input type="text" name="name" id="brand_name" class="form-control" required placeholder="เช่น Nike">
          </div>
          
          <div class="mb-3">
            <label class="form-label">รูปโลโก้ (URL ชั่วคราว)</label>
            <input type="text" name="existing_logo" id="brand_logo" class="form-control" placeholder="https://...">
          </div>

          <div class="form-check form-switch mb-3">
            <input class="form-check-input" type="checkbox" name="is_active" id="brand_active" checked>
            <label class="form-check-label" for="brand_active">เปิดใช้งาน (แสดงที่หน้าเว็บ)</label>
          </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 resetBrandForm() {
    document.getElementById('brandModalTitle').innerText = 'เพิ่มแบรนด์ใหม่';
    document.getElementById('brand_id').value = '';
    document.getElementById('brand_name').value = '';
    document.getElementById('brand_logo').value = '';
    document.getElementById('brand_active').checked = true;
}

function editBrand(b) {
    document.getElementById('brandModalTitle').innerText = 'แก้ไขแบรนด์';
    document.getElementById('brand_id').value = b.id;
    document.getElementById('brand_name').value = b.name;
    document.getElementById('brand_logo').value = b.logo_path || '';
    document.getElementById('brand_active').checked = b.is_active == 1;
    new bootstrap.Modal(document.getElementById('brandModal')).show();
}
</script>

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