<?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>


<!-- Modal -->
<div class="modal fade" id="detailsModal" tabindex="-1" aria-labelledby="detailsModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <form id="modalForm" autocomplete="off" class="w-100">
      <div class="modal-content rounded-3 shadow-sm">
        <div class="modal-header">
          <h5 class="modal-title" id="detailsModalLabel">Driver & Vehicle Details</h5>
        </div>

        <div class="modal-body">
          <div class="container-fluid">
            <div class="row g-3">
              <!-- Company Dropdown -->
                <div class="col-md-6">
                  <label for="state_code" class="form-label">State</label><br>
                  <select class="form-select "  name="state_code" id="state_code" style="width:400px" required>
                    <option value="">Select a state</option>
                    <?php
                    // PDO connection
                    try {
                        $stmt = $pdo->prepare("SELECT id, state, state_code FROM tbl_state_code ORDER BY state ASC");
                        $stmt->execute();
                
                        // Loop through results
                        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                            echo "<option value='" . htmlspecialchars($row['state_code']) . "'>" . htmlspecialchars($row['state']) . " (" . htmlspecialchars($row['state_code']) . ")</option>";
                        }
                    } catch (PDOException $e) {
                        echo "<option value=''>Error loading states</option>";
                    }
                    ?>
                  </select>
                </div>

              <div class="col-md-6">
                <label for="from" class="form-label">From</label>
                <input type="text" class="form-control" id="from" name="from" placeholder="" required>
              </div>
              <div class="col-md-6">
                <label for="driverName" class="form-label">Pincode</label>
                <input type="text" class="form-control" id="pincode" name="pincode" placeholder="" required>
              </div>
              
              <!--<div class="col-md-6">-->
              <!--    <label for="vehicle_type" class="form-label">Vehicle Type</label>-->
              <!--    <select id="vehicle_type" name="vehicle_type" class="form-control">-->
              <!--      <option value="r">Regular</option>-->
              <!--      <option value="o">ODC (Over Dimensional Cargo)</option>-->
              <!--    </select>-->
              <!--  </div>-->
                
                <div class="col-md-6">
                  <label for="reason" class="form-label">Reson For Ext Validity</label>
                  <select id="reason" name="reason" class="form-control">
                    <option value="1">natural calamity</option>
                    <option value="2">Law and Order Sitution</option>
                    <option value="4">Transshipment</option>
                    <option value="5">Accident</option>
                    <option value="99">Others</option>
                  </select>
                </div>
                
                <div class="col-md-6">
                  <label for="types" class="form-label">Transaction Types</label>
                  <select id="types" name="types" class="form-control">
                    <option value="1">Regular</option>
                    <option value="2">Bill To - Ship To</option>
                    <option value="3">Bill from -Dispatch From</option>
                    <option value="4">Combination of 2 and 3</option>
                  </select>
                </div>
                
                <div class="col-md-6">
                  <label for="status" class="form-label">Consignment Status</label>
                  <select id="status" name="status" class="form-control">
                    <option value="M">In Movement</option>
                    <option value="T">In Transit</option>
                    
                  </select>
                </div>

              <!-- Driver Name -->

              <!-- Vehicle Number -->
              <div class="col-md-6">
                <label for="vehicleNumber" class="form-label">Vehicle Number</label>
                <input type="text" class="form-control" id="vehicleNumber" name="vehicle_number" placeholder="ABC-1234" required>
              </div>
              
              <div class="col-md-6">
                <label for="vehicleNumber" class="form-label">Reason</label>
                <input type="text" class="form-control" id="reasons" name="reasons" placeholder="" required>
              </div>
              
               <div class="col-md-6">
                <label for="vehicleNumber" class="form-label">Ext Remarks</label>
                <input type="text" class="form-control" id="remarks" name="remarks" placeholder="" required>
              </div>

             
            </div>
          </div>
        </div>

        <div class="modal-footer">
          <button type="submit" class="btn btn-success w-100">Submit</button>
        </div>
      </div>
    </form>
  </div>
</div>
<!-- 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');
        ?>
        <form action="excel/eway_bill_extend_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="expiry" class="form-label">Today Expiry</label>-->
                <!--  <input type="checkbox" id="expiry" name="expiry" class="" value="" />-->
                <!--</div>-->
            
                <!-- Filter Button -->
                <div class="col-md-2 col-sm-6" style="display:flex;margin-top:25px">
                  <span type="button" id="filterBtn" class="btn btn-sm btn-warning"><i class="fa fa-filter"></i> Filter</span>
                  <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">EwayBill Date</th>
                        <th style="min-width:150px;" data-sortable="false">EwayBill Date Expiry</th>
                        <th style="min-width:150px;" data-sortable="false">Venus 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();
    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 from = $('#from').val();
        const pincode = $('#pincode').val();
        const vehicleNumber = $('#vehicleNumber').val();
        const vehicle_type = $('#vehicle_type').val();
        const branch_id = $('#branch_id').val();
        const reason = $('#reason').val();
        const expiry = $('#expiry').val();
        const types = $('#types').val();
        const status = $('#status').val();
        const reasons = $('#reasons').val();
        const remarks = $('#remarks').val();
        const state_code = $('#state_code').val();




     

        const formData = {
            arrayData: submittedArray,
            vehicleNumber :vehicleNumber,            
            vehicle_type :vehicle_type,
            branch_id :branch_id,
            reason :reason,
            expiry :expiry,
            types :types,
            status :status,
            reasons :reasons,
            remarks :remarks,
            state_code :state_code,
            pincode : pincode,
            from : from

        };

 $.ajax({
                url: 'apis/ewaybill-expiry-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) {
                    
                    console.log(response);
                    if(response.errors){
                    alert(response.errors);
                    }else{
                        alert(response.success_ids)
                    }
                    
                    // alert("Data submitted successfully!");
                    $('#detailsModal').modal('hide');  // Assuming this modal exists
                    $('#arrayForm')[0].reset();
                    // $('#modalForm')[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 = '') {
    if ($.fn.DataTable.isDataTable('#employee-grid')) {
        $('#employee-grid').DataTable().clear().destroy();
    }

    $('#employee-grid').DataTable({
        processing: true,
        serverSide: true,
        paging: true,
        info: true,
        lengthChange: true,
        pageLength: 10,
        searching: true,
        ordering: true,

        ajax: {
            url: "data-tables/eway_extend_dt.php",
            type: "POST",
            data: function (d) {
                d.start_date = start_date;
                d.end_date = end_date;
            },
            dataSrc: function (json) {
                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;
            },
            error: function () {
                $('#employee-grid tbody').html('<tr><td colspan="5">No data found in the server</td></tr>');
            }
        },

        order: [[0, 'desc']],

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

        rowCallback: function (row, data) {
            if (data[5] === 'expired') {
                $(row).addClass('table-danger'); // Bootstrap error styling
            }
        },

        dom: '<"row mb-3"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>' +
             '<"row"<"col-sm-12"tr>>' +
             '<"row mt-3"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>'
    });
}



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'); ?>
