<div id="ImportServiceFeeModal" class="modal fade" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">

      <div class="modal-header bg-primary">
        <h5 class="modal-title text-white">IMPORT SERVICES</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">

        <div class="mb-3">
          <label>Department</label>
          <select id="importDepartmentModal" class="form-control">
            <option value="">Select Department</option>
            <?php foreach($departments as $d): ?>
              <option value="<?= $d->id ?>"><?= $d->name ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="mb-3">
          <label>Service</label>
          <select id="importServiceModal" class="form-control">
            <option value="">Select Service</option>
          </select>
          <small id="noServiceMsgModal" class="text-danger d-none">
            No services found for this department
          </small>
        </div>

        <div class="mb-3">
          <label>CSV File</label>
          <input type="file" id="csv_file_modal" accept=".csv" class="form-control">
        </div>

      </div>

      <div class="modal-footer">
        <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button id="startImportBtnModal" class="btn btn-primary">Start Import</button>
      </div>

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

<script>
$(document).ready(function(){

    const csrfName = '<?= $this->security->get_csrf_token_name(); ?>';
    let csrfHash   = '<?= $this->security->get_csrf_hash(); ?>';
    let temp_file  = '';

    /* Load services in MODAL */
    $(document).on('change', '#importDepartmentModal', function(){

        let dep_id   = $(this).val();
        let $service = $('#importServiceModal');
        let $msg     = $('#noServiceMsgModal');

        $service.html('<option value="">Select Service</option>');
        $msg.addClass('d-none');

        if(!dep_id) return;

        $.getJSON(
            '<?= base_url("admin/sub_services/by_department/") ?>' + dep_id,
            function(data){
                if(data.length === 0){
                    $service.html('<option value="">No services found</option>');
                    $msg.removeClass('d-none');
                } else {
                    $.each(data, function(i,item){
                        $service.append(
                            '<option value="'+item.id+'">'+item.name+'</option>'
                        );
                    });
                }
            }
        );
    });

    /* Start import from MODAL */
    $(document).on('click', '#startImportBtnModal', function(){

        let service_id = $('#importServiceModal').val();
        let file       = $('#csv_file_modal')[0].files[0];

        if(!service_id || !file){
            alert('Select service and CSV file first!');
            return;
        }

        let formData = new FormData();
        formData.append('csv_file', file);
        formData.append('service_id', service_id);
        formData.append(csrfName, csrfHash);

        $.ajax({
            url: '<?= site_url("admin/sub_services/upload_csv_temp") ?>',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(res){
                if(res.status !== 'ok'){
                    alert(res.message || 'Upload failed');
                    return;
                }

                csrfHash = res.csrf_hash;

                $.post(
                    '<?= site_url("admin/sub_services/process_import") ?>',
                    {
                        temp_file : res.file,
                        service_id: service_id,
                        [csrfName]: csrfHash
                    },
                    function(resp){
                        alert(resp.message || 'Import completed!');
                        location.reload();
                    },
                    'json'
                );
            }
        });
    });

});
</script>
