<?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['length_meters']);
        $hasName = isset($data['name']);
        $hasRoadType = isset($data['road_type']);
        $hasConditionStatus = isset($data['condition_status']);

        // Full edit (multiple fields including name or road_type)
        if ($hasName || $hasRoadType || $hasCoordinates || $hasConditionStatus) {
            $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 ($hasRoadType) {
                $validTypes = ['Nasional', 'Provinsi', 'Kabupaten'];
                if (!in_array($data['road_type'], $validTypes)) {
                    http_response_code(400);
                    echo json_encode(['error' => 'Invalid road_type. Must be: Nasional, Provinsi, or Kabupaten']);
                    exit;
                }
                $updates[] = 'road_type = ?';
                $params[] = $data['road_type'];
            }

            if ($hasConditionStatus) {
                $validConditions = ['normal', 'minor_damage', 'major_damage'];
                if (!in_array($data['condition_status'], $validConditions)) {
                    http_response_code(400);
                    echo json_encode(['error' => 'Invalid condition_status. Must be: normal, minor_damage, or major_damage']);
                    exit;
                }
                $updates[] = 'condition_status = ?';
                $params[] = $data['condition_status'];
            }

            if ($hasCoordinates) {
                // Validate coordinates array
                if (!is_array($data['coordinates']) || count($data['coordinates']) < 2) {
                    http_response_code(400);
                    echo json_encode(['error' => 'Coordinates must be an array with at least 2 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 length_meters is positive
                if (!is_numeric($data['length_meters']) || $data['length_meters'] <= 0) {
                    http_response_code(400);
                    echo json_encode(['error' => 'Length must be a positive number']);
                    exit;
                }

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

            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 roads SET ' . implode(', ', $updates) . ' WHERE id = ?';
            $stmt = $db->prepare($sql);
            $stmt->execute($params);

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

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

            echo json_encode([
                'success' => true,
                'line' => $road
            ]);
        } 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']);
}
?>
