var save_method; //for save method string
    
    var table_parish;
    //Initialize Select2 Elements
$(document).ready( function () {
    start_load()
    table_parish = $('#parish-list').DataTable( {
    "ajax": base_url+"/admin-units/parish/list/",
    "rowId" : function(a) {
        return 'parish-' + a.id;
    },
    "columns": [
         {"data": "parish_id"},
         {"data": "parish_name"},
         {"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_villages('+data["parish_id"]+',\''+data["parish_name"]+'\')\"><i class="bi bi-list"></i></a>';
                 return btn;
             }
         },
         {
             "orderable":      false,
             "data":           null,
             render:function(data, type, row)
             {
              
                 var btn='<button onclick="edit_parish('+data['parish_id']+')" class="btn btn-default p-0"><i class="bi bi-pencil align-middle "></i></button> <button onclick="delete_parish('+data['parish_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_villages(id, parish_name)
    {
      $.ajax({
        url : base_url +'/admin-units/parish/villages/' + 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">'+parish_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.village_id+'">'+
                               '<td>' + item.village_id +'</td>'+
                               '<td>' + item.village_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');
        }
    });
    }



      $(document).ready(function(){
 
            $('#district-select').change(function(){ 
                var id=$(this).val();
                    $.ajax({
                        url : base_url+"district/counties/"+id,
                        method : "POST",
                        data : {id: id},
                        async : true,
                        dataType : 'json',
                        success: function(data){
                            
                            var html = '<option>Select a county</option>';
                            var i;
                            for(i=0; i<data.length; i++){
                                html += '<option value='+data[i].county_id+'>'+data[i].county_name+'</option>';
                            }
                            $('#county-select').html(html);

                        }
                    });
                    return false;
                }); 
        
        });

    $(document).ready(function(){
        $('#county-select').change(function(){ 
        var id=$(this).val();
            $.ajax({
                url : base_url+"county/subcounties/"+id,
                method : "POST",
                data : {id: id},
                async : true,
                dataType : 'json',
                success: function(data){
                    
                    var html = '<option>Select a Subcounty</option>';
                    var i;
                    for(i=0; i<data.length; i++){
                        html += '<option value='+data[i].subcounty_id+'>'+data[i].subcounty_name+'</option>';
                    }
                    $('#subcounty-select').html(html);

                }
            });
            return false;
        }); 
    
    });

      $.fn.serializeObject = function() {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

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

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

    function save_parish()
    {
      var url;
      if(save_method == 'add')
      {
          url = base_url+"parish/add";
      }
      else
      {
        url = base_url+"parish/edit";
      }
      
       // ajax adding data to database
       var county = $('#form-parish').serializeObject();
        $.ajax({
        url : url,
        type: "POST",
        data: $('#form-parish').serialize(),
        dataType: "JSON",
        headers: {'X-Requested-With': 'XMLHttpRequest'},
        success: function(data)
        {
            
            if(data.success == true)
            {
                //if success close modal and reload ajax table
                $('#modal-parish').modal('hide');
                var btnHtml = '<button onclick="edit_parish('+ data.parish_id +')" class="btn btn-default" style="margin-right:5px;"><i class="fa fa-edit align-middle"></i></button>';
               btnHtml +=    '<button onclick="delete_parish('+ data.parish_id +')" class="btn btn-default" ><i class="fa fa-trash-alt align-middle"></i></button>';
               
               var rowData = [
                        data.parish_id, 
                        county.parish_name,
                        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_parish.row.add(rowData).draw(false).node();
                    $(rowNode).attr("id",'parish-data-'+data.parish_id);
                    table_parish.order([0, 'asc']).draw();
                    table_parish.page('last').draw(false);
               }
               else
               {
                    var tableRow = table_parish.row($('#parish-data-'+data.subcounty_id).closest('tr'));
                    table_parish
                            .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_parish(id)
    {
      save_method = 'update';
      $('#form-parish')[0].reset(); // reset form on modals
      
      //Ajax Load data from ajax
      $.ajax({
        url : base_url+"parish/edit/" + id,
        type: "GET",
        dataType: "JSON",
        success: function(data)
        {
            console.log(data);
            //$('[name="district_id"]').val(data.district_id);
            $('[name="parish_id"]').val(data.parish_id);
            $('[name="parish_name"]').val(data.parish_name);
           
 
            $('#modal-parish').modal('show'); // show bootstrap modal when complete loaded
            $('.modal-title').text('Edit Parish'); // Set title to Bootstrap modal title
 
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error get data from ajax');
        }
    });
    }

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