
    var save_method; //for save method string
    var table_district;
    var table_county;
 $(document).ready( function () {
   start_load()
   table_district = $('#district-list').DataTable( {
   "ajax": base_url+"/admin-units/districts/list/",
   "rowId" : function(a) {
       return 'district-' + a.id;
   },
   "columns": [
        {"data": "district_id"},
        {"data": "district_name"},
        {
            "orderable":      false,
            "data":           null,
            render:function(data, type, row)
            {
                var btn='<a href="#" class="btn btn-sm btn-primary" onclick="view_counties('+data["district_id"]+',\''+data["district_name"]+'\')\"><i class="bi bi-list"></i></a>';

                return btn;
            }
        },
        {
            "orderable":      false,
            "data":           null,
            render:function(data, type, row)
            {
             
                var btn='<div class="dropdown"><button class="btn btn-white" 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" href="#" onclick="edit_district('+data['district_id']+')">Edit</a></li><li><a class="dropdown-item" href="#" onclick="delete_district1('+data['district_id']+')">Delete</a></li></ul></div>';
                return btn;
            }
        }
   ],
   "order": [[0, 'asc']],
   "paging":   true,
   "ordering": true,
   "info":     false,
   "filter": false,
   "searching": true,
   });
   setTimeout(function(){
    end_load()
    
},500)
 });
 function view_counties(id, district_name)
 {
   $.ajax({
     url : base_url +'/admin-units/district/counties/' + 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">'+district_name+' District</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.county_id+'">'+
                            '<td>' + item.county_id +'</td>'+
                            '<td>' + item.county_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 format_county_list ( rowData ) {
        var div = $('<div/>')
            .addClass( 'loading' )
            .attr("style","margin-left:100px;")
            .text( 'Loading...' );
            
        $.ajax( {
            url: base_url+"district/counties/" + rowData[0],
            data: {
                name: rowData.name
            },
            dataType: 'json',
            headers: {'X-Requested-With': 'XMLHttpRequest'},
            success: function ( data ) {
                var districtId = rowData[0];
                var expandUrl = base_url+"district/counties/"+ districtId;
                var html = '<div class="card">';
                html += '<div class="card-body">';
                html += '<p class="card-title">Counties';
                html += '<button onclick="add_county('+ districtId +')" style="margin-left:5px;" class="btn btn-default float-right"><i class="mdi mdi-plus align-middle"></i></button>';
                html +='<a href="'+ expandUrl + '" class="btn btn-default float-right"><i class="fa fa-window-maximize align-middle"></i></a>';
                html +='</h5>';
                
                html += '<div class="table-responsive">';
                html += '<table id="county-list-'+ districtId +'" class="display expandable-table" style="width:100%">';
                html += '<thead><tr><th>ID</th><th>Name</th><th>Sub-Counties</th><th>Options</th></tr></thead>';
                html += '<tbody>';
                
                data.forEach((item)=>{
                    html += '<tr id="county-data-'+item.county_id+'">'+
                            '<td>' + item.county_id +'</td>'+
                            '<td>' + item.county_name +'</td>'+
                            '<td class="constituency-list-control"><button class="btn btn-default"><i class="mdi mdi-menu align-middle"></i></button></td>'+
                            '<td>'+
                            '<button onclick="edit_county('+ item.county_id +')" class="btn btn-default" style="margin-right:5px;"><i class="fa fa-edit align-middle"></i></button>'+
                            '<button onclick="delete_county('+ item.county_id +')" class="btn btn-default" ><i class="fa fa-trash-alt align-middle"></i></button>'+
                            '</td>'+
                            '</tr>';
                });     
                html += '</tbody>';  
                html += '</table>'; 
                html += '</div>';
                html += '</div>';
                html += '</div>'; 

                div
                    .html( html )
                    .removeClass( 'loading' );

               
                table_county = $('#county-list-'+districtId).DataTable({
                    'columnDefs' : [
                        { 'visible': false, 'targets': [0] }
                    ]
                 });
            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                var err =JSON.parse(jqXHR.responseText);
                var html = '<div class="alert alert-danger alert-dismissible"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>  <h5>Error</h5>'+err.message+'</div>';
                div
                    .html( html )
                    .removeClass( 'loading' );
            }
        } );
    
        return div;
    }

   
    
    function add_county(id)
    {
        
        save_method = 'add';
        $('#form-county')[0].reset(); // reset form on modals

        $('[name="district_id"]').val(id);

        $('#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, 
                        '<td class="subcounty-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)
        {
            $('[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');
            }
        });
 
      }
    }


    function add_district()
    {
        
        save_method = 'add';
        var form = $('#form-district')[0].reset(); // reset form on modals
        $('#modal-district').modal('show'); // show bootstrap modal
        $('.modal-title').text('Add District'); // Set Title to Bootstrap modal title
    }

    function save_district()
    {
      var url;
      if(save_method == 'add')
      {
          url = base_url+"/admin-units/district/add";
      }
      else
      {
        url = base_url+"/admin-units/district/edit";
      }
      
       //var district = $('#form-district').serializeObject();
       var form =  $('#form-district')[0];
       $.ajax({
        type: "post",
        url: url,
        dataType: "JSON",
        data: new FormData(form),
        processData: false,
        contentType: false,
        headers: {'X-Requested-With': 'XMLHttpRequest'},
        success: function(data)
        {
            if(data.success == true)
            {
                //if success close modal and reload ajax table
                $('#modal-district').modal('hide');

               var btnHtml = '<button onclick="edit_district('+ data.district_id +')" class="btn btn-default" style="margin-right:5px;"><i class="fa fa-edit align-middle"></i></button>';
               btnHtml +=    '<button onclick="delete_district('+ data.district_id +')" class="btn btn-default" ><i class="fa fa-trash-alt align-middle"></i></button>';
               
               var rowData = [
                        data.district_id, 
                        form.district_name, 
                        '<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_district.row.add(rowData).draw(false).node();
                    $(rowNode).attr("id",'district-data-'+data.district_id);
                    table_district.order([0, 'asc']).draw();
                    table_district.page('last').draw(false);
               }
               else
               {
                    var tableRow = table_district.row($('#district-data-'+data.district_id).closest('tr'));
                    table_district
                            .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>  <h6>Error</h6>'+data.msg+'</div>';
                document.getElementById('district-ajax-result').innerHTML = html;
            }
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            var err =JSON.parse(jqXHR.responseText);
            alert('Error :'+ err.message);
        }
    });
    }

    function edit_district(id)
    {
      save_method = 'update';
      $('#form-district')[0].reset(); // reset form on modals
      
      //Ajax Load data from ajax
      $.ajax({
        url : base_url+"district/edit/" + id,
        type: "GET",
        dataType: "JSON",
        success: function(data)
        {
            $('[name="district_id"]').val(data.district_id);
            $('[name="district_name"]').val(data.district_name);
           
 
            $('#modal-district').modal('show'); // show bootstrap modal when complete loaded
            $('.modal-title').text('Edit District'); // Set title to Bootstrap modal title
 
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error get data from ajax');
        }
    });
    }

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