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

require_once 'config.php';

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

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

// POST - Create new service
if ($method === 'POST') {
    requireAuth();
    $input = getJsonInput();
    
    $title = $input['title'] ?? '';
    if (empty($title)) {
        errorResponse('Title harus diisi', 400);
    }
    
    $id = generateUUID();
    $description = $input['description'] ?? '';
    $icon = $input['icon'] ?? 'wrench';
    $order = (int)($input['order'] ?? 0);
    
    $stmt = $db->prepare("INSERT INTO services (id, title, description, icon, order_num) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([$id, $title, $description, $icon, $order]);
    
    jsonResponse([
        'id' => $id,
        'title' => $title,
        'description' => $description,
        'icon' => $icon,
        'order' => $order
    ], 201);
}

// PUT - Update service
if ($method === 'PUT') {
    requireAuth();
    
    if (!$id) {
        errorResponse('ID harus disertakan', 400);
    }
    
    $stmt = $db->prepare("SELECT * FROM services WHERE id = ?");
    $stmt->execute([$id]);
    $service = $stmt->fetch();
    
    if (!$service) {
        errorResponse('Service tidak ditemukan', 404);
    }
    
    $input = getJsonInput();
    
    $title = $input['title'] ?? $service['title'];
    $description = $input['description'] ?? $service['description'];
    $icon = $input['icon'] ?? $service['icon'];
    $order = isset($input['order']) ? (int)$input['order'] : $service['order_num'];
    
    $stmt = $db->prepare("UPDATE services SET title = ?, description = ?, icon = ?, order_num = ? WHERE id = ?");
    $stmt->execute([$title, $description, $icon, $order, $id]);
    
    jsonResponse([
        'id' => $id,
        'title' => $title,
        'description' => $description,
        'icon' => $icon,
        'order' => $order
    ]);
}

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

errorResponse('Method not allowed', 405);
