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

try {
    $db = getDB();

    // Get filter parameters
    $search = isset($_GET['search']) ? '%' . $_GET['search'] . '%' : '';
    $from_date = isset($_GET['from_date']) ? $_GET['from_date'] : '';
    $to_date = isset($_GET['to_date']) ? $_GET['to_date'] : '';
    $certificate_type = isset($_GET['certificate_type']) ? $_GET['certificate_type'] : '';

    // Build dynamic WHERE clause
    $where_clauses = [];
    $params = [];

    if ($search !== '%' && $search !== '%') {
        $where_clauses[] = '(name LIKE ?)';
        $params[] = $search;
    }

    if ($from_date) {
        $where_clauses[] = '(DATE(created_at) >= ?)';
        $params[] = $from_date;
    }

    if ($to_date) {
        $where_clauses[] = '(DATE(created_at) <= ?)';
        $params[] = $to_date;
    }

    if ($certificate_type) {
        $where_clauses[] = '(certificate_type = ?)';
        $params[] = $certificate_type;
    }

    // Build SQL query
    $sql = 'SELECT id, name, certificate_type, coordinates, area_sqm, created_at, updated_at FROM land_parcels';

    if (count($where_clauses) > 0) {
        $sql .= ' WHERE ' . implode(' AND ', $where_clauses);
    }

    $sql .= ' ORDER BY created_at DESC';

    // Execute query
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $parcels = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

    // Count total for query
    $count_sql = 'SELECT COUNT(*) as total FROM land_parcels' . (count($where_clauses) > 0 ? ' WHERE ' . implode(' AND ', $where_clauses) : '');
    $count_stmt = $db->prepare($count_sql);
    $count_stmt->execute($params);
    $total = $count_stmt->fetch(PDO::FETCH_ASSOC)['total'];

    // Prepare filters applied info
    $filters_applied = [];
    if ($search !== '%' && $search !== '%') {
        $filters_applied['search'] = str_replace('%', '', $search);
    }
    if ($from_date || $to_date) {
        $filters_applied['date_range'] = [];
        if ($from_date) $filters_applied['date_range'][] = $from_date;
        if ($to_date) $filters_applied['date_range'][] = $to_date;
    }
    if ($certificate_type) {
        $filters_applied['certificate_type'] = $certificate_type;
    }

    // Return success response
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'polygons' => $parcels,
        'total' => $total,
        'filters_applied' => $filters_applied
    ]);

} 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()
    ]);
}
?>
