  <style>
    .the-legend {
      border-style: none;
      border-width: 0;
      font-size: 15px;
      line-height: 20px;
      margin-bottom: 0;
      width: auto;
      padding: 6px 17px;
      border: 1px solid #e0e0e0;
      background: #1f67b2;
      color: white;
      font-weight: 500;
      border-radius: 18px 2%;
    }

    .the-fieldset {
      /* border: 1px solid #e0e0e0; */
      padding: 10px;
      /* background: #d2e8ffa3; */
      border-radius: 5px;

    }
  </style>

  <?php

  $cs = Yii::app()->getClientScript();

  $baseUrl = Yii::app()->baseUrl;

  $form = $this->beginWidget('CActiveForm', array(
    'id' => 'upload-audit-type-form',
    'enableAjaxValidation' => false,
    'enableClientValidation' => false,
  ));
  ?>

  <ul class="clearfix form-ul material">
    <fieldset class="the-fieldset">
      <li lass="col-sm-3" style="float: right;">
        <span style="float:left;color:red">* All fields in the excel are Mandatory *<br>
          * Vendor Name should be unique *<br>
          * Upload files in .csv format *<br>
        </span><br><br><br>
      </li>

      <li class="col-sm-3" id="div_upload">
        <?php
        $allowedExtensions = array("csv");
        $this->widget('ext.EAjaxUpload.EAjaxUpload', array(
          'id' => 'vendor_list_0_upload_csv', //rand(),//'vendor_list_0_upload_csv',
          'config' => array(
            'action' => Yii::app()->createUrl(Yii::app()->controller->id . '/UploadVendorCsv', array('folder' => 'uploads/vendor_csv')),
            'multiple' => false,
            'allowedExtensions' => $allowedExtensions,
            'sizeLimit' => 1 * 1024 * 1024,
            'onStart' => "js:function(){}",
            'class' => 'pull-right',
            'onComplete' => "js:function(id, fileName, responseJSON){
                                  $('#vendor_list_file_name').val(responseJSON.filename);
                                  vendorUpload(responseJSON.filename)
                              }",
          )
        ));
        ?>

      </li>
      <li class="col-sm-3">
        <div id="csv_msg">
        </div> 
      </li>

      <li class="col-sm-3" id="div_template">
        <?= CHtml::link(
          'Download Template',
          array('vendor/DownloadSampleCsv'),
          array('class' => '', 'target' => '_blank')
        ); ?>
        <br><br>

        <label id="remaining_count_msg"></label>

      </li>
      <li class="col-sm-3" id="total_count_msg">

      </li>
      <li class="col-sm-12" id="upload-log" style="display: none;">
        <div class="panel-body">
          <div class="custom-data-table">
            <table class="table table-hover table-bordered personal-task" id="tbl_upload_details">
              <thead>
                <tr>
                  <!-- <th>Sl.No</th> -->
                  <th>New Records</th>
                  <th>Existing Records</th>
                  <th>Error</th>
                </tr>
              </thead>
              <tbody id="tbl_upload_details_body">

              </tbody>
            </table>
          </div>
        </div>
      </li>

    </fieldset>
  </ul>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-danger" data-dismiss="modal" id="btn_category_upload_close">Close</button>
  </div>
  <?php
  $this->endWidget();
  $cs = Yii::app()->getClientScript();

  $cs->registerScript("vendorUpload", "function vendorUpload(filename)
  {

      if (filename != '') {
          jQuery.ajax({
              'type': 'post',
              'dataType': 'json',
              'data': {
                  filename: filename
              },
              'url': '" . Yii::app()->createUrl('vendor/SaveVendorUploadCsv') . "',
              'cache': false,
              'success': function (data) {
                  $('#loader').hide();
                  console.log(data);
                  if (data.status == 'success') {
                      
                      var total_records = (data.total_records || 0);
                      var success_count = data.success_count;
                      var error_count = (data.error_count || 0);
                      var existing_count = (data.existing_count || 0);
                      $('#total_count_msg').html('Total Record: '+total_records);

                      updateUploadDetailsTable(success_count, existing_count, error_count);

                      $('#upload-log').show();

                      if (data.error && data.error.length > 0) {


                          $('#csv_msg').html(data.link);
                          $('#div_template').hide();


                          $.each(data.error, function (key, val) {
                              t8.error('' + val + '');
                          });
                      } 
                      else if(data.flag === 'continue'){
                          $('#csv_msg').html(data.next_button);
                          $('#div_upload').hide();
                          $('#div_template').hide();
                      }      
                      else {

                          t8.success('Details Uploaded Successfully');
                        
                      }
                  } else {

                      if (data.error_url && data.error_url !== '') {
                                              $('#btn_category_upload_close').css('display', 'none');

                          $('#csv_msg').html(data.link);
                          $.each(data.error, function (key, val) {
                              t8.error('' + val + '');
                          });
                      }
                  }
              },
              'beforeSend': function () {
                  $('#loader').show();
              },
              'complete': function () {
                  $('#loader').hide();
              }
          });
      } else {
          t8.error('File not found');
      }
  }", CClientScript::POS_HEAD);


  ?>

  <script>
    $(document).on('click', '#next-batch-btn', function () {
      const url = $(this).data('url'); // Get the URL for the next batch
      $('#csv_msg').html(`
              <div class="spinner-border text-primary" role="status">
                  <span class="visually-hidden">Loading...</span>
              </div>
          `);
      $.ajax({
        type: 'post',
        url: url,
        dataType: 'json',
        success: function (response) {
          if (response.status === 'success') {
            $('#csv_msg').html(response.message); // Display success message
            var total_records = (response.total_records || 0);
            var success_count = response.success_count;
            var error_count = (response.error_count || 0);
            var existing_count = (response.existing_count || 0);
            $('#total_count_msg').html('Total Record: '+total_records);
            updateUploadDetailsTable(success_count, existing_count, error_count);
            if (response.flag === 'continue') {
              // Replace the Next button with the new one
              $('#csv_msg').append(response.next_button);
            } else {
              t8.success('Details Uploaded Successfully.');
            }
          } else {
            $('#csv_msg').html(response.link);

            t8.error('Error occurred while processing the batch.');
          }
        },
        error: function () {
          t8.error('Failed to process the request.');
        }
      });
    });

  </script>
  <script>
    function updateUploadDetailsTable(newRecord, existingCount, errorCount) {
      var row_html = '<tr>' +
        '<td>' + newRecord + '</td>' +
        '<td>' + existingCount + '</td>' +
        '<td>' + errorCount + '</td>' +
        '</tr>';
      $('#tbl_upload_details_body').append(row_html);
    }

  </script>