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

require_once 'config.php';

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

// GET - List all areas
if ($method === 'GET') {
    $stmt = $db->query("SELECT * FROM areas");
    $areas = $stmt->fetchAll();
    
    // Decode cities JSON for each area
    foreach ($areas as &$area) {
        $area['cities'] = json_decode($area['cities'], true) ?? [];
    }
    
    jsonResponse($areas);
}

// POST - Create new area
if ($method === 'POST') {
    requireAuth();
    $input = getJsonInput();
    
    $province = $input['province'] ?? '';
    if (empty($province)) {
        errorResponse('Province harus diisi', 400);
    }
    
    $id = generateUUID();
    $cities = json_encode($input['cities'] ?? []);
    
    $stmt = $db->prepare("INSERT INTO areas (id, province, cities) VALUES (?, ?, ?)");
    $stmt->execute([$id, $province, $cities]);
    
    jsonResponse([
        'id' => $id,
        'province' => $province,
        'cities' => $input['cities'] ?? []
    ], 201);
}

// PUT - Update area
if ($method === 'PUT') {
    requireAuth();
    
    if (!$id) {
        errorResponse('ID harus disertakan', 400);
    }
    
    $stmt = $db->prepare("SELECT * FROM areas WHERE id = ?");
    $stmt->execute([$id]);
    $area = $stmt->fetch();
    
    if (!$area) {
        errorResponse('Area tidak ditemukan', 404);
    }
    
    $input = getJsonInput();
    
    $province = $input['province'] ?? $area['province'];
    $cities = isset($input['cities']) ? json_encode($input['cities']) : $area['cities'];
    
    $stmt = $db->prepare("UPDATE areas SET province = ?, cities = ? WHERE id = ?");
    $stmt->execute([$province, $cities, $id]);
    
    jsonResponse([
        'id' => $id,
        'province' => $province,
        'cities' => isset($input['cities']) ? $input['cities'] : (json_decode($area['cities'], true) ?? [])
    ]);
}

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

errorResponse('Method not allowed', 405);
