/** =============================================================
 * LT CMS allows users to create block posts, this makes it easy for users
 * with specific post or blog needs that can have a rythm and flow in reading
 * LT CMS is a product of LWEGATECH under MIT LICENSE
 * So this js will have all POST BLOCK Activity
 *=================================================================*/
// Auto expand the Text Area as content increases   
$("textarea").each(function () {
    this.setAttribute("style", "height:" + (this.scrollHeight) + "px;overflow-y:hidden;border:0px");
  }).on("input", function () {
    this.style.height = "auto";
    this.style.height = (this.scrollHeight) + "px";
  }).on("click", function () {
    // Display the entire content when clicked to edit
    this.style.height = (this.scrollHeight) + "px";
  });
   
  
  $(document).ready(function () {
      // Function to show the selected block element
      function showBlockElement(elementClass) {
        $('.block-element').hide(); // Hide all block elements
        $('.' + elementClass).show(); // Show the selected block element
      }
    
      // Event listener for the dropdown menu items
      $('.dropdown-menu a').on('click', function (e) {
        e.preventDefault();
        var selectedOption = $(this).text().trim().toLowerCase();
    
        // Determine which block element to show based on the selected option
        switch (selectedOption) {
          case 'add heading':
            showBlockElement('heading-block');
            break;
          case 'add text':
            showBlockElement('text-block');
            break;
          case 'add image':
            showBlockElement('image-block');
            break;
          case 'add code':
            showBlockElement('code-block');
            break;
          case 'add video':
            showBlockElement('video-block');
            break;
          case 'add advert':
            showBlockElement('advertcode-block');
            break;
          case 'add list':
            showBlockElement('list-block');
            break;
          default:
            $('.block-element').hide(); // Hide all block elements if none is selected
        }
      });
    });
    
  
  // Saving POST Blocks Content
  $(document).ready(function()
    {
      // Saving Text Block Content
      $("#addTextButton").click( function(e){
        // Serialize the form data
        e.preventDefault();
        //var formData = $('#text-form').serialize();
        var form = $("#text-form")[0];
    
        $.ajax({
          type: 'post',
          url: base_url + 'administrator/team/block/text/add',
          dataType: "JSON",
          data: new FormData(form),
          processData: false,
          contentType: false,
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          beforeSend: function(){
            $('#addTextButton').attr("disabled","disabled");
            $('#addTextButton').text('Please wait...');
          },
          success: function (data) {
            if (data.success == true) {
              toastr.success(data.msg);
              window.location.reload();
            } else {
              toastr.error(data.msg);
            }
          },
          error: function (xhr, status, error) {
            console.error(xhr, status, error);
          }
        });
      });
      // Saving Heading Block Content
      $("#addHeadingButton").click( function(e){
        // Serialize the form data
        e.preventDefault();
        //var formData = $('#text-form').serialize();
        var form = $("#heading-form")[0];
    
        $.ajax({
          type: 'post',
          url: base_url + 'administrator/team/block/heading/add',
          dataType: "JSON",
          data: new FormData(form),
          processData: false,
          contentType: false,
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          beforeSend: function(){
            $('#addHeadingButton').attr("disabled","disabled");
            $('#addHeadingButton').text('Please wait...');
          },
          success: function (data) {
            if (data.success == true) {
             toastr.success(data.msg);
              window.location.reload();
            } else {
              toastr.error(data.msg);
            }
          },
          error: function (xhr, status, error) {
            console.error(xhr, status, error);
          }
        });
      });
  
      // Saving List Block Content
      $("#addListButton").click( function(e){
        e.preventDefault();
        var form = $("#list-form")[0];
        $.ajax({
          type: 'post',
          url: base_url + 'administrator/team/block/list/add',
          dataType: "JSON",
          data: new FormData(form),
          processData: false,
          contentType: false,
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          beforeSend: function(){
            $('#addListButton').attr("disabled","disabled");
            $('#addListButton').text('Please wait...');
          },
          success: function (data) {
            if (data.success == true) {
             toastr.success(data.msg);
              window.location.reload();
            } else {
              toastr.error(data.msg);
            }
          },
          error: function (xhr, status, error) {
            console.error(xhr, status, error);
          }
        });
      });
  
      // Saving IMAGE Block Content
      $("#addImageButton").click( function(e){
        e.preventDefault();
        var form = $("#image-form")[0];
        $.ajax({
          type: 'post',
          url: base_url + 'administrator/team/block/image/add',
          dataType: "JSON",
          data: new FormData(form),
          processData: false,
          contentType: false,
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          beforeSend: function(){
            $('#addImageButton').attr("disabled","disabled");
            $('#addImageButton').text('Please wait...');
          },
          success: function (data) {
            if (data.success == true) {
             toastr.success(data.msg);
              window.location.reload();
            } else {
              toastr.error(data.msg);
            }
          },
          error: function (xhr, status, error) {
            console.error(xhr, status, error);
          }
        });
      });
  
      // Saving VIDEO Block Content
      $("#addVideoButton").click( function(e){
        e.preventDefault();
        var form = $("#video-form")[0];
        $.ajax({
          type: 'post',
          url: base_url + 'administrator/team/block/video/add',
          dataType: "JSON",
          data: new FormData(form),
          processData: false,
          contentType: false,
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          beforeSend: function(){
            $('#addVideoButton').attr("disabled","disabled");
            $('#addVideoButton').text('Please wait...');
          },
          success: function (data) {
            if (data.success == true) {
             toastr.success(data.msg);
              window.location.reload();
            } else {
              toastr.error(data.msg);
            }
          },
          error: function (xhr, status, error) {
            console.error(xhr, status, error);
          }
        });
      });
  
      // Saving Advert Code Block Content
      $("#addAdvertCodeButton").click( function(e){
        e.preventDefault();
        var form = $("#advertcode-form")[0];
        $.ajax({
          type: 'post',
          url: base_url + 'administrator/team/block/advert-code/add',
          dataType: "JSON",
          data: new FormData(form),
          processData: false,
          contentType: false,
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          beforeSend: function(){
            $('#addAdvertCodeButton').attr("disabled","disabled");
            $('#addAdvertCodeButton').text('Please wait...');
          },
          success: function (data) {
            if (data.success == true) {
             toastr.success(data.msg);
              window.location.reload();
            } else {
              toastr.error(data.msg);
            }
          },
          error: function (xhr, status, error) {
            console.error(xhr, status, error);
          }
        });
      });
  
      // Saving Code Block Content
      // Initialize CodeMirror
      var editor = CodeMirror.fromTextArea(document.getElementById("code-editor"), {
          mode: "htmlmixed", // Set the mode to HTML, or use other modes like JavaScript
          lineNumbers: true, // Show line numbers
          tabSize: 2, // Set the tab size
          theme: "default", // Choose a theme (you can create custom themes)
      });
      
      // Add an event listener to update the hidden input field
      editor.on("change", function (instance) {
          // Get the code content from CodeMirror and set it in the hidden input
          var codeContent = instance.getValue();
          document.getElementById("code-content").value = codeContent;
      });
      
      // Modify your existing "Send" function to use CodeMirror content
      $("#addCodeButton").click(function (e) {
        e.preventDefault();
        var form = $("#code-form")[0];
        
        // Get the code content from CodeMirror
        var codeContent = editor.getValue();
        
        // Set the code content in the hidden input field
        $("#code-content").val(codeContent);
        
        // Use FormData to send the form data, including the code content
        var formData = new FormData(form);
        //console.log(formData);
          $.ajax({
              type: 'post',
              url: base_url + 'administrator/team/block/code/add',
              dataType: "JSON",
              data: formData,
              processData: false,
              contentType: false,
              headers: { 'X-Requested-With': 'XMLHttpRequest' },
              success: function (data) {
                  if (data.success == true) {
                      toastr.success(data.msg);
                      window.location.reload();
                  } else {
                      toastr.error(data.msg);
                  }
              },
              error: function (xhr, status, error) {
                  console.error(xhr, status, error);
              }
          });
      });
      
      
    
  });
  
    //Edit Block Text
    function edit_codeblock(id) {
      // Reset the form
      $("#edit-code-form")[0].reset();
      
      $.ajax({
          url: base_url + "administrator/team/block/code/edit/" + id,
          type: "GET",
          dataType: "JSON",
          success: function(data) {
              // Set the post_id and id hidden input values
              $('[name="post_id"]').val(data.post_id);
              $('[name="id"]').val(data.id);
              
              // Set the code data in the CodeMirror editor
              editor.setValue(data.code); // Set the code data in the editor
  
              // Show the modal
              $('#code_blockModal').modal('show');
              $('.modal-title').text('Update Block');
              $('.stbtn').text('Update Code'); 
          },
          error: function(xhr, status, error) {
              toastr.error('Error - Block not retrieved');
              console.error(xhr, status, error);
          }
      });
    }
    function update_codeblock()
    {
      // Get the code content from CodeMirror
      var codeContent = editor.getValue();
  
      // Append the code content to the form data
      var form = new FormData($("#edit-code-form")[0]);
      form.append('code', codeContent);
  
        $.ajax({
          type: 'post',
          url: base_url + 'administrator/team/block/code/update',
          dataType: "JSON",
          data: form,
          processData: false,
          contentType: false,
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          success: function (data) {
            if (data.success == true) {
              $('#code_blockModal').modal('hide');
              toastr.success(data.msg);
              window.location.reload();
              $('#code_blockModal').reset;
            } else {
              toastr.error(data.msg);
            }
          },
          error: function (xhr, status, error) {
            console.error(xhr, status, error);
          }
        });
    }
    function delete_codeblock(id)
    {
      var confirmation = confirm('Are you sure want to delete this CODE BLOCK?');
      if(confirmation == true){
        window.location.href = base_url + ('administrator/team/block/code/delete/')+ id;
      }
    }
  
  
    //Edit Block Text
    function edit_blocktext(id)
    {  
  
      $("#edit-text-form")[0].reset();
      $("#text_blockModal").modal("show");
      
      $.ajax({
        url: base_url + "administrator/team/block/text/edit/" + id,
        type: "GET",
        dataType: "JSON",
        success: function(data)
        {
          $('[name="post_id"]').val(data.post_id);
          $('[name="id"]').val(data.id);
          $('[name="content"]').val(data.content);
          
          $('#text_blockModal').modal('show');
          $('.modal-title').text('Update Block');
          $('.stbtn').text('Update Text'); 
        },
        error: function (xhr, status, error) {
          toastr.error('Error - Block not retrieved');
          console.error(xhr, status, error);
        }
      });
    }
    function update_textblock()
    {
      var form = $("#edit-text-form")[0];
        $.ajax({
          type: 'post',
          url: base_url + 'administrator/team/block/text/update',
          dataType: "JSON",
          data: new FormData(form),
          processData: false,
          contentType: false,
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          success: function (data) {
            if (data.success == true) {
              $('#text_blockModal').modal('hide');
              toastr.success(data.msg);
              window.location.reload();
              $('#text_blockModal').reset;
            } else {
              toastr.error(data.msg);
            }
          },
          error: function (xhr, status, error) {
            console.error(xhr, status, error);
          }
        });
    }
    function delete_textblock(id)
    {
      var confirmation = confirm('Are you sure want to delete this TEXT BLOCK?');
      if(confirmation == true){
        window.location.href = base_url + ('administrator/team/block/text/delete/')+ id;
      }
    }
  
    //Edit HEADING Block
    function edit_headingblock(id)
    {  
      $("#edit-heading-form")[0].reset();
      $("#heading_blockModal").modal("show");
      
      $.ajax({
        url: base_url + "administrator/team/block/heading/edit/" + id,
        type: "GET",
        dataType: "JSON",
        success: function(data)
        {
          $('[name="post_id"]').val(data.post_id);
          $('[name="id"]').val(data.id);
          $('[name="heading"]').val(data.heading);
          $('[name="heading_type"]').val(data.heading_type);
          $('[name="color"]').val(data.color);
  
          
          $('#heading_blockModal').modal('show');
          $('.modal-title').text('Update Block');
          $('.stbtn').text('Update Heading'); 
        },
        error: function (xhr, status, error) {
          toastr.error('Error - Block not retrieved');
          console.error(xhr, status, error);
        }
      });
    }
    function update_headingblock()
    {
      var form = $("#edit-heading-form")[0];
        $.ajax({
          type: 'post',
          url: base_url + 'administrator/team/block/heading/update',
          dataType: "JSON",
          data: new FormData(form),
          processData: false,
          contentType: false,
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          success: function (data) {
            if (data.success == true) {
              $('#heading_blockModal').modal('hide');
              toastr.success(data.msg);
              window.location.reload();
              $('#heading_blockModal').reset;
            } else {
              toastr.error(data.msg);
            }
          },
          error: function (xhr, status, error) {
            console.error(xhr, status, error);
          }
        });
    }
    function delete_headingblock(id)
    {
      var confirmation = confirm('Are you sure want to delete this HEADING BLOCK?');
      if(confirmation == true){
        window.location.href = base_url + ('administrator/team/block/heading/delete/')+ id;
      }
    }
  
    //Edit IMAGE Block
    function edit_imageblock(id)
    {  
      $("#edit-image-form")[0].reset();
      $("#image_blockModal").modal("show");
      
      $.ajax({
        url: base_url + "administrator/team/block/image/edit/" + id,
        type: "GET",
        dataType: "JSON",
        success: function(data)
        {
          $('[name="post_id"]').val(data.post_id);
          $('[name="id"]').val(data.id);
          $('[name="caption"]').val(data.caption);
          if(data.photo !== null){
            $("#preview-image").html("<img src="+data.photo+" width='100%'>");
          }
  
          $('#image_blockModal').modal('show');
          $('.modal-title').text('Update Block');
          $('.stbtn').text('Update Photo'); 
        },
        error: function (xhr, status, error) {
          toastr.error('Error - Block not retrieved');
          console.error(xhr, status, error);
        }
      });
    }
    function update_imageblock()
    {
      var form = $("#edit-image-form")[0];
        $.ajax({
          type: 'post',
          url: base_url + 'administrator/team/block/image/update',
          dataType: "JSON",
          data: new FormData(form),
          processData: false,
          contentType: false,
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          success: function (data) {
            if (data.success == true) {
              $('#image_blockModal').modal('hide');
              toastr.success(data.msg);
              window.location.reload();
              $('#image_blockModal').reset;
            } else {
              toastr.error(data.msg);
            }
          },
          error: function (xhr, status, error) {
            console.error(xhr, status, error);
          }
        });
    }
    function delete_imageblock(id)
    {
      var confirmation = confirm('Are you sure want to delete this IMAGE BLOCK?');
      if(confirmation == true){
        window.location.href = base_url + ('administrator/team/block/image/delete/')+ id;
      }
    }
  
    //Edit VIDEO Block
    function edit_videoblock(id)
    {  
      $("#edit-video-form")[0].reset();
      $("#video_blockModal").modal("show");
      
      $.ajax({
        url: base_url + "administrator/team/block/video/edit/" + id,
        type: "GET",
        dataType: "JSON",
        success: function(data)
        {
          $('[name="post_id"]').val(data.post_id);
          $('[name="id"]').val(data.id);
          $('[name="url"]').val(data.url);
          $('[name="content"]').val(data.content);
          
  
          $('#video_blockModal').modal('show');
          $('.modal-title').text('Update Block');
          $('.stbtn').text('Update Link'); 
        },
        error: function (xhr, status, error) {
          toastr.error('Error - Block not retrieved');
          console.error(xhr, status, error);
        }
      });
    }
    function update_videoblock()
    {
      var form = $("#edit-video-form")[0];
        $.ajax({
          type: 'post',
          url: base_url + 'administrator/team/block/video/update',
          dataType: "JSON",
          data: new FormData(form),
          processData: false,
          contentType: false,
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          success: function (data) {
            if (data.success == true) {
              $('#video_blockModal').modal('hide');
              toastr.success(data.msg);
              window.location.reload();
              $('#video_blockModal').reset;
            } else {
              toastr.error(data.msg);
            }
          },
          error: function (xhr, status, error) {
            console.error(xhr, status, error);
          }
        });
    }
    function delete_videoblock(id)
    {
      var confirmation = confirm('Are you sure want to delete this VIDEO BLOCK?');
      if(confirmation == true){
        window.location.href = base_url + ('administrator/team/block/video/delete/')+ id;
      }
    }
  
    //Edit LIST Block
    function edit_listblock(id)
    {  
      $("#edit-list-form")[0].reset();
      $("#list_blockModal").modal("show");
      
      $.ajax({
        url: base_url + "administrator/team/block/list/edit/" + id,
        type: "GET",
        dataType: "JSON",
        success: function(data)
        {
          $('[name="post_id"]').val(data.post_id);
          $('[name="id"]').val(data.id);
          $('[name="list_type"]').val(data.list_type);
          $('[name="content"]').val(data.content);
          
  
          $('#list_blockModal').modal('show');
          $('.modal-title').text('Update Block');
          $('.stbtn').text('Update List'); 
        },
        error: function (xhr, status, error) {
          toastr.error('Error - Block not retrieved');
          console.error(xhr, status, error);
        }
      });
    }
    function update_listblock()
    {
      var form = $("#edit-list-form")[0];
        $.ajax({
          type: 'post',
          url: base_url + 'administrator/team/block/list/update',
          dataType: "JSON",
          data: new FormData(form),
          processData: false,
          contentType: false,
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          success: function (data) {
            if (data.success == true) {
              $('#list_blockModal').modal('hide');
              toastr.success(data.msg);
              window.location.reload();
              $('#list_blockModal').reset;
            } else {
              toastr.error(data.msg);
            }
          },
          error: function (xhr, status, error) {
            console.error(xhr, status, error);
          }
        });
    }
    function delete_listblock(id)
    {
      var confirmation = confirm('Are you sure want to delete this LIST BLOCK?');
      if(confirmation == true){
        window.location.href = base_url + ('administrator/team/block/list/delete/')+ id;
      }
    }
  
    //Edit ADVERT CODE Block
    function edit_advertcodeblock(id)
    {  
      $("#edit-advert-form")[0].reset();
      $("#advert_blockModal").modal("show");
      
      $.ajax({
        url: base_url + "administrator/team/block/advertcode/edit/" + id,
        type: "GET",
        dataType: "JSON",
        success: function(data)
        {
          $('[name="post_id"]').val(data.post_id);
          $('[name="id"]').val(data.id);
          $('[name="advert_code"]').val(data.advert_code);
          
  
          $('#advert_blockModal').modal('show');
          $('.modal-title').text('Update Block');
          $('.stbtn').text('Update Advert'); 
        },
        error: function (xhr, status, error) {
          toastr.error('Error - Block not retrieved');
          console.error(xhr, status, error);
        }
      });
    }
    function update_advertcodeblock()
    {
      var form = $("#edit-advert-form")[0];
        $.ajax({
          type: 'post',
          url: base_url + 'administrator/team/block/advertcode/update',
          dataType: "JSON",
          data: new FormData(form),
          processData: false,
          contentType: false,
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          success: function (data) {
            if (data.success == true) {
              $('#advert_blockModal').modal('hide');
              toastr.success(data.msg);
              window.location.reload();
              $('#advert_blockModal').reset;
            } else {
              toastr.error(data.msg);
            }
          },
          error: function (xhr, status, error) {
            console.error(xhr, status, error);
          }
        });
    }
    function delete_advertcodeblock(id)
    {
      var confirmation = confirm('Are you sure want to delete this ADVERT BLOCK?');
      if(confirmation == true){
        window.location.href = base_url + ('administrator/team/block/advertcode/delete/')+ id;
      }
    }
    
  
  
  //Show Code with codemirror settings
  document.addEventListener('DOMContentLoaded', function () {
    const codeBlocks = document.querySelectorAll('.codemirror-container');
    codeBlocks.forEach(function (block) {
        const codeContent = block.dataset.code;
  
        // Create a new CodeMirror instance for each code block
        const editor = CodeMirror(block, {
            value: codeContent,
            mode: 'htmlmixed', // Set the mode to HTML mixed mode
            lineNumbers: true, // Show line numbers
            theme: 'yonce', // Choose your preferred theme
            readOnly: true // Make the editor read-only
        });
    });
  });
  
  
  