var save_method; //for save method string
    
var table_county;
//Initialize Select2 Elements
$(document).ready( function () {
    start_load()
    table_county = $('#county-list').DataTable( {
    "ajax": base_url+"/admin-units/county/list/",
    "rowId" : function(a) {
        return 'county-' + a.id;
    },
    "columns": [
         {"data": "county_id"},
         {"data": "county_name"},
         {"data": "district_name"},
         {
             "orderable":      false,
             "data":           null,
             render:function(data, type, row)
             {
                 var btn='<a href="#" class="btn btn-sm btn-primary" onclick="view_subcounties('+data["county_id"]+',\''+data["county_name"]+'\')\"><i class="bi bi-list"></i></a>';
                 return btn;
             }
         },
         {
             "orderable":      false,
             "data":           null,
             render:function(data, type, row)
             {
              
                 var btn='<button onclick="edit_county1('+data['county_id']+')" class="btn btn-default p-0"><i class="bi bi-pencil align-middle "></i></button> <button onclick="delete_county1('+data['county_id']+')" class="btn btn-default p-0" ><i class="bi bi-trash align-middle"></i></button>';
                 return btn;
             }
         }
    ],
    "order": [[0, 'asc']],
    "paging":   true,
    "ordering": true,
    "info":     false,
    "filter": false,
    "searching": true,
    });
    setTimeout(function(){
     end_load()
     
 },500)
});
  function view_subcounties(id, county_name)
  {
    $.ajax({
      url : base_url +'/admin-units/county/subcounties/' + id,
      type: "GET",
      dataType: "JSON",
      success: function(data)
      {
         console.log(data);
          var html = '<div class="table-responsive"><table class="table table-borderless" width="100%">'+
          '<tr><td>'+
          '<strong style="font-size: 16px">'+county_name+' </strong>'+
          '</td></tr>';
          html += '<div class="table-responsive">';
                 html += '<table id="county-list-'+ id +'" class="table table-borderless expandable-table">';
                 html += '<thead><tr><th>ID</th><th>Name</th></tr></thead>';
                 html += '<tbody>';
                 
                 data.forEach((item)=>{
                     html += '<tr id="county-data-'+item.subcounty_id+'">'+
                             '<td>' + item.subcounty_id +'</td>'+
                             '<td>' + item.subcounty_name +'</td>'+
                             '</tr>';
                 });     
                 html += '</tbody>';  
                 html += '</table>'; 
                 html += '</div>';
          '<tr><td></table></div>';            
          start_load()
          $('#allorders').html(html);
          setTimeout(function(){
            end_load()
              $('#showModal').modal('show');
            },500);
      },
      error: function (jqXHR, textStatus, errorThrown)
      {
          toastr.error('Error - Counties not retrieved');
      }
  });
  }
function add_county()
{
    
    save_method = 'add';
    $('#form-county')[0].reset(); // reset form on modals

    $('#modal-county').modal('show'); // show bootstrap modal
    $('.modal-title').text('Add County'); // Set Title to Bootstrap modal title
}

function save_county()
{
  var url;
  if(save_method == 'add')
  {
      url = base_url+"county/add";
  }
  else
  {
    url = base_url+"county/edit";
  }
  
   // ajax adding data to database
   var county = $('#form-county').serializeObject();
    $.ajax({
    url : url,
    type: "POST",
    data: $('#form-county').serialize(),
    dataType: "JSON",
    headers: {'X-Requested-With': 'XMLHttpRequest'},
    success: function(data)
    {
        
        if(data.success == true)
        {
            //if success close modal and reload ajax table
            $('#modal-county').modal('hide');
            var btnHtml = '<button onclick="edit_county('+ data.county_id +')" class="btn btn-default" style="margin-right:5px;"><i class="fa fa-edit align-middle"></i></button>';
           btnHtml +=    '<button onclick="delete_county('+ data.county_id +')" class="btn btn-default" ><i class="fa fa-trash-alt align-middle"></i></button>';
           
           var rowData = [
                    data.county_id, 
                    county.county_name, 
                    county.district_id,
                    '<td class="county-list-control"><button class="btn btn-default"><i class="mdi mdi-menu align-middle"></i></button></td>',
                    btnHtml
                    ]
           if(save_method == 'add')
            {
                var rowNode = table_county.row.add(rowData).draw(false).node();
                $(rowNode).attr("id",'county-data-'+data.county_id);
                table_county.order([0, 'asc']).draw();
                table_county.page('last').draw(false);
           }
           else
           {
                var tableRow = table_county.row($('#county-data-'+data.county_id).closest('tr'));
                table_county
                        .row( tableRow )
                        .data(rowData)
                        .draw();
           }

        }
        else
        {
            var html = '<div class="alert alert-danger alert-dismissible"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>  <h5>Error</h5>'+data.msg+'</div>';
            document.getElementById('county-ajax-result').innerHTML = html;
        }
    },
    error: function (jqXHR, textStatus, errorThrown)
    {
        var err =JSON.parse(jqXHR.responseText);
        alert('Error :'+ err.message);
    }
});
}

function edit_county(id)
{
  save_method = 'update';
  $('#form-county')[0].reset(); // reset form on modals
 
  //Ajax Load data from ajax
  $.ajax({
    url : base_url+"county/edit/" + id,
    type: "GET",
    dataType: "JSON",
    success: function(data)
    {
        console.log(data);
        //$('[name="district_id"]').val(data.district_id);
        $('[name="county_id"]').val(data.county_id);
        $('[name="county_name"]').val(data.county_name);
       

        $('#modal-county').modal('show'); // show bootstrap modal when complete loaded
        $('.modal-title').text('Edit County'); // Set title to Bootstrap modal title

    },
    error: function (jqXHR, textStatus, errorThrown)
    {
        alert('Error get data from ajax');
    }
});
}

function delete_county(id)
{
  if(confirm('Are you sure delete this county?'))
  {
    // ajax delete data from database
      $.ajax({
        url : base_url+"county/delete/"+id,
        type: "POST",
        dataType: "JSON",
        headers: {'X-Requested-With': 'XMLHttpRequest'},
        success: function(data)
        {
            $('#county-data-' + id).closest('tr').remove();
           
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error deleting data');
        }
    });

  }
}