<?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 = (int)$data['id'];
        $db = getDB();

        // Determine what type of update this is
        $hasCoordinates = isset($data['latitude']) && isset($data['longitude']);
        $hasName = isset($data['name']);
        $hasNomorSpbu = isset($data['nomor_spbu']);
        $hasStatus = isset($data['open_24_hours']);

        // Full edit (multiple fields including coordinates or name)
        if ($hasName || ($hasCoordinates && ($hasName || $hasNomorSpbu || $hasStatus))) {
            $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 ($hasNomorSpbu) {
                $updates[] = 'nomor_spbu = ?';
                $params[] = $data['nomor_spbu'] ?: null;
            }

            if ($hasCoordinates) {
                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 || $longitude < -180 || $longitude > 180) {
                    http_response_code(400);
                    echo json_encode(['error' => 'Invalid coordinates']);
                    exit;
                }

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

            if ($hasStatus) {
                $updates[] = 'open_24_hours = ?';
                $params[] = (int)$data['open_24_hours'];
            }

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

            // Add id to params
            $params[] = $id;

            $sql = 'UPDATE markers SET ' . implode(', ', $updates) . ' WHERE id = ?';
            $stmt = $db->prepare($sql);
            $stmt->execute($params);

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

            echo json_encode([
                'success' => true,
                'marker' => $marker
            ]);
        }
        // Coordinates-only update (drag)
        else if ($hasCoordinates) {
            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;
            }

            $stmt = $db->prepare('UPDATE markers SET latitude = ?, longitude = ? WHERE id = ?');
            $stmt->execute([$latitude, $longitude, $id]);

            echo json_encode([
                'success' => true,
                'id' => $id,
                'latitude' => $latitude,
                'longitude' => $longitude
            ]);
        }
        // Status-only update (toggle)
        else if ($hasStatus) {
            $open_24_hours = (int)$data['open_24_hours'];
            $stmt = $db->prepare('UPDATE markers SET open_24_hours = ? WHERE id = ?');
            $stmt->execute([$open_24_hours, $id]);

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

