<?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['id'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing required field: id']);
            exit;
        }

        $id = intval($data['id']);
        $db = getDB();

        // Determine what type of update this is
        $hasCoordinates = isset($data['coordinates']) && isset($data['area_sqm']);
        $hasName = isset($data['name']);
        $hasCertificateType = isset($data['certificate_type']);

        // Full edit (multiple fields including name or certificate_type)
        if ($hasName || $hasCertificateType || $hasCoordinates) {
            $updates = [];
            $params = [];

            if ($hasName) {
                if (empty($data['name'])) {
                    http_response_code(400);
                    echo json_encode(['error' => 'Name cannot be empty']);
                    exit;
                }
                $updates[] = 'name = ?';
                $params[] = $data['name'];
            }

            if ($hasCertificateType) {
                $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;
                }
                $updates[] = 'certificate_type = ?';
                $params[] = $data['certificate_type'];
            }

            if ($hasCoordinates) {
                // 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']);
                    exit;
                }

                // Validate each coordinate
                foreach ($data['coordinates'] as $coord) {
                    if (!is_array($coord) || count($coord) !== 2 || !is_numeric($coord[0]) || !is_numeric($coord[1])) {
                        http_response_code(400);
                        echo json_encode(['error' => 'Invalid coordinate format']);
                        exit;
                    }

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

                    if ($lat < -90 || $lat > 90 || $lng < -180 || $lng > 180) {
                        http_response_code(400);
                        echo json_encode(['error' => 'Invalid coordinate range']);
                        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;
                }

                $updates[] = 'coordinates = ?';
                $updates[] = 'area_sqm = ?';
                $params[] = json_encode($data['coordinates']);
                $params[] = floatval($data['area_sqm']);
            }

            if (empty($updates)) {
                http_response_code(400);
                echo json_encode(['error' => 'No fields to update']);
                exit;
            }

            // Add updated_at and id to params
            $updates[] = 'updated_at = CURRENT_TIMESTAMP';
            $params[] = $id;

            $sql = 'UPDATE land_parcels SET ' . implode(', ', $updates) . ' WHERE id = ?';
            $stmt = $db->prepare($sql);
            $stmt->execute($params);

            // Fetch updated record
            $getStmt = $db->prepare('SELECT * FROM land_parcels WHERE id = ?');
            $getStmt->execute([$id]);
            $parcel = $getStmt->fetch(PDO::FETCH_ASSOC);

            if ($parcel) {
                $parcel['coordinates'] = json_decode($parcel['coordinates'], true);
            }

            echo json_encode([
                'success' => true,
                'polygon' => $parcel
            ]);
        } else {
            http_response_code(400);
            echo json_encode(['error' => 'No fields to update']);
        }
    } 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']);
}
?>
