var save_method; //for save method string
    
    var table_subcounty;
    $(document).ready( function () {
        start_load()
        table_county = $('#subcounty-list').DataTable( {
        "ajax": base_url+"/admin-units/subcounty/list/",
        "rowId" : function(a) {
            return 'county-' + a.id;
        },
        "columns": [
            { "data": "subcounty_id" },
            { "data": "subcounty_name" },
            { "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_parishes('+data["subcounty_id"]+',\''+data["subcounty_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_subcounty('+data['subcounty_id']+')">Edit</a></li><li><a class="dropdown-item" href="#" onclick="onclick="delete_subcounty('+data["subcounty_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_parishes(id, subcounty_name)
    {
      $.ajax({
        url : base_url +'/admin-units/subcounty/parishes/' + 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">'+subcounty_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.parish_id+'">'+
                               '<td>' + item.parish_id +'</td>'+
                               '<td>' + item.parish_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_subcounty()
    {
        
        save_method = 'add';
        $('#form-subcounty')[0].reset(); // reset form on modals

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

    function save_subcounty()
    {
      var url;
      if(save_method == 'add')
      {
          url = base_url+"subcounty/add";
      }
      else
      {
        url = base_url+"subcounty/edit";
      }
      
       // ajax adding data to database
       var county = $('#form-subcounty').serializeObject();
        $.ajax({
        url : url,
        type: "POST",
        data: $('#form-subcounty').serialize(),
        dataType: "JSON",
        headers: {'X-Requested-With': 'XMLHttpRequest'},
        success: function(data)
        {
            
            if(data.success == true)
            {
                //if success close modal and reload ajax table
                $('#modal-subcounty').modal('hide');
                var btnHtml = '<button onclick="edit_subcounty('+ data.subcounty_id +')" class="btn btn-default" style="margin-right:5px;"><i class="fa fa-edit align-middle"></i></button>';
               btnHtml +=    '<button onclick="delete_subcounty('+ data.subcounty_id +')" class="btn btn-default" ><i class="fa fa-trash-alt align-middle"></i></button>';
               
               var rowData = [
                        data.subcounty_id, 
                        county.subcounty_name, 
                        county.county_name, 
                        county.district_id,
                        '<td class="parish-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_subcounty.row.add(rowData).draw(false).node();
                    $(rowNode).attr("id",'subcounty-data-'+data.subcounty_id);
                    table_subcounty.order([0, 'asc']).draw();
                    table_subcounty.page('last').draw(false);
               }
               else
               {
                    var tableRow = table_subcounty.row($('#subcounty-data-'+data.subcounty_id).closest('tr'));
                    table_subcounty
                            .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('subcounty-ajax-result').innerHTML = html;
            }
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            var err =JSON.parse(jqXHR.responseText);
            alert('Error :'+ err.message);
        }
    });
    }

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

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