<?php
require_once __DIR__ . '/../../config/cors.php';
require_once __DIR__ . '/../../config/jwt.php';

auth_required();

// ── Output compression (reduces payload ~5x) ─────────────────────────────────
if (!headers_sent()) {
    $acceptGzip = strpos($_SERVER['HTTP_ACCEPT_ENCODING'] ?? '', 'gzip') !== false;
    if ($acceptGzip && function_exists('ob_gzhandler')) {
        ob_start('ob_gzhandler');
    }
}

$zone = $_GET['zone'] ?? null;

// Use explicit column list — avoids fetching internal MySQL metadata cols
// polygon_coords IS included (needed by app to draw parcels)
$cols = 'id, kml_id, zone, sheet_number, parcel_no, shape_area_sqm,
          grid_map_page, polygon_coords, centroid_lat, centroid_lng, survey_status';

if ($zone) {
    $stmt = $pdo->prepare("SELECT $cols FROM parcels WHERE zone = ?");
    $stmt->execute([$zone]);
} else {
    $stmt = $pdo->query("SELECT $cols FROM parcels");
}

// Stream JSON without buffering all rows in PHP memory at once
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
