<style>
    #mira-application-update {
        border: 2px solid #dddddd;
    }

    #mira-application-update>thead>tr>th,
    #mira-application-update>tbody>tr>th,
    #mira-application-update>tfoot>tr>th,
    #mira-application-update>thead>tr>td,
    #mira-application-update>tbody>tr>td,
    #mira-application-update>tfoot>tr>td {
        border: 2px solid #dddddd;

    }

    #mira-application-update {
        width: 100%;
        overflow-x: scroll;
    }

    .back-btn-style {
        float: right;
        margin-bottom: -10px;
    }
    
#overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5); /* Semi-transparent black */
  display: none; /* Initially hidden */
  z-index: 9999; /* Ensure it stays on top */
  justify-content: center;
  align-items: center;
  color: white;
  font-size: 18px;
}

/* Loader style */
#loader {
  font-size: 40px;
  text-align: center;
}    
</style>
<?php
$ashaName = 'Testing';
$level = $this->session->userdata('level');
$asharegion = $this->session->userdata('asharegionId');
?>
<div class="panel">

    <div class="panel-body" style="margin-top: -16px">
        <div class="col text-left bg-info">
            <h3 class="text-info" style=" width: 300px; float:left;">
                <strong>Registered&nbsp;TG&nbsp;Data&nbsp;</strong></h3>
            
        </div>
        
                <!-- Loader and Overlay -->
<div id="overlay" style="display: none;">
    <div id="loader" style="margin-top:280px!important;">Loading...</div>
</div> 
        
        <table id="mira-application-update" class="table table-bordred table-striped table-hover">
            <thead>

                        <tr>
                            <th colspan="10">
                                <div class="row" style="margin-left: 2px">
                                    <div class="row">
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <div class="input-group">
                                                    <span class="input-group-addon"><i aria-hidden="true"></i><strong>Select
                                                            FC</strong></span>
                                                    <select name="anm_region_code" id="anm_region_code" class="form-control">
                                                        <option value="0" selected="true" disabled="true"> Select FC</option>
                                         <option value="99999" > All Data</option>                
                                                        <?php
                                                        for ($i = 0; $i < count($anmList); $i++) {
                                                            if (isset($regionCode)) {
                                                                if ($anmselected == $anmList[$i]['region_code']) {
                                                                    ?>
                                                                    <option selected="true" value=<?= $anmList[$i]['region_code'] ?>>
                                                                        <strong><?= $anmList[$i]['user_name'] ?></strong></option>
                                                                <?php } else { ?>
                                                                    <option value=<?= $anmList[$i]['region_code'] ?>><strong><?= $anmList[$i]['user_name'] ?></strong></option>
                                                                    <?php
                                                                }
                                                            } else {
                                                                ?>
                                                                <option value=<?= $anmList[$i]['region_code'] ?>><strong><?= $anmList[$i]['user_name'] ?></strong></option>
                                                                <?php
                                                            }
                                                        }
                                                        ?>
                                                    </select>
                                                    <span class="input-group-addon"><i class="fa fa-level-down"
                                                            aria-hidden="true"></i></span>
                                                </div>
                                            </div>
                                        </div>
                                         <div class="col-md-4">
                                    <div class="form-group">
                                        <div class="input-group">
                                            <span class="input-group-addon"><i aria-hidden="true"></i><strong>Search By</strong></span>
                                            <select name="searchbydate" id="searchbydate" required class="form-control">
                                                <!--<option value="0" disabled="true" selected="true"> Select Option</option>-->
                                                <!--<option value="1"> <strong>By Mobile Date</strong></option>-->
                                                 <!--<option value="2"> <strong>By Actual Date</strong></option>-->
                                                <option value="3"><strong>By Server Date</strong></option>
                                            </select>
                                            <span class="input-group-addon"><i class="fa fa-level-down"aria-hidden="true"></i></span>
                                        </div>                    
                                    </div> 
                                </div>
                                    </div>
                                
                                    
                                <div class="row">
                                <div class="col-lg-4">   
                                    <div class="form-group">
                                        <div class="input-group date" id="st_date" data-date-fromat="dd-mm-yyyy" style="color: white">
                                            <span class="input-group-addon"><strong>Start Date</strong></span>
                                            <input class="form-control" type="text" name="st_date" id="st_date_input"   required placeholder="dd-mm-yyyy">
                                            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                        </div>                    
                                    </div>

                                </div>
                                <div class="col-lg-4">   
                                    <div class="form-group">
                                        <div class="input-group date" id="en_date" data-date-fromat="dd-mm-yyyy" style="color: white">
                                            <span class="input-group-addon"><strong>End Date</strong></span>
                                            <input class="form-control" type="text" name="en_date" id="en_date_input"  required placeholder="dd-mm-yyyy">
                                            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                        </div>                    
                                    </div>
                                </div>

                                <div class="col-lg-4">
                                    <input type="button" class="btn btn-primary" id="btnsearch" value="Submit">
                                </div>
                                </div>
                                </div>

                              


                            </th>
                            <th colspan="2" style="border: none;">
                                <button type="button" id="dwnldBtn" style="margin-bottom: 10px; display: none;" onclick="downloadTableAsExcel();">Download Sheet</button>
                            </th>
                        </tr>
                 
                    <tr>
                    <th class="text-center">#</th>
                    <th class="text-center">TG&nbsp;Name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</th>
                    <th class="text-center">Houses</th>
                    <th class="text-center">Children</th>
                    <th class="text-center">ZD&nbsp;Children</th>
                    <th class="text-center">PV&nbsp;Children</th>
                    <th class="text-center">FV&nbsp;Children</th>
                    <th class="text-center">Active&nbsp;Children</th>
                    <th class="text-center">Closed&nbsp;Children</th>
                    <th class="text-center">Immunized&nbsp;Children</th>
                    <th class="text-center">Not&nbsp;Immunized&nbsp;Children</th>
                     <th class="text-center">Total&nbsp;Vaccination</th>
                    <th class="text-center">Follow-ups&nbsp;Conducted</th>
                    <th class="text-center">Top&nbsp;3&nbsp;challenges</th>
                    <th class="text-center">Children&nbsp;Percentage&nbsp;MCP&nbsp;Card</th>
                    
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>

    </div>
    <div class="panel-footer" style="margin-top: -36px">
        <h4 id="no-data" class="text-center text-danger" style="display: none;">
            <b>* Data not found . . !</b>
        </h4>
        <div class="row">
            <div class="col-lg-6">
                <ul id="pagination" class="pagination pagination-large">
                    
                </ul>
            </div>
        </div>
    </div>
</div>



<!-- Include the SheetJS Library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>

<script type="text/javascript">
    
    function downloadTableAsExcel() {
        var table = document.getElementById("mira-application-update");
        var rows = table.querySelectorAll("tr");
        
        // Create an array to hold the table data
        var tableData = [];
        
        // Loop through the rows, starting from the second one (index 1)
        rows.forEach(function(row, index) {
            if (index === 0) return;  // Skip the first row (header row)

            var cols = row.querySelectorAll("td, th");
            var rowData = [];
            cols.forEach(function(col) {
                rowData.push(col.innerText);
            });
            tableData.push(rowData);
        });
        
        // Create a new workbook and add the table data to a worksheet
        var wb = XLSX.utils.book_new();
        var ws = XLSX.utils.aoa_to_sheet(tableData);
        
        // Append the worksheet to the workbook
        XLSX.utils.book_append_sheet(wb, ws, "Table Data");
        
        // Generate Excel file and trigger the download
        XLSX.writeFile(wb, "Asha_Workers.xlsx");
    }


    $(document).ready(function () {
    
        

        
         var anmcode='0'
        $('#anm_region_code').change(function (e) {
          e.preventDefault();
          // $('#overlay').show(); 
         var region_code = parseInt($('#anm_region_code').val());
         anmcode=region_code;
         let stdate=$('#st_date_input').val();
         let endate=$('#en_date_input').val();
         let searchby=parseInt($('#searchbydate').val());
         if(searchby !== '0' && stdate !== '' && endate !== '' && anmcode !== '0')
            {   $('#overlay').show(); 
                GetDataByAnmId(anmcode, stdate,endate,searchby)
            }
            
          
            else
            {    $('#overlay').show(); 
                GetDataByAnmId(region_code, null,null,null)
            }
        });


       $('#btnsearch').click(function(e){
           e.preventDefault();
            let stdate=$('#st_date_input').val();
            let endate=$('#en_date_input').val();
            let rcode=parseInt($('#region_code').val());
            let searchby=parseInt($('#searchbydate').val());
            let searchbyanm =parseInt($('#anm_region_code').val());
                     console.log(stdate);
                     console.log(endate);
                     console.log(searchby);
            if(searchby !== '0' && stdate !== '' && endate !== '' && anmcode !== '0')
            {   $('#overlay').show();
                GetDataByAnmId(anmcode, stdate,endate,searchby)
            }
            else
            {
                alert("Plese Select and fill all fields");
            }
        });

        $('#st_date').datepicker({ autoclose: true, format: 'dd-mm-yyyy' });
        $('#en_date').datepicker({ autoclose: true, format: 'dd-mm-yyyy' });
    });
     
     function GetDataByAnmId(region_code,st_date,en_date,searchby){
          
            anmcode=region_code;
            $('#mira-application-update tbody tr').remove();
            $.ajax({
                url: '<?= base_url('getAshaHouseHoldDataByANMId') ?>',
                data: {
                    region_code: region_code,
                    st_date_input:st_date,
                    en_date_input:en_date,
                    searchbydate:searchby
                },
                type: "POST",
                success: function (json) {
                    $('#overlay').hide();
                    var states = $.parseJSON(json);
                    console.log(states);
                    document.getElementById("dwnldBtn").style.display = "block";
                    for (var i = 0; i < states['miraList'].length; i++) {
        
                    const raw = states.miraList[i]['top_3_chalanges'] || '';

                    const challenges = raw.split(',')
                                       .map(item => item.trim())
                                       .filter(item => item !== ''); 
                                       // convert to bullet HTML
                    let challengesHtml = '<ul style="padding-left:15px; margin:0;">';
                    challenges.forEach(function(item) {
                  challengesHtml += '<li>' + item + '</li>';
                   });
                    challengesHtml += '</ul>';
                        $("#mira-application-update tbody").append('<tr></tr>');

            $('#mira-application-update tbody tr:last').append('<td class="text-center">' + (i + 1) + '</td>');
            $('#mira-application-update tbody tr:last').append('<td class="text-left">' + states.miraList[i]['user_name'] + '</td>');
            $('#mira-application-update tbody tr:last').append('<td class="text-center">' + states.miraList[i]['houses'] + '</td>');
            $('#mira-application-update tbody tr:last').append('<td class="text-center">' + states.miraList[i]['children'] + '</td>');
            $('#mira-application-update tbody tr:last').append('<td class="text-center">' + states.miraList[i]['zerodose'] + '</td>');
            $('#mira-application-update tbody tr:last').append('<td class="text-center">' + states.miraList[i]['partialyvaccinated'] + '</td>');
            $('#mira-application-update tbody tr:last').append('<td class="text-center">' + states.miraList[i]['fullyvaccinated'] + '</td>');
            $('#mira-application-update tbody tr:last').append('<td class="text-center">' + states.miraList[i]['activechild'] + '</td>');
            $('#mira-application-update tbody tr:last').append('<td class="text-center">' + states.miraList[i]['closedchild'] + '</td>');
            $('#mira-application-update tbody tr:last').append('<td class="text-center">' + states.miraList[i]['immunized_child'] + '</td>');
            $('#mira-application-update tbody tr:last').append('<td class="text-center">' + states.miraList[i]['not_immunized_child'] + '</td>');
            $('#mira-application-update tbody tr:last').append('<td class="text-center">' + states.miraList[i]['total_vaccination'] + '</td>');
            $('#mira-application-update tbody tr:last').append('<td class="text-center">' + states.miraList[i]['total_followups'] + '</td>');
            $('#mira-application-update tbody tr:last').append('<td class="text-center">' + challengesHtml + '</td>');
            $('#mira-application-update tbody tr:last').append('<td class="text-center">' + states.miraList[i]['mcp_card'] + '</td>');
                            
                    }
                    $('#asha_list_update_spinner').css('display', 'none');
                },
                error: function (xhr, status, errorThrown) {
                    $('#asha_list_update_spinner').css('display', 'none');
                },
                complete: function (xhr, status) {
                    $('#asha_list_update_spinner').css('display', 'none');
                }
            });
     }
     
    function getDateFormat(date) {
        var split_date_array1 = date.split('-');
        var split_date_array2 = split_date_array1[2].split(' ');
        return (split_date_array2[0] + '-' + split_date_array1[1] + '-' + split_date_array1[0]);
    }

</script>