<?php
/**
 * Brands API
 * GET    /api/brands.php         - Get all brands
 * POST   /api/brands.php         - Create brand (auth required)
 * PUT    /api/brands.php?id=xxx  - Update brand (auth required)
 * DELETE /api/brands.php?id=xxx  - Delete brand (auth required)
 */

require_once 'config.php';

$method = $_SERVER['REQUEST_METHOD'];
$id = $_GET['id'] ?? null;
$db = getDB();

// GET - List all brands
if ($method === 'GET') {
    $stmt = $db->query("SELECT id, name, logo_url, alt_text, order_num as `order` FROM brands ORDER BY order_num ASC");
    $brands = $stmt->fetchAll();
    jsonResponse($brands);
}

// POST - Create new brand
if ($method === 'POST') {
    requireAuth();
    $input = getJsonInput();
    
    $name = $input['name'] ?? '';
    if (empty($name)) {
        errorResponse('Name harus diisi', 400);
    }
    
    $id = generateUUID();
    $logoUrl = $input['logo_url'] ?? '';
    $altText = $input['alt_text'] ?? '';
    $order = (int)($input['order'] ?? 0);
    
    $stmt = $db->prepare("INSERT INTO brands (id, name, logo_url, alt_text, order_num) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([$id, $name, $logoUrl, $altText, $order]);
    
    jsonResponse([
        'id' => $id,
        'name' => $name,
        'logo_url' => $logoUrl,
        'alt_text' => $altText,
        'order' => $order
    ], 201);
}

// PUT - Update brand
if ($method === 'PUT') {
    requireAuth();
    
    if (!$id) {
        errorResponse('ID harus disertakan', 400);
    }
    
    $stmt = $db->prepare("SELECT * FROM brands WHERE id = ?");
    $stmt->execute([$id]);
    $brand = $stmt->fetch();
    
    if (!$brand) {
        errorResponse('Brand tidak ditemukan', 404);
    }
    
    $input = getJsonInput();
    
    $name = $input['name'] ?? $brand['name'];
    $logoUrl = $input['logo_url'] ?? $brand['logo_url'];
    $altText = $input['alt_text'] ?? $brand['alt_text'];
    $order = isset($input['order']) ? (int)$input['order'] : $brand['order_num'];
    
    $stmt = $db->prepare("UPDATE brands SET name = ?, logo_url = ?, alt_text = ?, order_num = ? WHERE id = ?");
    $stmt->execute([$name, $logoUrl, $altText, $order, $id]);
    
    jsonResponse([
        'id' => $id,
        'name' => $name,
        'logo_url' => $logoUrl,
        'alt_text' => $altText,
        'order' => $order
    ]);
}

// DELETE - Delete brand
if ($method === 'DELETE') {
    requireAuth();
    
    if (!$id) {
        errorResponse('ID harus disertakan', 400);
    }
    
    $stmt = $db->prepare("SELECT id FROM brands WHERE id = ?");
    $stmt->execute([$id]);
    
    if (!$stmt->fetch()) {
        errorResponse('Brand tidak ditemukan', 404);
    }
    
    $db->prepare("DELETE FROM brands WHERE id = ?")->execute([$id]);
    
    jsonResponse(['message' => 'Brand berhasil dihapus']);
}

errorResponse('Method not allowed', 405);
