<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
header('Content-Type: application/json');

require_once 'config.php';

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    try {
        $db = getDB();
        $stmt = $db->query('SELECT id, name, certificate_type, coordinates, area_sqm, created_at, updated_at FROM land_parcels ORDER BY created_at DESC');
        $parcels = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Decode coordinates JSON for each parcel
        foreach ($parcels as &$parcel) {
            $parcel['coordinates'] = json_decode($parcel['coordinates'], true);
        }

        echo json_encode([
            'success' => true,
            'polygons' => $parcels
        ]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}
?>
