


/**====================================================================
*   Forest
*=======================================================================*/
(function($) {
    $(document).ready(function() {


        // Initialize Bootstrap components safely
        if (typeof bootstrap !== 'undefined') {

    const foModal = new bootstrap.Modal('#forestModal');
    const foForm = $('#forestForm');
    // Initialize map
    var map = L.map('addForestMap').setView([0.3476, 32.5825], 7); // Center Uganda
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap'
    }).addTo(map);

    var drawnItems = new L.FeatureGroup();
    map.addLayer(drawnItems);

    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 new drawing
    map.on(L.Draw.Event.CREATED, function (e) {
        drawnItems.clearLayers(); // allow only one polygon
        var layer = e.layer;
        drawnItems.addLayer(layer);

        var geojson = layer.toGeoJSON();
        $('#boundaryGeoJson').val(JSON.stringify(geojson.geometry));
    });

    // Capture edit event
    map.on(L.Draw.Event.EDITED, function (e) {
        e.layers.eachLayer(function (layer) {
            var geojson = layer.toGeoJSON();
            $('#boundaryGeoJson').val(JSON.stringify(geojson.geometry));
        });
    });

    // Save (Create/Update) Forest
    foForm.on('submit', function(event) {  // Changed 'e' to 'event'
        event.preventDefault();
        
        const formData = new FormData(this);

        $.ajax({
            url: base_url +'administrator/redd/forests', // controller method (same for create/update)
            type: 'POST',
            data: formData,
            processData: false, // Required for file upload
            contentType: false, // Required for file upload
            dataType: 'json',
            success: function (res) {
                if (res.success) {
                    toastr.success(res.message);
                    foModal.hide();
                    setTimeout(() => location.reload(), 1000);
                } else {
                    let errors = res.errors ? JSON.stringify(res.errors) : res.message;
                    toastr.error("Error: " + errors);
                }
            },
            error: function (xhr) {
                toastr.error('Server error: ' + xhr.status);
            }
        });
    });

    // Edit Forest (populate modal)
    $(document).on('click', '.editForest', function () {
        let forestId = $(this).data('id');

        $.get(base_url +'administrator/redd/forests', { id: forestId }, function (res) {
            if (res.data) {
                let forest = res.data;

                // Fill form fields
                $('#forestForm [name=id]').val(forest.id);
                $('#forestForm [name=name]').val(forest.name);
                $('#forestForm [name=classification]').val(forest.classification);
                $('#forestForm [name=size]').val(forest.size);
                $('#forestForm [name=location_description]').val(forest.location_description);
                $('#forestForm [name=geo_lat]').val(forest.geo_lat);
                $('#forestForm [name=geo_long]').val(forest.geo_long);
                $('#forestForm [name=description]').val(forest.description);

                // If boundary exists, load into map
                if (forest.boundary_file) {
                    drawnItems.clearLayers();
                    try {
                        var boundary = JSON.parse(forest.boundary_file);
                        var geoLayer = L.geoJSON(boundary).addTo(drawnItems);
                        map.fitBounds(geoLayer.getBounds());
                        $('#boundaryGeoJson').val(JSON.stringify(boundary));
                    } catch (e) {
                        console.warn("Invalid GeoJSON in DB", e);
                    }
                }

                foModal.show();
            }
        }, 'json');
    });

    } else {
            console.error('Bootstrap not loaded!');
    }
});
})(jQuery);

//Delete Forest
function delete_forest(id, name){
    var confirmation = confirm('Are you sure want to delete this forest? ' + name);
    if(confirmation == true){
        window.location.href = base_url + ('administrator/redd/delete-forest/')+ id;
    }
}

/**====================================================================
*   Activity
*=======================================================================*/
(function($) {
    $(document).ready(function() {
    // Initialize modal and form
    const actModal = new bootstrap.Modal('#activityModal');
    const actForm = $('#activityForm');

    // Add new policy
    $('[data-bs-target="#activityModal"]').click(function() {
        actForm[0].reset();
        actForm.find('input[name="id"]').val('');
        $('#staticBackdropLabel').text('Add New Activity');
        $(".sbtn").text("Save Activity");
        //clearValidationErrors();
    });

    // Edit policy
    $(document).on('click', '.editActivity', function(e) {
        e.preventDefault();
        const activityId = $(this).data('id');
        
        $.get(base_url + 'administrator/redd/activities', {id: activityId}, function(response)
        {
                if (response.data) {

                    const activity = response.data;

                    // Populate form
                    actForm.find('input[name="id"]').val(activity.id);
                    actForm.find('input[name="name"]').val(activity.name);
                    actForm.find('textarea[name="description"]').val(activity.description);

                    
                    // Show current photo if exists
                    if (response.data.photo) {
                        $('#currentPhoto').html(`
                            <div class="mb-3">
                                <label class="form-label">Current Photo</label>
                                <img src="${response.data.photo}" class="img-thumbnail" style="max-height: 50px;">
                                <div class="form-text" style="font-size:10px;color:#f00;">Leave blank to keep existing</div>
                            </div>
                        `).show();
                    } else {
                        $('#currentPhoto').hide();
                    }
                    
                    // Update UI
                    $('#staticBackdropLabel').text('Edit Activity');
                    $(".sbtn").text("Update Activity");
                    
                    // Show modal
                    actModal.show();
                } else {
                    toastr.error('Activity data not found');
                }
            })
            .fail(function() {
                toastr.error('Failed to load activity data');
            });
    });

    // Form submission
    actForm.on('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        
        $.ajax({
            url: base_url + 'administrator/redd/activities',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    toastr.success(response.message);
                    actModal.hide();
                    setTimeout(() => location.reload(), 1000);
                } else {
                    handleErrors(response);
                }
            },
            error: function(xhr) {
                toastr.error('Server error occurred. Please try again.');
                console.error(xhr.responseText);
            }
        });
    

    // Helper functions
    

    function handleErrors(response) {
        //clearValidationErrors();
        if (response.errors) {
            $.each(response.errors, function(key, value) {
                const input = actForm.find('[name="' + key + '"]');
                input.addClass('is-invalid');
                input.next('.invalid-feedback').text(value);
            });
        } else {
            toastr.error(response.message || 'An error occurred');
        }
    }

});

});
})(jQuery);

function delete_activity(id, name){
    var confirmation = confirm('Are you sure want to delete this Activity? ' + name);
    if(confirmation == true){
        window.location.href = base_url + ('administrator/redd/delete-activity/')+ id;
    }
}

/**====================================================================
*   Methodology
*=======================================================================*/
(function($) {
    $(document).ready(function() {
    const methoModal = new bootstrap.Modal('#methodologyModal');
    const methoForm = $('#methodologyForm');

    // Add New
    $('[data-bs-target="#methodologyModal"]').click(function() {
        methoForm[0].reset();
        methoForm.find('input[name="id"]').val('');
        $('#staticBackdropLabel').text('Add New Methodology');
        $(".sbtn").text("Save methodology");
        //clearValidationErrors();
    });

    // Edit
    $(document).on('click', '.editMethodology', function(e) {
        e.preventDefault();
        const methodologyId = $(this).data('id');
        
        $.get(base_url + 'administrator/redd/methodologies', {id: methodologyId}, function(response)
        {
                if (response.data) {

                    const methodology = response.data;

                    // Populate form
                    methoForm.find('input[name="id"]').val(methodology.id);
                    methoForm.find('input[name="name"]').val(methodology.name);
                    methoForm.find('input[name="reference_link"]').val(methodology.reference_link);
                    methoForm.find('textarea[name="description"]').val(methodology.description);

                    
                    // Update UI
                    $('#staticBackdropLabel').text('Edit Methodology');
                    $(".sbtn").text("Update Methodology");
                    
                    // Show modal
                    methoModal.show();
                } else {
                    toastr.error('Methodoldgy data not found');
                }
            })
            .fail(function() {
                toastr.error('Failed to load methodology data');
            });
    });

    // Form submission
    methoForm.on('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        
        $.ajax({
            url: base_url + 'administrator/redd/methodologies',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    toastr.success(response.message);
                    methoModal.hide();
                    setTimeout(() => location.reload(), 1000);
                } else {
                    handleErrors(response);
                }
            },
            error: function(xhr) {
                toastr.error('Server error occurred. Please try again.');
                console.error(xhr.responseText);
            }
        });
    

    // Helper functions
    

    function handleErrors(response) {
        //clearValidationErrors();
        if (response.errors) {
            $.each(response.errors, function(key, value) {
                const input = actForm.find('[name="' + key + '"]');
                input.addClass('is-invalid');
                input.next('.invalid-feedback').text(value);
            });
        } else {
            toastr.error(response.message || 'An error occurred');
        }
    }

});

});
})(jQuery);

function delete_methodology(id, name){
    var confirmation = confirm('Are you sure want to delete this Methodology? ' + name);
    if(confirmation == true){
        window.location.href = base_url + ('administrator/redd/delete-methodology/')+ id;
    }
}

/**====================================================================
*   GASES
*=======================================================================*/
(function($) {
    $(document).ready(function() {

    const gModal = new bootstrap.Modal('#gasModal');
    const gForm = $('#gasForm');

    // Add New
    $('[data-bs-target="#gasModal"]').click(function() {
        gForm[0].reset();
        gForm.find('input[name="id"]').val('');
        $('#staticBackdropLabel').text('Add New Gas');
        $(".sbtn").text("Save gas");
        //clearValidationErrors();
    });

    // Edit
    $(document).on('click', '.editGas', function(e) {
        e.preventDefault();
        const gasId = $(this).data('id');
        
        $.get(base_url + 'administrator/redd/gases', {id: gasId}, function(response)
        {
                if (response.data) {

                    const gas = response.data;

                    // Populate form
                    gForm.find('input[name="id"]').val(gas.id);
                    gForm.find('input[name="name"]').val(gas.name);
                    gForm.find('input[name="symbol"]').val(gas.symbol);
                    gForm.find('input[name="atomic_number"]').val(gas.atomic_number);
                    gForm.find('input[name="atomic_mass"]').val(gas.atomic_mass);
                    gForm.find('input[name="global_warming_potential"]').val(gas.global_warming_potential);
                    gForm.find('input[name="gas_group"]').val(gas.gas_group);
                    gForm.find('input[name="period"]').val(gas.period);
                    gForm.find('textarea[name="description"]').val(gas.description);

                    // Update UI
                    $('#staticBackdropLabel').text('Edit Gas');
                    $(".sbtn").text("Update Gas");
                    
                    // Show modal
                    gModal.show();
                } else {
                    toastr.error('Gas data not found');
                }
            })
            .fail(function() {
                toastr.error('Failed to load gas data');
            });
    });

    // Form submission
    gForm.on('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        
        $.ajax({
            url: base_url + 'administrator/redd/gases',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    toastr.success(response.message);
                    gModal.hide();
                    setTimeout(() => location.reload(), 1000);
                } else {
                    handleErrors(response);
                }
            },
            error: function(xhr) {
                toastr.error('Server error occurred. Please try again.');
                console.error(xhr.responseText);
            }
        });
    

    // Helper functions
    function handleErrors(response) {
        //clearValidationErrors();
        if (response.errors) {
            $.each(response.errors, function(key, value) {
                const input = actForm.find('[name="' + key + '"]');
                input.addClass('is-invalid');
                input.next('.invalid-feedback').text(value);
            });
        } else {
            toastr.error(response.message || 'An error occurred');
        }
    }

});

});
})(jQuery);

function delete_gas(id, name){
    var confirmation = confirm('Are you sure want to delete this Gas? ' + name);
    if(confirmation == true){
        window.location.href = base_url + ('administrator/redd/delete-gas/')+ id;
    }
}


/**====================================================================
*   Carbon Pools
*=======================================================================*/
(function($) {
    $(document).ready(function() {

    const cpoolModal = new bootstrap.Modal('#carbonModal');
    const cpoolForm = $('#carbonForm');

    // Add New
    $('[data-bs-target="#carbonModal"]').click(function() {
        cpoolForm[0].reset();
        cpoolForm.find('input[name="id"]').val('');
        $('#staticBackdropLabel').text('Add New Carbon Pool');
        $(".sbtn").text("Save carbon pool");
        //clearValidationErrors();
    });

    // Edit
    $(document).on('click', '.editCarbon', function(e) {
        e.preventDefault();
        const cId = $(this).data('id');
        
        $.get(base_url + 'administrator/redd/carbon-pools', {id: cId}, function(response)
        {
                if (response.data) {

                    const carbon = response.data;

                    // Populate form
                    cpoolForm.find('input[name="id"]').val(carbon.id);
                    cpoolForm.find('input[name="name"]').val(carbon.name);
                    cpoolForm.find('textarea[name="description"]').val(carbon.description);

                    // Update UI
                    $('#staticBackdropLabel').text('Edit Carbon Pool');
                    $(".sbtn").text("Update Carbon");
                    
                    // Show modal
                    cpoolModal.show();
                } else {
                    toastr.error('Carbon Pool data not found');
                }
            })
            .fail(function() {
                toastr.error('Failed to load carbon pool data');
            });
    });

    // Form submission
    cpoolForm.on('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        
        $.ajax({
            url: base_url + 'administrator/redd/carbon-pools',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    toastr.success(response.message);
                    cpoolModal.hide();
                    setTimeout(() => location.reload(), 1000);
                } else {
                    handleErrors(response);
                }
            },
            error: function(xhr) {
                toastr.error('Server error occurred. Please try again.');
                console.error(xhr.responseText);
            }
        });
    

    // Helper functions
    function handleErrors(response) {
        //clearValidationErrors();
        if (response.errors) {
            $.each(response.errors, function(key, value) {
                const input = actForm.find('[name="' + key + '"]');
                input.addClass('is-invalid');
                input.next('.invalid-feedback').text(value);
            });
        } else {
            toastr.error(response.message || 'An error occurred');
        }
    }

});

});
})(jQuery);

function delete_carbon(id, name){
    var confirmation = confirm('Are you sure want to delete this Carbon Pool? ' + name);
    if(confirmation == true){
        window.location.href = base_url + ('administrator/redd/delete-carbon/')+ id;
    }
}

/**====================================================================
*   Entity Types
*=======================================================================*/
(function($) {
    $(document).ready(function() {

    const entModal = new bootstrap.Modal('#entityModal');
    const entForm = $('#entityForm');

    // Add New
    $('[data-bs-target="#entityModal"]').click(function() {
        entForm[0].reset();
        entForm.find('input[name="id"]').val('');
        $('#staticBackdropLabel').text('Add New Entity Type');
        $(".sbtn").text("Save Entity");
        //clearValidationErrors();
    });

    // Edit
    $(document).on('click', '.editEntity', function(e) {
        e.preventDefault();
        const cId = $(this).data('id');
        
        $.get(base_url + 'administrator/redd/entity-types', {id: cId}, function(response)
        {
                if (response.data) {

                    const ent = response.data;

                    // Populate form
                    entForm.find('input[name="id"]').val(ent.id);
                    entForm.find('input[name="name"]').val(ent.name);
                    entForm.find('textarea[name="description"]').val(ent.description);

                    // Update UI
                    $('#staticBackdropLabel').text('Edit Entity Type');
                    $(".sbtn").text("Update Entity");
                    
                    // Show modal
                    entModal.show();
                } else {
                    toastr.error('Entity Type data not found');
                }
            })
            .fail(function() {
                toastr.error('Failed to load entity data');
            });
    });

    // Form submission
    entForm.on('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        
        $.ajax({
            url: base_url + 'administrator/redd/entity-types',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    toastr.success(response.message);
                    entModal.hide();
                    setTimeout(() => location.reload(), 1000);
                } else {
                    handleErrors(response);
                }
            },
            error: function(xhr) {
                toastr.error('Server error occurred. Please try again.');
                console.error(xhr.responseText);
            }
        });
    

    // Helper functions
    function handleErrors(response) {
        //clearValidationErrors();
        if (response.errors) {
            $.each(response.errors, function(key, value) {
                const input = actForm.find('[name="' + key + '"]');
                input.addClass('is-invalid');
                input.next('.invalid-feedback').text(value);
            });
        } else {
            toastr.error(response.message || 'An error occurred');
        }
    }

});

});
})(jQuery);

function delete_entity(id, name){
    var confirmation = confirm('Are you sure want to delete this Entity Type? ' + name);
    if(confirmation == true){
        window.location.href = base_url + ('administrator/redd/delete-entity/')+ id;
    }
}

/**====================================================================
*   Project Types
*=======================================================================*/
(function($) {
    $(document).ready(function() {

    const entModal = new bootstrap.Modal('#projectTypeModal');
    const entForm = $('#projectTypeForm');

    // Add New
    $('[data-bs-target="#projectTypeModal"]').click(function() {
        entForm[0].reset();
        entForm.find('input[name="id"]').val('');
        $('#staticBackdropLabel').text('Add New  Type');
        $(".sbtn").text("Save Type");
        //clearValidationErrors();
    });

    // Edit
    $(document).on('click', '.editProjectType', function(e) {
        e.preventDefault();
        const cId = $(this).data('id');
        
        $.get(base_url + 'administrator/redd/project-types', {id: cId}, function(response)
        {
                if (response.data) {

                    const ent = response.data;

                    // Populate form
                    entForm.find('input[name="id"]').val(ent.id);
                    entForm.find('input[name="name"]').val(ent.name);
                    entForm.find('textarea[name="description"]').val(ent.description);

                    // Update UI
                    $('#staticBackdropLabel').text('Edit Project Type');
                    $(".sbtn").text("Update Type");
                    
                    // Show modal
                    entModal.show();
                } else {
                    toastr.error('Project Type data not found');
                }
            })
            .fail(function() {
                toastr.error('Failed to load Project data');
            });
    });

    // Form submission
    entForm.on('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        
        $.ajax({
            url: base_url + 'administrator/redd/project-types',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    toastr.success(response.message);
                    entModal.hide();
                    setTimeout(() => location.reload(), 1000);
                } else {
                    handleErrors(response);
                }
            },
            error: function(xhr) {
                toastr.error('Server error occurred. Please try again.');
                console.error(xhr.responseText);
            }
        });
    

    // Helper functions
    function handleErrors(response) {
        //clearValidationErrors();
        if (response.errors) {
            $.each(response.errors, function(key, value) {
                const input = actForm.find('[name="' + key + '"]');
                input.addClass('is-invalid');
                input.next('.invalid-feedback').text(value);
            });
        } else {
            toastr.error(response.message || 'An error occurred');
        }
    }

});

});
})(jQuery);

function delete_projecttype(id, name){
    var confirmation = confirm('Are you sure want to delete this Project Type? ' + name);
    if(confirmation == true){
        window.location.href = base_url + ('administrator/redd/delete-projecttype/')+ id;
    }
}

/**====================================================================
*   Project STATUS
*=======================================================================*/
(function($) {
    $(document).ready(function() {

    const entModal = new bootstrap.Modal('#projectStatusModal');
    const entForm = $('#projectStatusForm');

    // Add New
    $('[data-bs-target="#projectStatusModal"]').click(function() {
        entForm[0].reset();
        entForm.find('input[name="id"]').val('');
        $('#staticBackdropLabel').text('Add New Project Status');
        $(".sbtn").text("Save Status");
        //clearValidationErrors();
    });

    // Edit
    $(document).on('click', '.editProjectStatus', function(e) {
        e.preventDefault();
        const cId = $(this).data('id');
        
        $.get(base_url + 'administrator/redd/project-statuses', {id: cId}, function(response)
        {
                if (response.data) {

                    const ent = response.data;

                    // Populate form
                    entForm.find('input[name="id"]').val(ent.id);
                    entForm.find('input[name="name"]').val(ent.name);
                    entForm.find('input[name="icon"]').val(ent.icon);
                    entForm.find('input[name="color"]').val(ent.color);
                    entForm.find('textarea[name="description"]').val(ent.description);

                    // Update UI
                    $('#staticBackdropLabel').text('Edit Project Status');
                    $(".sbtn").text("Update Status");
                    
                    // Show modal
                    entModal.show();
                } else {
                    toastr.error('Project Status data not found');
                }
            })
            .fail(function() {
                toastr.error('Failed to load Project data');
            });
    });

    // Form submission
    entForm.on('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        
        $.ajax({
            url: base_url + 'administrator/redd/project-statuses',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    toastr.success(response.message);
                    entModal.hide();
                    setTimeout(() => location.reload(), 1000);
                } else {
                    handleErrors(response);
                }
            },
            error: function(xhr) {
                toastr.error('Server error occurred. Please try again.');
                console.error(xhr.responseText);
            }
        });
    

    // Helper functions
    function handleErrors(response) {
        //clearValidationErrors();
        if (response.errors) {
            $.each(response.errors, function(key, value) {
                const input = actForm.find('[name="' + key + '"]');
                input.addClass('is-invalid');
                input.next('.invalid-feedback').text(value);
            });
        } else {
            toastr.error(response.message || 'An error occurred');
        }
    }

});

});
})(jQuery);

function delete_projectstatus(id, name){
    var confirmation = confirm('Are you sure want to delete this Project Status? ' + name);
    if(confirmation == true){
        window.location.href = base_url + ('administrator/redd/delete-projectstatus/')+ id;
    }
}