<?php
/**
 * About Cards API
 * GET    /api/about.php         - Get all about cards
 * POST   /api/about.php         - Create about card (auth required)
 * PUT    /api/about.php?id=xxx  - Update about card (auth required)
 * DELETE /api/about.php?id=xxx  - Delete about card (auth required)
 */

require_once 'config.php';

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

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

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

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

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

errorResponse('Method not allowed', 405);
