/**
 * This jQuery file contains functions for Customer Settings
 * in ACB
 * Developed by LWEGATECH - www.lwegatech.com
 **/

var save_method;

/** ================================================
 *  Members List
 *===================================================*/
var table_clients;
$(document).ready( function () {
  start_load()
  $(document).on('click', '[data-bs-toggle="popover"]', function () {
       $(this).popover();
   });
  table_clientss = $('#clients-list').DataTable( {
  dom: 'Blfrtip',
    buttons: [
        'copy', 'csv', 'excel', 'pdf', 'print'
      ],
  "processing": true,
    "serverSide": true,
    "ajax": {
        "url": base_url + "administrator/redd/client-list",
        "type": "GET",
        "data": function (d) {

            d.search = { "value": $('#clients-list_filter input').val() };
        }
    },
  "columns": [
        {"data": "id"},
        { 
              "orderable": false,
              "data": null,
              render: function (data, type, row) {
                  if (data["photo"] == null) {
                      return '<img src="' + base_url + '/assets/images/no-image.gif" alt="" height="20px">';
                  } else {
                      return '<img src="' + data["photo"] + '" alt="' + data["fname"] +'" style="height:50px;width:50px;object-fit:contain">';
                  }
              }
        },
        {
            "orderable":      true,
            "data":           null,
            render: function ( data, type, row ) {
            return '<a href="'+ base_url+"administrator/redd/single-client/id="+data["id"] +'"><strong>' + data["fname"] + ' '+ data["lname"] + '</strong></a>'; 
            }
        },
        {"data": "phone"},
       {"data": "email"},
        {"data":"entity_name"},
       {"data": "total_projects"},
       {"data": "city_name"},
       {"data": "state_name"},
       {"data": "country_name"},
       {
           "orderable":      false,
           "data":           null,
           render:function(data, type, row)
           {
               var btn ='<div class="dropdown">'+
                        '<button class="btn btn-light" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">'+
                        '<i class="bi bi-three-dots-vertical"></i>'+
                        '</button>'+
                        '<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">'+
                        '<li><a class="dropdown-item" title="Edit" onclick="edit_client('+data["id"]+')\" style="cursor: pointer"><small>Edit</small></a></li>'+
                        '<li><a class="dropdown-item" href="'+base_url+'administrator/redd/single-client/id='+data["id"]+'"><small>View</small></a></li>'+
                        '<li><a class="dropdown-item" onclick="delete_client('+data["id"]+',\''+data["fname"]+'\')\" style="cursor: pointer"><small>Delete</small></a></li>'+
                        ' </ul>'+
                        '</div>';
                    return btn;
           }
       }
  ],
  "order": [[0, 'desc']],
  });
  setTimeout(function(){
   end_load()
   
},500)
});

//Edit Member
function edit_client(id)
{
    $('#clientModal').modal('show');

    $.ajax({
        url:  base_url + 'administrator/redd/edit-client/'+ id,
        type: "GET",
        dataType: "JSON",
        success: function(data)
        {
            $('[name="id"]').val(data.id);
            $('[name="fname"]').val(data.fname);
            $('[name="lname"]').val(data.lname);
            $('[name = "alias"]').val(data.alias);
            $('[name = "email"]').val(data.email);
            $('[name = "phone"]').val(data.phone);
            $('[name = "national_id"]').val(data.national_id);
            $('[name = "address"]').val(data.address);
            $('[name = "entity_type_id"]').val(data.entity_type_id);
            $('[name = "website"]').val(data.website);
            $('[name = "description"]').val(data.description);
            $('[name = "geo_lat"]').val(data.geo_lat);
            $('[name = "geo_long"]').val(data.geo_long);
            $('[name = "country_id"]').val(data.country_id);             

            $( "#state_id option:selected").val(data.state_id);
            $( "#state_id option:selected").text(data.state_name);
            $( "#city_id option:selected").val(data.city_id);
            $( "#city_id option:selected").text(data.city_name);

            // Show current photo if exists
            if (data.photo) {
                $('#currentPhoto').html(`
                    <div class="mb-3 mt-2">
                        <label class="form-label small">Current Photo</label>
                        <img src="${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();
            }


            //load modal
            start_load()
            $("#clientModal").modal('show');
            $(".modal-title").text("Update Client!");
            $(".sbtn").text("Update");
            setTimeout(function(){
            end_load();
        },500)
        }
    });
}

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


/** ===================================================
 *  EDIT Project
 *=================================================*/
function edit_project(id)
{
    $('#projectModal').modal('show');

    $.ajax({
        url:  base_url + 'administrator/redd/edit-project/'+ id,
        type: "GET",
        dataType: "JSON",
        success: function(data)
        {
            $('[name="id"]').val(data.id);
            $('[name="client_id"]').val(data.client_id);
            $('[name="project_number"]').val(data.project_number);
            $('[name="name"]').val(data.name);
            $('[name="size"]').val(data.size);
            $('[name="project_validator"]').val(data.project_validator);
            $('[name = "location_description"]').val(data.location_description);
            $('[name = "description"]').val(data.description);
            $('[name = "geo_lat"]').val(data.geo_lat);
            $('[name = "geo_long"]').val(data.geo_long);
            $('[name = "district_id"]').val(data.district_id);             

            
            //Show selected location
            $( "#county_id option:selected").val(data.county_id);
            $( "#county_id option:selected").text(data.county_name);
            $( "#subcounty_id option:selected").val(data.subcounty_id);
            $( "#subcounty_id option:selected").text(data.subcounty_name);
            $( "#parish_id option:selected").val(data.parish_id);
            $( "#parish_id option:selected").text(data.parish_name);
            $( "#village_id option:selected").val(data.village_id);
            $( "#village_id option:selected").text(data.village_name);
           


            //load modal
            start_load()
            $("#projectModal").modal('show');
            $(".modal-title").text("Update Project!");
            $(".sbtn").text("Update Project");
            setTimeout(function(){
            end_load();
        },500)
        }
    });
}

/**
 * Carbon Data
 */
function carbon_data(projectId)
{
    $('#projectCarbonDataModal').modal('show');
    $('[name="project_id"]').val(projectId);

    $(".modal-title").text("Collect Carbon Data!");
    $(".sbtn").text("Save Data"); 

}

function edit_carbon_data(id)
{
    $('#projectCarbonDataModal').modal('show');

    $.ajax({
        url:  base_url + 'administrator/redd/projects/carbon-data/edit/'+ id,
        type: "GET",
        dataType: "JSON",
        success: function(data)
        {
            $('[name="id"]').val(data.id);
            $('[name="project_id"]').val(data.project_id);
            $('[name="estimated_er"]').val(data.estimated_er);
            $('[name="buffer_credit"]').val(data.buffer_credit);
            $('[name="credit_period_start"]').val(dateToYMD(new Date(data.credit_period_start)));
            $('[name="credit_period_end"]').val(dateToYMD(new Date(data.credit_period_end)));
            $('[name="reff_period_start"]').val(dateToYMD(new Date(data.reff_period_start)));
            $('[name="reff_period_end"]').val(dateToYMD(new Date(data.reff_period_end)));
            $('[name="uncertainty"]').val(data.uncertainty);
            $('[name="registry"]').val(data.registry);;
            $('[name = "description"]').val(data.description);   

            // Change form action to update URL
            $("form").attr("action", base_url + "administrator/redd/projects/carbon-data/update");
            
            //load modal
            start_load()
            $("#projectCarbonDataModal").modal('show');
            $(".modal-title").text("Update Carbon Data!");
            $(".sbtn").text("Update Data");
            setTimeout(function(){
            end_load();
        },500)
        }
    });
}