<?php require_once('header.php'); ?>
<style>
        /* Full-screen loader styling */
        #loader {
            display: none; /* Hidden by default */
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5); /* Semi-transparent black background */
            z-index: 9999; /* Make sure it's on top */
            display: flex;
            justify-content: center;
            align-items: center;
        }

        /* Simple spinner */
        .spinner {
            border: 8px solid #f3f3f3; /* Light grey */
            border-top: 8px solid #3498db; /* Blue */
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 2s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
        <div id="loader">
        <div class="spinner"></div>
    </div>
<section class="content-header">
    <a id="btnSync1" href="apis/auth.php" class="btn btn-success" target="_blank">Manual Sync 1</a>
    <a id="btnSync2" href="apis/getdatas_bygst.php" class="btn btn-warning disabled" target="_blank" aria-disabled="true">Manual Sync 2</a>
</section>

<script>
    document.getElementById('btnSync1').addEventListener('click', function () {
        const btn2 = document.getElementById('btnSync2');
        btn2.classList.remove('disabled');
        btn2.removeAttribute('aria-disabled');
    });

    document.getElementById('btnSync2').addEventListener('click', function (e) {
        if (this.classList.contains('disabled')) {
            e.preventDefault();
            alert('Please click Manual Sync 1 first.');
        }
    });
</script>
<!-- Date Range Filter -->
<div class="container mt-4">
  <div class='box-body' style="margin: 0px 0px;box-shadow: rgba(0, 0, 0, 0.19) 0px 10px 20px, rgba(0, 0, 0, 0.23) 0px 6px 6px;background-color: white;">  
      <?php
        // Set default start date as today and end date as one year later
        $start_date = date('Y-m-d');
        $end_date = date('Y-m-d', strtotime('+1 year'));
      ?>
    
        <form action="excel/eway_bill_update_export.php" method="POST">
          <div class="row g-3 align-items-end mb-4">
            <!-- Start Date -->
            <div class="col-md-2">
              <label for="start_date" class="form-label">Start Date</label>
              <input type="date" id="start_date" name="start_date" class="form-control" value="<?php echo htmlspecialchars($start_date); ?>" />
            </div>
        
            <!-- End Date -->
            <div class="col-md-2">
              <label for="end_date" class="form-label">End Date</label>
              <input type="date" id="end_date" name="end_date" class="form-control" value="<?php echo htmlspecialchars($end_date); ?>" />
            </div>
        
            <!-- Filter Button -->
            <div class="col-md-2 col-sm-6" style="display:flex;margin-top:25px">
              <button type="button" id="filterBtn" class="btn btn-success w-100"><i class="fa fa-filter"></i> Filter</button>
              <button class="btn btn-sm btn-primary"  style="margin-left:10px"><i class="fa fa-download"></i> Export As Excel</button>
            </div>
            
          </div>
        </form>
    </div>
</div>


<section class="content-header">
    <div class="box-body" style="margin: 0px; box-shadow: rgba(0, 0, 0, 0.19) 0px 10px 20px, rgba(0, 0, 0, 0.23) 0px 6px 6px; background-color: white;">
        <div class="table-responsive box-body">
            <table id="employee-grid" class="table table-bordered table-striped">
                <thead style="color:gray;">
                    <tr>
                        <th style="min-width:150px;" data-sortable="false">ID</th>
                        <th style="min-width:150px;" data-sortable="false">EWBN</th>
                        <th style="min-width:150px;" data-sortable="false">GENGST</th>
                        <th style="min-width:150px;" data-sortable="false">INVOICE</th>
                        <th style="min-width:150px;" data-sortable="false">INVOICE DATE</th>
                        <th style="min-width:150px;" data-sortable="false">RHD INVOICE DATE</th>
                        <th style="min-width:150px;" data-sortable="false">EwayBill Date</th>
                        <th style="min-width:150px;" data-sortable="false">EwayBill Date Expiry</th>
                        <!--<th style="min-width:150px;" data-sortable="false">RHD STATUS</th>-->
                        <th style="min-width:150px;" data-sortable="false">PART B</th>
                    </tr>
                </thead>
            </table>
        </div>
    </div>
</section>



<script>
$(document).ready(function () {
      $('#loader').hide();
      
      
      
          $('#detailsModal').on('show.bs.modal', function () {
        $('#modalForm')[0].reset();
        $('#reason').val('').trigger('change');
    });
    let submittedArray = [];

    function updatePreview() {
        let rawText = $('#columnInput').val();
        let array = rawText.split(/\r?\n/)
                           .map(item => item.trim())
                           .filter(item => item !== '')
                           .map(item => isNaN(item) ? item : Number(item));
        $('#arrayPreview').text(JSON.stringify(array, null, 2));
        $('#arrayCount').text(array.length);
        return array;
    }

    $('#columnInput').on('input', updatePreview);

    $('#arrayForm').on('submit', function (e) {
        e.preventDefault();
        submittedArray = updatePreview();

        if (submittedArray.length === 0) {
            alert("Please enter some data before submitting.");
            return;
        }

        $('#detailsModal').modal('show');
    });

    $('#modalForm').on('submit', function (e) {
        e.preventDefault();

        const driverName = $('#driverName').val();
        const vehicle_number = $('#vehicle_number').val();
        // const collectionDate = $('#collectionDate').val();
        const branch_id = $('#branch_id').val();
        const reason = $('#reason').val();
        const state_code = $('#state_code').val();
        const from = $('#from').val();
        const remark = $('#remark').val();

     

        const formData = {
            arrayData: submittedArray,
            reason,
            vehicle_number,
            remark,
            from,
            state_code
        };

 $.ajax({
                url: 'apis/ewaybill-update.php',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                beforeSend: function() {
                    // Show the full-screen loader before the request
                    $('#loader').show(); // Show loader
                    $('body').css('overflow', 'hidden'); // Disable scrolling during the request
                },
                success: function(response) {
                       $('#loader').hide();
                    console.log(response);
                        if (response.errors.length > 0) {
                            alert(response.errors);
                        } else {
                            alert('Success ids:'+response.success_ids);
                        }


                    $('#detailsModal').modal('hide');  // Assuming this modal exists
                    $('#arrayForm')[0].reset();
                    $('#modalForm')[0].reset();
                    $('#reason')[0].reset();
                    $('#arrayPreview').empty();
                    $('#arrayCount').text(0);
                },
                error: function() {
                    alert("An error occurred while submitting the data.");
                },
                complete: function() {
                    // Hide the loader once the request is complete (whether success or error)
                    $('#loader').hide(); // Hide the loader
                    $('body').css('overflow', 'auto'); // Re-enable scrolling
                }
            });    });
});
</script>

<script>
$(document).ready(function () {
    getData();
    get_company();

    $('#company_id').on('change', function () {
        get_branch();
    });
    $('#filterBtn').on('click', function () {
    
    var start_date = $('#start_date').val() ?? '';
    var end_date = $('#end_date').val() ?? '';
    // alert(start_date);
        getData(start_date,end_date)
    });
});

function getData(start_date = '', end_date = '') {

    $('#employee-grid').DataTable({
        processing: true,
        serverSide: true,
        bDestroy: true,
        aaSorting: [[0, 'desc']],

        ajax: {
            url: "data-tables/ewaybillreport-dt.php",
            type: "POST",
            data: {
                start_date: start_date,
                end_date: end_date
            },
            dataSrc: function (json) {
                // Update count values in the DOM
                if (json.counts) {
                    $('#rhd_generated').text(json.counts.rhd_generated);
                    $('#rhd_not_generated').text(json.counts.rhd_not_generated);
                    $('#vehicle_updated').text(json.counts.vehicle_updated);
                    $('#vehicle_not_updated').text(json.counts.vehicle_not_updated);
                }
                return json.data; // Return actual table data to DataTables
            },
            error: function () {
                $("#employee-grid").html('<tbody class="employee-grid-error"><tr><th colspan="5">No data found in the server</th></tr></tbody>');
            }
        },

        rowCallback: function (row, data) {
            if (data[5] === 'expired') {
                $(row).css('background-color', '#f8d7da');
            }
        },

        columnDefs: [
            {
                targets: [5],
                visible: false,
                searchable: false
            }
        ]
    });
}


function get_branch() {
    $('#branch_id').empty();
    let company_id = $('#company_id').val();
    $.ajax({
        url: 'apis/get-drop-down-list.php',
        type: 'POST',
        data: { type: 'get_branch_dropdown', company_id },
        success: function (response) {
            $('#branch_id').html(response);
        }
    });
}



function get_company(){
    $('#company_id').empty();
    $.ajax({
        url: 'apis/get-drop-down-list.php',
        type: 'post',
        data: {type:'get_company_dropdown'},
         success:function(response){
            $('#company_id').empty();
            $('#company_id').append(response);
            get_branch();
        }
    });
}
</script>

<?php require_once('footer.php'); ?>
