<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);  // Don't display errors in output
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['latitude']) || !isset($data['longitude'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing required fields: name, latitude, or longitude']);
            exit;
        }

        // Validate coordinates are numeric
        if (!is_numeric($data['latitude']) || !is_numeric($data['longitude'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Latitude and longitude must be numeric values']);
            exit;
        }

        $db = getDB();
        $stmt = $db->prepare('INSERT INTO markers (name, nomor_spbu, latitude, longitude, open_24_hours) VALUES (?, ?, ?, ?, ?)');
        $open_24_hours = isset($data['open_24_hours']) ? (int)$data['open_24_hours'] : 0;
        $nomor_spbu = isset($data['nomor_spbu']) ? $data['nomor_spbu'] : null;

        $stmt->execute([
            $data['name'],
            $nomor_spbu,
            (float)$data['latitude'],
            (float)$data['longitude'],
            $open_24_hours
        ]);

        echo json_encode([
            'success' => true,
            'id' => $db->lastInsertId(),
            'name' => $data['name'],
            'nomor_spbu' => $nomor_spbu,
            'latitude' => (float)$data['latitude'],
            'longitude' => (float)$data['longitude'],
            'open_24_hours' => $open_24_hours
        ]);
    } 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']);
}
?>
