<?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);

        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;
        }

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

        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;
        }

        $latitude = (float)$data['latitude'];
        $longitude = (float)$data['longitude'];

        if ($latitude < -90 || $latitude > 90) {
            http_response_code(400);
            echo json_encode(['error' => 'Latitude must be between -90 and 90']);
            exit;
        }

        if ($longitude < -180 || $longitude > 180) {
            http_response_code(400);
            echo json_encode(['error' => 'Longitude must be between -180 and 180']);
            exit;
        }

        $radiusError = null;
        $radius = normalizeMasjidRadius(isset($data['radius_meters']) ? $data['radius_meters'] : null, $radiusError);
        if ($radius === null) {
            http_response_code(400);
            echo json_encode(['error' => $radiusError]);
            exit;
        }

        $db = getDB();
        $stmt = $db->prepare('INSERT INTO masjids (name, latitude, longitude, radius_meters) VALUES (?, ?, ?, ?)');
        $stmt->execute([$name, $latitude, $longitude, $radius]);

        echo json_encode([
            'success' => true,
            'masjid' => [
                'id' => (int)$db->lastInsertId(),
                'name' => $name,
                'latitude' => $latitude,
                'longitude' => $longitude,
                'radius_meters' => $radius
            ]
        ]);
    } 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']);
}
?>
