$(document).ready(function () {
    // Initialize map
    var map = L.map('forestMap').setView([0.3476, 32.5825], 7); // Uganda center

    // Add OSM tile layer
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap'
    }).addTo(map);

    // FeatureGroup for drawn layers
    var drawnItems = new L.FeatureGroup();
    map.addLayer(drawnItems);

    // Draw control
    var drawControl = new L.Control.Draw({
        edit: { featureGroup: drawnItems },
        draw: {
            marker: false,
            circle: false,
            circlemarker: false,
            polyline: false,
            polygon: true,
            rectangle: true
        }
    });
    map.addControl(drawControl);

    // Capture draw events
    map.on(L.Draw.Event.CREATED, function (e) {
        drawnItems.clearLayers(); // only keep one shape
        var layer = e.layer;
        drawnItems.addLayer(layer);

        // Save GeoJSON into hidden input
        var geojson = layer.toGeoJSON();
        $('#boundaryGeoJson').val(JSON.stringify(geojson.geometry));
    });

    // Save form with AJAX
    $('#saveForest').click(function () {
        var formData = $('#forestForm').serialize();

        $.ajax({
            url: base_url +'forests/save', // CI4 controller endpoint
            type: 'POST',
            data: formData,
            success: function (res) {
                alert('Forest saved successfully!');
                $('#forestModal').modal('hide');
                location.reload();
            },
            error: function (xhr) {
                alert('Error saving forest!');
            }
        });
    });
});
