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

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

        $existingStmt = $db->prepare('SELECT id, name, latitude, longitude, radius_meters FROM masjids WHERE id = ?');
        $existingStmt->execute([$id]);
        $existing = $existingStmt->fetch(PDO::FETCH_ASSOC);

        if (!$existing) {
            http_response_code(404);
            echo json_encode(['error' => 'Masjid not found']);
            exit;
        }

        $updates = [];
        $params = [];

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

            $updates[] = 'name = ?';
            $params[] = $name;
        }

        $hasLatitude = array_key_exists('latitude', $data);
        $hasLongitude = array_key_exists('longitude', $data);
        if ($hasLatitude || $hasLongitude) {
            $latitude = $hasLatitude ? $data['latitude'] : $existing['latitude'];
            $longitude = $hasLongitude ? $data['longitude'] : $existing['longitude'];

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

            $latitude = (float)$latitude;
            $longitude = (float)$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;
            }

            $updates[] = 'latitude = ?';
            $updates[] = 'longitude = ?';
            $params[] = $latitude;
            $params[] = $longitude;
        }

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

            $updates[] = 'radius_meters = ?';
            $params[] = $radius;
        }

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

        $updates[] = 'updated_at = CURRENT_TIMESTAMP';
        $params[] = $id;

        $updateSql = 'UPDATE masjids SET ' . implode(', ', $updates) . ' WHERE id = ?';
        $updateStmt = $db->prepare($updateSql);
        $updateStmt->execute($params);

        $resultStmt = $db->prepare('SELECT id, name, latitude, longitude, radius_meters, created_at, updated_at FROM masjids WHERE id = ?');
        $resultStmt->execute([$id]);
        $masjid = $resultStmt->fetch(PDO::FETCH_ASSOC);

        $cleanupResult = cleanupNeedPointsOutsideMasjidCoverage($db, $id);

        echo json_encode([
            'success' => true,
            'masjid' => $masjid,
            'deleted_need_points' => $cleanupResult['deleted_count'],
            'deleted_need_point_ids' => $cleanupResult['deleted_ids']
        ]);
    } 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']);
}
?>
