<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="<?php echo base_url();?>public/assets/css/choices.min.css">
<script src="<?php echo base_url();?>public/assets/js/choices.min.js"></script>	

  <style>
     body { background: #f9f9f9; padding: 20px; }
  .timeline {
    width: 60%;
    margin: 0 auto;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 6px rgba(0,0,0,0.1);
    padding: 10px 20px;
  }
  .year {
    background: #f4b083;
    padding: 8px 15px;
    border-radius: 5px;
    font-weight: bold;
    cursor: pointer;
    margin-top: 10px;
  }
  .month {
    background: #d9b8f1;
    padding: 5px 15px;
    border-radius: 5px;
    margin: 5px 0 0 30px;
    font-weight: 500;
    cursor: pointer;
  }
  .documents {
    background: #d4f0d4;
    margin: 3px 0 0 60px;
    padding: 5px 15px;
    border-radius: 5px;
  }
  .doc-item {
    padding: 3px 0;
    border-bottom: 1px dotted #bbb;
  }
  .doc-item:last-child { border-bottom: none; }
  .authority, .year, .month { cursor: pointer; padding: 6px 10px; margin: 3px 0; border-radius: 5px; }
.authority { background-color: #007bff; color: white; font-weight: bold; }
.year { background-color: #28a745; color: white; margin-left: 20px;line-height:2.2rem; }
.month { background-color: #ffc107; margin-left: 40px;line-height:2.2rem; }
.documents { margin-left: 60px; }
.doc-item { padding: 10px 0; }
  </style>

<div class="content-wrapper p-3">
  <section class="content pt-3">
    <div class="container-fluid">

      <!-- ===== Company Info Cards ===== -->
      
      <!-- ===== Filter Form ===== -->
      <div class="card card-outline card-info mb-4">
        <div class="card-header"><h4 class="card-title">View Documents</h4></div>
        <div class="card-body">

          <form id="documentFilterForm" action="<?= base_url('company/filter'); ?>" method="post" class="row g-2 align-items-center mb-3">
            <input type="hidden" name="company_id" value="<?= $company_list[0]['id']; ?>">

            <div class="col-md-3">
              <select name="authoritySelect" id="authoritySelect" class="form-control" multiple>
                <option value="">Select Authority Type</option>
                <?php foreach($type_data1 as $authority): ?>
                  <option value="<?= $authority['id']; ?>"><?= $authority['type_name']; ?></option>
                <?php endforeach; ?>
              </select>
            </div>
          </form>

          <!-- ===== Document Results ===== -->
          <div id="documentResults">
            <div id="timeline" class="mt-4"></div>
          </div>

        </div>
      </div>

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

<!-- ===== Edit Modal ===== -->
<div class="modal fade" id="editModal" tabindex="-1">
  <div class="modal-dialog">
    <form id="editForm" enctype="multipart/form-data">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Edit Document</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <input type="hidden" name="doc_id" id="edit_doc_id">
          <input type="hidden" name="<?= $this->security->get_csrf_token_name(); ?>" value="<?= $this->security->get_csrf_hash(); ?>">
          <div class="form-group mb-3">
            
            <input type="text" id="edit_document_name" name="document_name" class="form-control" readonly>
			<label>Document Name</label>
          </div>
          <div class="form-group mb-3">
            Current File
            <div id="uploaded_file" class="border rounded p-2 bg-light small text-muted"></div>
          </div>
          <div class="form-group mb-3">
           
            <input type="file" name="file" class="form-control">
			 <label>Replace File</label>
          </div>
          <div id="editMsg" class="small"></div>
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-primary">Save Changes</button>
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        </div>
      </div>
    </form>
  </div>
</div>

<!-- ===== JS Dependencies ===== -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<!-- ===== Custom Script ===== -->
<script>
  const base_url = "<?= base_url(); ?>";
</script>
<script>
$(document).ready(function() {
  const authoritySelect = document.getElementById('authoritySelect');
  if (authoritySelect) {
    new Choices(authoritySelect, {
      removeItemButton: true,
      placeholder: true,
      placeholderValue: 'Select authority type(ssssss)...'
    });
  } else {
    console.error("⚠️ Could not find #authoritySelect element");
  }
});
$(document).ready(function() {
	 
$("#documentFilterForm").submit(function(e) {
    e.preventDefault();
    $.ajax({
      url: $(this).attr("action"),
      type: "POST",
      data: $(this).serialize(),
      beforeSend: ()=> $("#documentResults").html("<div class='p-3 text-center text-muted'>Loading...</div>"),
      success: (res)=> $("#documentResults").html(res),
      error: ()=> $("#documentResults").html("<div class='p-3 text-danger'>Error loading documents</div>")
    });
  });	
  const editModalEl = document.getElementById('editModal');
  const editModal = new bootstrap.Modal(editModalEl);

  // Collapse header arrow animation
  $(document).on('click', '.gradient-header', function(){
    $(this).find('.arrow-icon').toggleClass('rotate');
  });

  // ===== Open Edit Modal =====
  $(document).on('click', '.openEditModal', function(e){
    e.preventDefault();
    const docId = $(this).data('id');

    $.ajax({
      url: "<?= base_url('company/getDocument'); ?>",
      type: "POST",
      data: { 
        doc_id: docId, 
        "<?= $this->security->get_csrf_token_name(); ?>": "<?= $this->security->get_csrf_hash(); ?>" 
      },
      dataType: "json",
      success: function(res){
        if(res.status === 'success'){
          $('#edit_doc_id').val(res.data.id);
          $('#edit_document_name').val(res.data.document_name);
          $('#uploaded_file').html(res.data.file_name || '<i>No file uploaded</i>');
          $('#editMsg').html('');
          editModal.show();
        } else {
          Swal.fire('Error', res.message, 'error');
        }
      },
      error: function(){
        Swal.fire('Error', 'Error fetching document details.', 'error');
      }
    });
  });

  // ===== Save Edited Document =====
  $('#editForm').submit(function(e){
    e.preventDefault();
    const formData = new FormData(this);

    $.ajax({
      url: "<?= base_url('company/updateDocument'); ?>",
      type: "POST",
      data: formData,
      dataType: "json",
      contentType: false,
      processData: false,
      beforeSend: function(){
        $('#editMsg').removeClass().addClass('text-info').html('Saving...');
      },
      success: function(res){
        if(res.status === 'success'){
          $('#editMsg').removeClass().addClass('text-success').html(res.message);
          const docId = res.data.id;
          const newFile = res.data.file_name;

          $('#doc-item-' + docId).find('.file-name').text(newFile);
          $('#doc-item-' + docId).find('.uploaded-on').text('Uploaded: ' + res.data.uploaded_at);

          setTimeout(() => {
            editModal.hide();
            Swal.fire('Updated', 'Document updated successfully!', 'success');
          }, 600);
        } else {
          $('#editMsg').removeClass().addClass('text-danger').html(res.message);
        }
      },
      error: function(){
        $('#editMsg').removeClass().addClass('text-danger').html('Error while saving.');
      }
    });
  });

  // ===== Delete Document =====
  $(document).on('click', '.deleteDocument', function(e){
    e.preventDefault();
    const docId = $(this).data('id');
    const row = $('#doc-item-' + docId);

    Swal.fire({
      title: 'Are you sure?',
      text: 'You will not be able to recover this document!',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Yes, delete it!',
      cancelButtonText: 'Cancel'
    }).then((result) => {
      if (result.isConfirmed) {
        $.ajax({
          url: "<?= base_url('company/deleteDocument'); ?>",
          type: "POST",
          data: { 
            doc_id: docId, 
            "<?= $this->security->get_csrf_token_name(); ?>": "<?= $this->security->get_csrf_hash(); ?>" 
          },
          dataType: "json",
          success: function(res){
            if(res.status === "success"){
              row.fadeOut(400, () => row.remove());
              Swal.fire('Deleted!', 'Document deleted successfully.', 'success');
            } else {
              Swal.fire('Error', res.message, 'error');
            }
          },
          error: function(){
            Swal.fire('Error', 'Error deleting document.', 'error');
          }
        });
      }
    });
  });
});

function buildTimeline(documents) {
  //console.log("📄 Documents array:", documents); 
  $("#timeline").empty();

  if (!documents || documents.length === 0) {
    $("#timeline").html("<p class='text-muted text-center'>No documents found</p>");
    return;
  }

  const grouped = {};
  documents.forEach(d => {
    const authority = d.authority || 'Unknown Authority';
    const authority_id = d.authority_id || 'unknown';
    const year = d.year;
    const monthNum = d.month.padStart(2, "0");
    const monthName = getMonthName(monthNum);

    //if (!grouped[authority_id]) grouped[authority_id] = {};
    
    if (!grouped[authority]) grouped[authority] = {};
    if (!grouped[authority][year]) grouped[authority][year] = {};
    if (!grouped[authority][year][monthName]) grouped[authority][year][monthName] = [];
    grouped[authority][year][monthName].push(d);
  });

  for (const authority in grouped) {
    
    const authorityEl = $(`
      <div class='authority d-flex align-items-center justify-content-between' 
          style='line-height:3rem; padding:0 10px;' 
          data-authority='${authority}'>

        <span><i class="fa-solid fa-caret-right me-2 toggle-icon"></i> ${authority}</span>

        <i class="fa-solid fa-download fa-lg text-success download-icon ms-auto" 
          title="Download all for ${authority}" 
          data-level="authority" 
          data-value="${authority}">
        </i>
      </div>
    `);

    const yearsContainer = $('<div class="years ms-4"></div>').hide();

    for (const year in grouped[authority]) {
      const yearEl = $(`<div class='year d-flex align-items-center justify-content-between'  style='line-height:2.5rem' data-year='${year}'>
      <span><i class="fa-solid fa-caret-right me-2 toggle-icon"></i> ${year}</span>
      <i class="fa-solid fa-download fa-md text-primary download-icon" 
           title="Download all for ${authority} ${year}" 
           data-level="year" data-authority="${authority}" data-value="${year}" ></i>
      </div>`);
      const monthsContainer = $('<div class="months"></div>').hide();

      for (const month in grouped[authority][year]) {
        const monthEl = $(`<div class='month d-flex align-items-center justify-content-between' 
             style='line-height:2.2rem'  data-month='${month}'>
             <span><i class="fa-solid fa-caret-right me-2 toggle-icon"></i> ${month}</span>
             <i class="fa-solid fa-download fa-sm text-secondary download-icon" 
             title="Download all for ${authority} ${year} ${month}" 
             data-level="month" data-authority="${authority}" 
             data-year="${year}" data-value="${month}"></i>
             </div>`);
        const docsContainer = $('<div class="documents"></div>').hide();

        grouped[authority][year][month].forEach(doc => {
          const hasFile = doc.name && doc.name !== "";
          const docItem = $(`
            <div class="doc-item d-flex justify-content-between align-items-center border-bottom py-1" id="doc-item-${doc.doc_id}">
              <span>${doc.name}</span>
              <div class="doc-actions">
                ${hasFile ? `
                  <a href="#" class="openEditModal me-2" data-id="${doc.doc_id}" title="Edit"><i class="fa fa-edit fa-lg text-primary"></i></a>
                  <a href="#" class="deleteDocument me-2" data-id="${doc.doc_id}" title="Delete"><i class="fa fa-trash fa-lg text-danger"></i></a>
                  <a href="${base_url}uploads/documents/${doc.file_name}" target="_blank" title="View"><i class="fa fa-eye fa-lg text-success me-2"></i></a>
                  <a href="${base_url}company/downloadDocument/${doc.doc_id}" title="Download"><i class="fa fa-cloud-download fa-lg text-info"></i></a>
                  <a href="#" class="openEditModal me-2" data-id="${doc.doc_id}" title="Print"><i class="fa fa-print fa-lg text-secondary"></i></a>
                  <a href="#" class="deleteDocument me-2" data-id="${doc.doc_id}" title="Whatsapp"><i class="fa fa-whatsapp fa-lg text-success"></i></a>
                  <a href="#" class="openEditModal me-2" data-id="${doc.doc_id}" title="Email"><i class="fa fa-envelope fa-lg text-info"></i></a>
                  <a href="#" class="deleteDocument me-2" data-id="${doc.doc_id}" title="Favourite"><i class="fa fa-star fa-lg text-warning"></i></a>

                ` : `
                  <a href="#" class="openUploadModal" data-id="${doc.doc_id}" title="Upload"><i class="fa fa-upload fa-lg text-secondary"></i></a>
                `}
              </div>
            </div>
          `);
          docsContainer.append(docItem);
        });

        monthsContainer.append(monthEl).append(docsContainer);
      }

      yearsContainer.append(yearEl).append(monthsContainer);
    }

    $("#timeline").append(authorityEl).append(yearsContainer);
  }
}
function getMonthName(num) {
  const months = [
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
  ];
  const index = parseInt(num, 10) - 1;
  return months[index] || num;
}
// Toggle behavior
/*$(document).on('click', '.authority', function() {
  $(this).next('.years').slideToggle();
});
$(document).on('click', '.year', function() {
  $(this).next('.months').slideToggle();
});
$(document).on('click', '.month', function() {
  $(this).next('.documents').slideToggle();
}); */

let clickTimer = null;

$(document).on('click', '.authority, .year, .month', function (e) {
  // Prevent conflict with dropdowns or icons
  if (
    $(e.target).is('select, option, input, textarea, button, label') ||
    $(e.target).closest('.dropdown, .dropdown-menu, .multiselect-container').length > 0 ||
    $(e.target).hasClass('download-icon') ||
    ($(e.target).is('i') && !$(e.target).hasClass('toggle-icon'))
  ) {
    return;
  }

  const $this = $(this);

  // Handle single vs double click with timer
  if (clickTimer) {
    clearTimeout(clickTimer);
    clickTimer = null;
    handleDoubleClick($this);
  } else {
    clickTimer = setTimeout(() => {
      handleSingleClick($this);
      clickTimer = null;
    }, 250); // 250ms threshold for double click
  }
});

function handleSingleClick($this) {
  // Toggle only the immediate next level
  const caret = $this.find('.toggle-icon').first();
  caret.toggleClass('fa-caret-right fa-caret-down');

  if ($this.hasClass('authority')) {
    $this.next('.years').slideToggle(200);
  } else if ($this.hasClass('year')) {
    $this.next('.months').slideToggle(200);
  } else if ($this.hasClass('month')) {
    $this.next('.documents').slideToggle(200);
  }
}

function handleDoubleClick($this) {
  // Toggle all nested levels recursively
  const caret = $this.find('.toggle-icon').first();
  const isOpen = caret.hasClass('fa-caret-down');

  caret.toggleClass('fa-caret-right fa-caret-down');

  const targetContainer =
    $this.hasClass('authority')
      ? $this.next('.years')
      : $this.hasClass('year')
      ? $this.next('.months')
      : $this.hasClass('month')
      ? $this.next('.documents')
      : null;

  if (!targetContainer) return;

  if (isOpen) {
    // Collapse all children
    targetContainer.find('.years, .months, .documents').slideUp(200);
    targetContainer.slideUp(200);
    targetContainer
      .find('.toggle-icon')
      .removeClass('fa-caret-down')
      .addClass('fa-caret-right');
  } else {
    // Expand all children
    targetContainer.slideDown(200);
    targetContainer.find('.years, .months, .documents').slideDown(200);
    targetContainer
      .find('.toggle-icon')
      .removeClass('fa-caret-right')
      .addClass('fa-caret-down');
  }
}

// Fetch data on select change
$('#authoritySelect').on('change', function() {
  const selected = $(this).val(); // array of selected authority IDs
  if (!selected || selected.length === 0) {
    $("#timeline").empty();
    return;
  }

  $.ajax({
    url: '<?= base_url('company/getDocumentsByAuthority'); ?>',
    type: 'POST',
    data: { authority_ids: selected },
    dataType: 'json',
    beforeSend: function() {
      $("#timeline").html("<p>Loading...</p>");
    },
    success: function(response) {
      buildTimeline(response);
    },
    error: function() {
      $("#timeline").html("<p class='text-danger'>Failed to load data</p>");
    }
  });
});
$(document).ready(function() {
  const companyId = $('input[name="company_id"]').val();

  // Reusable function for AJAX
  function fetchDocuments(selectedAuthorities = []) {
    $.ajax({
      url: '<?= base_url('company/getDocumentsByAuthority'); ?>',
      type: 'POST',
      data: { 
        authority_ids: selectedAuthorities,
        company_id: companyId
      },
      dataType: 'json',
      beforeSend: function() {
        $("#timeline").html("<p class='text-center text-muted'>Loading...</p>");
      },
      success: function(response) {
        buildTimeline(response,true);
      },
      error: function() {
        $("#timeline").html("<p class='text-danger text-center'>Failed to load data.</p>");
      }
    });
  }

  // ===== 1️⃣ On page load - fetch all documents
  fetchDocuments(); // No parameters = all documents

  // ===== 2️⃣ On dropdown change - fetch filtered documents
  $('#authoritySelect').on('change', function() {
    const selected = $(this).val(); // array of selected authority IDs
    if (!selected || selected.length === 0) {
      fetchDocuments(); // load all again if none selected
    } else {
      fetchDocuments(selected);
    }
  });
});

$(document).on('click', '.download-icon', function () {
  const level = $(this).data('level');
  //const authorityId = $(this).data('authorityid');
  //alert(authorityId);
  //const authority = $(this).data('authority');
  const authority = $(this).closest('.authority').data('authority'); // pulls from parent div
  //const authorityId = $(this).closest('.authority').data('authorityId');
  //alert(authority);
  const year = $(this).data('year');
  const value = $(this).data('value');

  let url = '';
  
  if (level === 'authority') 
    url = "<?= base_url('company/download_all/15') ?>";
  else if (level === 'year')
      url = "<?= base_url('company/download_year/') ?>" + authority + "/" + year;
  else if (level === 'month')
      url = "<?= base_url('company/download_month/') ?>" + authority + "/" + year + "/" + value;

  window.location.href = url;
});

</script>

<style>
    

.download-icon {
  color: #fff !important;
  cursor: pointer;
  transition: transform 0.2s;
}

.download-icon:hover {
  transform: scale(1.2);
}

</style>