<?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['road_type']) || !isset($data['coordinates']) || !isset($data['length_meters'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing required fields: name, road_type, coordinates, or length_meters']);
            exit;
        }

        // Validate road_type
        $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;
        }

        // 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) {
                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' => 'Road name cannot be empty']);
            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;
        }

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

        $db = getDB();

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

        $stmt = $db->prepare('INSERT INTO roads (name, road_type, coordinates, length_meters, condition_status) VALUES (?, ?, ?, ?, ?)');
        $stmt->execute([
            $data['name'],
            $data['road_type'],
            $coordinatesJson,
            floatval($data['length_meters']),
            $condition_status
        ]);

        echo json_encode([
            'success' => true,
            'id' => $db->lastInsertId(),
            'name' => $data['name'],
            'road_type' => $data['road_type'],
            'coordinates' => $data['coordinates'],
            'length_meters' => floatval($data['length_meters']),
            'condition_status' => $condition_status,
            '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']);
}
?>
