var save_method;
/** ========================================================================
 * Directory
 * ========================================================================**/
function setupImagePreview() {
  // Handle logo upload
  $('input[name="logo"]').on('change', function(e) {
    handleImageUpload(e, '#postImgPreview', 'logo');
  });

  // Handle cover photo upload
  $('input[name="cover_photo"]').on('change', function(e) {
    handleImageUpload(e, '#postImgPreview2', 'cover');
  });
}
function handleImageUpload(event, previewSelector, type) {
  const file = event.target.files[0];
  if (!file) return;
  // Clear previous preview
  $(previewSelector).empty();

  // Validate file type
  const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/tiff', 'image/webp'];
  if (!validTypes.includes(file.type)) {
    toastr.error('Invalid file type. Please upload an image (JPEG, PNG, GIF, TIFF, or WEBP).');
    resetFileInput(event.target);
    return;
  }

  // Validate file size (2MB max)
  const maxSize = 2 * 1024 * 1024; // 2MB in bytes
  if (file.size > maxSize) {
    toastr.error(`Image too large (${formatFileSize(file.size)}). Maximum 2MB allowed.`);
    resetFileInput(event.target);
    return;
  }

  // Create preview
  const reader = new FileReader();
  reader.onload = function(e) {
    const img = document.createElement('img');
    img.src = e.target.result;
    img.className = 'img-thumbnail thumb';
    img.style.height = '120px';
    img.alt = `${type} preview`;
    
    // Different styling for cover photo if needed
    if (type === 'cover') {
      img.style.width = '100%';
      img.style.objectFit = 'cover';
    }
    
    $(previewSelector).append(img);
  };
  reader.readAsDataURL(file);
}

function resetFileInput(input) {
  // Reset the file input
  $(input).val('');
}

function formatFileSize(bytes) {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// Initialize on document ready
$(document).ready(function() {
  setupImagePreview();
});

//Directory Listing
var table_directory;
$(document).ready( function () {
  start_load()
  $(document).on('click', '[data-bs-toggle="popover"]', function () {
       $(this).popover();
   });
  table_directory = $('#directory-list').DataTable( {
  dom: 'Blfrtip',
    buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ],
    "processing": true,
    "serverSide": true,
    "ajax": {
            "url": base_url + "administrator/directory/list",
            "type": "GET",
            "data": function (d) {

                d.search = { "value": $('#directory-list_filter input').val() };
            }
    },
  "columns": [
        {"data": "id"},
        { 
          "orderable": false,
          "data": null,
          render: function (data, type, row) {
              if (data["logo"] == null) {
                  return '<img src="' + base_url + '/assets/images/no-image.gif" alt="" height="20px">';
              } else {
                  return '<img src="' + data["logo"] + '" alt="' + data["title"] + '" height="40px; object-fit:cover">';
              }
          }
        },
        {
            "orderable":      true,
            "data":           null,
            render: function ( data, type, row ) {
            return '<a href="'+ base_url +"administrator/directory/single-directory/id="+data["id"]+'"><strong><small>' + data['title'] + '</small></strong></a>'; 
            }
        },
        {
          "orderable":      true,
          "data":           null,
          render: function ( data, type, row ) {
          return '<small class="text-muted" style="font-size:11px" >' + data['category_name'] + '</small>'; 
          }
        },
        {
          "orderable":      true,
          "data":           null,
          render: function ( data, type, row ) {
          return '<a href="'+ base_url +"administrator/members/single-client/id="+data["member_id"]+'" class="text-dark"><small>' + data["fname"]+' '+data['lname']+'</small></a>'; 
          }
        },
        { 
          "orderable":      false,
          "data":           null,
          render: function ( data, type, row ) {
              if( data["is_featured"] == 1){
                  return '<span class="badge" style="background: #FF8000 ;font-weight: 600;font-size:9px;color:#fff;">Featured</span>';
              }else{
                  return '<span class="badge" style="background: #69008C ;font-weight: 600;font-size:9px;color:#fff;">Not Featured</span>';
              }
          }
        },
        { 
          "orderable":      false,
          "data":           null,
          render: function ( data, type, row ) {
              if( data["verification_status"] == 'Verified'){
                  return '<span class="badge bg-success bg-opacity-75" style="font-size:9px;">VERIFIED</span>';
              }else if( data["verification_status"] == 'Pending'){
                  return '<span class="badge bg-secondary bg-opacity-75" style="font-size:9px;">PENDING</span>';
              }else if( data["verification_status"] == 'Info'){
                  return '<span class="badge badge bg-info bg-opacity-75" style="font-size:9px;">INFO</span>';
              }else{
                  return '<span class="badge badge bg-danger bg-opacity-75">REJECTED</span>';
              }
          }
        },
        {
          "orderable": false,
          "data": null,
          render: function(data, type, row) {
            const isActive = data["active"] == 1;
            return `
              <div class="form-check form-switch">
                <input class="form-check-input status-toggle" 
                      type="checkbox" 
                      data-id="${data.id}"
                      ${isActive ? 'checked' : ''}>
                <label class="form-check-label" for="flexSwitchCheckChecked">
                  ${isActive ? 'ACTIVE' : 'INACTIVE'}
                </label>
              </div>
            `;
          }
        },
        {
          "orderable":      true,
          "data":           null,
          render: function ( data, type, row ) {
          return '<small class="text-muted" style="font-size:11px" >' + data['views_count'] + '</small>'; 
          }
        },
        {
           "orderable":      false,
           "data":           null,
           render:function(data, type, row)
           {
               var btn ='<div class="dropdown">'+
                        '<button class="btn btn-light" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">'+
                        '<i class="bi bi-three-dots-vertical"></i>'+
                        '</button>'+
                        '<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">'+
                        '<li><a href="'+base_url+'administrator/directory/edit='+data["id"]+'" class="dropdown-item" title="Edit"><small>Edit</small></a></li>'+
                        '<li><a class="dropdown-item"onclick="directory_featured('+data["id"]+',\''+data["title"]+'\')\" style="cursor: pointer"><small>Featured?</small></a></li>'+
                        '<li>'+
                        '<a class="dropdown-item" href="'+base_url+'administrator/directory/single-directory/id='+data["id"]+'"><small>View</small></a></li>'+
                        '<li><a class="dropdown-item" onclick="delete_directory('+data["id"]+',\''+data["title"]+'\')\" style="cursor: pointer"><small>Delete</small></a></li>'+
                        ' </ul>'+
                        '</div>';
                    return btn;
           }
       }
  ],
  "order": [[0, 'DESC']],
  });
  setTimeout(function(){
   end_load()
   
},500)
});

//Activate / Suspend Directory
$(document).on('change', '.status-toggle', function() {
  const directoryId = $(this).data('id');
  const isActive = $(this).is(':checked') ? 1 : 0;
  
  // Show loading state
  const $switch = $(this);
  $switch.prop('disabled', true);
  
  $.ajax({
    url: base_url + ('administrator/directory/status-change'),
    method: 'POST',
    data: {
      id: directoryId,
      active: isActive,
    },
    success: function(response) {
      $switch.next('label').text(isActive ? 'ACTIVE' : 'INACTIVE');
      toastr.success(`Status updated to ${isActive ? 'Active' : 'Inactive'}`);
    },
    error: function(xhr) {
      $switch.prop('checked', !isActive);
      toastr.error('Failed to update status');
    },
    complete: function() {
      $switch.prop('disabled', false);
    }
  });
});

//Delete Directory
 function delete_directory(id, name){
  var confirmation = confirm('Are you sure you want to delete '+ name +' Directory?');
  if(confirmation == true){
      window.location.href = base_url + ('administrator/directory/delete/')+ id;
  }
}

function directory_featured(id, title)
{
  var getTitle = title +' Directory';
  $('[name="id"]').val(id);
  $('[name="title"]').val(getTitle);
  $('#featuredModal').modal('show');
  $(".modal-title").text('Make Featured');
    $(".sbtn").text('Update Status');
}

//Add Gallery
function directory_gallery(id, title)
{
  var getTitle = title +' Directory';
  $('[name="directory_id"]').val(id);
  $('[name="title"]').val(getTitle);
  $('#addGalleryModal').modal('show');
  $(".modal-title").text('Upload  Photos');
    $(".sbtn").text('Save Gallery');
}

//Delete Gallery Photo 
function delete_galleryphoto(id, name){
  var confirmation = confirm('Are you sure you want to delete '+ name +' Photo?');
  if(confirmation == true){
      window.location.href = base_url + ('administrator/directory/gallery/delete/')+ id;
  }
}

//Add Gallery
function directory_downloads(id, title)
{
  var getTitle = title +' Directory';
  $('[name="directory_id"]').val(id);
  $('[name="directory_title"]').val(getTitle);
  $('#addDownloadModal').modal('show');
  $(".modal-title").text('Upload  File');
    $(".sbtn").text('Save Document');
}

//Delete Gallery Photo 
function delete_directoryfile(id, name){
  var confirmation = confirm('Are you sure you want to delete '+ name +' File?');
  if(confirmation == true){
      window.location.href = base_url + ('administrator/directory/download/delete/')+ id;
  }
}