<?php
header('Content-Type: application/json');
require_once 'config.php';

try {
    $db = getDB();

    // Get optional filter parameter
    $area_type = isset($_GET['area_type']) ? $_GET['area_type'] : '';

    // Build SQL query
    $sql = 'SELECT id, name, area_type, geometry, population, created_at, updated_at FROM pontianak_areas';

    if ($area_type) {
        $sql .= ' WHERE area_type = ?';
        $stmt = $db->prepare($sql);
        $stmt->execute([$area_type]);
    } else {
        $stmt = $db->prepare($sql);
        $stmt->execute();
    }

    $areas = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Decode geometry JSON for each area
    foreach ($areas as &$area) {
        $area['geometry'] = json_decode($area['geometry'], true);
    }

    // Return success response
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'areas' => $areas
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Database error: ' . $e->getMessage()
    ]);
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>
