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

require_once 'config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $data = json_decode(file_get_contents('php://input'), true);

        // Validate required fields
        if (!isset($data['name']) || !isset($data['certificate_type']) || !isset($data['coordinates']) || !isset($data['area_sqm'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing required fields: name, certificate_type, coordinates, or area_sqm']);
            exit;
        }

        // Validate certificate_type
        $validTypes = ['SHM', 'HGB', 'HGU', 'HP'];
        if (!in_array($data['certificate_type'], $validTypes)) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid certificate_type. Must be: SHM, HGB, HGU, or HP']);
            exit;
        }

        // Validate coordinates array (minimum 3 for polygon)
        if (!is_array($data['coordinates']) || count($data['coordinates']) < 3) {
            http_response_code(400);
            echo json_encode(['error' => 'Coordinates must be an array with at least 3 points for a polygon']);
            exit;
        }

        // Validate each coordinate
        foreach ($data['coordinates'] as $coord) {
            if (!is_array($coord) || count($coord) !== 2) {
                http_response_code(400);
                echo json_encode(['error' => 'Each coordinate must be [latitude, longitude]']);
                exit;
            }

            $lat = floatval($coord[0]);
            $lng = floatval($coord[1]);

            if (!is_numeric($coord[0]) || !is_numeric($coord[1])) {
                http_response_code(400);
                echo json_encode(['error' => 'Coordinates must be numeric values']);
                exit;
            }

            if ($lat < -90 || $lat > 90 || $lng < -180 || $lng > 180) {
                http_response_code(400);
                echo json_encode(['error' => 'Invalid coordinate range. Latitude: -90 to 90, Longitude: -180 to 180']);
                exit;
            }
        }

        // Validate name is not empty
        if (empty(trim($data['name']))) {
            http_response_code(400);
            echo json_encode(['error' => 'Parcel name cannot be empty']);
            exit;
        }

        // Validate area_sqm is positive
        if (!is_numeric($data['area_sqm']) || $data['area_sqm'] <= 0) {
            http_response_code(400);
            echo json_encode(['error' => 'Area must be a positive number']);
            exit;
        }

        $db = getDB();

        // Store coordinates as JSON
        $coordinatesJson = json_encode($data['coordinates']);

        $stmt = $db->prepare('INSERT INTO land_parcels (name, certificate_type, coordinates, area_sqm) VALUES (?, ?, ?, ?)');
        $stmt->execute([
            $data['name'],
            $data['certificate_type'],
            $coordinatesJson,
            floatval($data['area_sqm'])
        ]);

        echo json_encode([
            'success' => true,
            'id' => $db->lastInsertId(),
            'name' => $data['name'],
            'certificate_type' => $data['certificate_type'],
            'coordinates' => $data['coordinates'],
            'area_sqm' => floatval($data['area_sqm']),
            'created_at' => date('Y-m-d H:i:s')
        ]);
    } 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']);
}
?>
