  <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">

  <style>
    /* ==== Card Borders ==== */
    .border-primary { border-color: rgb(27, 28, 30) !important; }
    .border-info { border-color: rgb(41, 60, 64) !important; }

    /* ==== Gradient Header ==== */
    .gradient-header {
      background: linear-gradient(45deg, #ffd700, #e38a49);
      color: #fff;
      font-weight: 500;
      transition: background 0.3s ease;
      cursor: pointer;
    }
    .gradient-header .arrow-icon {
      transition: transform 0.3s ease;
    }
    .gradient-header.collapsed .arrow-icon {
      transform: rotate(-90deg);
    }

    /* ==== Document Item Styles ==== */
    .card { border-radius: 12px; overflow: hidden; }
    .document-list { border-radius: 12px; background: #f9f9f9; }
    .doc-item {
      background: #fff;
      border: 1px solid #e0e0e0;
      border-radius: 8px;
    }
    .doc-item:hover { background: #f1f9ff; }

    /* ==== Icon Boxes ==== */
    .icon-box {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      width: 35px;
      height: 35px;
      border-radius: 12px;
      font-size: 16px;
      transition: all 0.3s ease;
      text-decoration: none;
    }
    .icon-box:hover { transform: translateY(-3px); box-shadow: 0 4px 10px rgba(0,0,0,0.1); }

    /* ==== Gradient Toggle Header ==== */
    .gradient-header { background: linear-gradient(90deg, #007bff, #00bcd4); }
    .gradient-header .arrow-icon { transition: transform 0.3s; }
    .gradient-header .rotate { transform: rotate(180deg); }

    /* ==== Hover States ==== */
    .doc-item:hover { background: #f9f9f9; }
  </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="authority" class="form-control">
                <option value="">Select Authority</option>
                <?php foreach($authority_data as $authority): ?>
                  <option value="<?= $authority['id']; ?>"><?= $authority['authority_name']; ?></option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="col-md-3">
              <select name="year" class="form-control">
                <option value="">Select Year</option>
                <?php $year = date('Y'); for($i = 2024; $i <= $year; $i++): ?>
                  <option value="<?= $i; ?>" <?= ($i == date('Y')) ? 'selected' : ''; ?>><?= $i; ?></option>
                <?php endfor; ?>
              </select>
            </div>

            <div class="col-md-3">
              <select name="monthly" class="form-control">
                <option value="">Select Month</option>
                <?php 
                  $months = [
                    '01'=>'January','02'=>'February','03'=>'March','04'=>'April','05'=>'May','06'=>'June',
                    '07'=>'July','08'=>'August','09'=>'September','10'=>'October','11'=>'November','12'=>'December'
                  ];
                  foreach($months as $key=>$month): ?>
                    <option value="<?= $key; ?>"><?= $month; ?></option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="col-md-3">
              <button type="submit" class="btn btn-info w-100">Submit</button>
            </div>
          </form>

          <!-- ===== Document Results ===== -->
          <div id="documentResults">
            <div class="row">
              <?php $i = 1; foreach($type_data as $type): ?>
              <div class="col-md-12 mb-3">
                <div class="card border-info">
                  <div class="card-header gradient-header collapsed" data-bs-toggle="collapse" data-bs-target="#collapse-<?= $i; ?>">
                    <div class="d-flex justify-content-between align-items-center">
                      <h5 class="mb-0"><?= ucfirst($type['type_name']); ?> (<?= $type['doc_count']; ?> Documents)</h5>
                      <i class="fa fa-chevron-down arrow-icon"></i>
                    </div>
                  </div>

                  <div id="collapse-<?= $i; ?>" class="collapse show">
                    <div class="card-body p-3">
                      <?php foreach($type['documents'] as $doc): ?>
                        <div class="doc-item d-flex justify-content-between align-items-center p-3 mb-2" id="doc-item-<?= $doc['doc_id']; ?>">
                          <div>
                            <h6 class="mb-1 fw-bold"><?= $doc['doc_name']; ?></h6>
                            <small class="text-muted file-name"><?= ($doc['file_name']) ? $doc['file_name'] : 'No file uploaded'; ?></small><br>
                            <?php if($doc['file_name']): ?>
                              <small class="text-muted uploaded-on">Uploaded: <?= $doc['uploaded_at']; ?></small>
                            <?php endif; ?>
                          </div>
                          <div class="doc-actions">
                            <?php if($doc['file_name']): ?>
                              <?php if (can_edit()): ?>
                              <a href="#" class="openEditModal me-2" data-id="<?= $doc['doc_id']; ?>" title="Edit"><i class="fa fa-edit fa-lg text-primary"></i></a>
                              <?php endif; ?>
                              <?php if (can_delete()): ?>
                              <a href="#" class="deleteDocument me-2" data-id="<?= $doc['doc_id']; ?>" title="Delete"><i class="fa fa-trash fa-lg text-danger"></i></a>
                              <?php endif; ?>
                              <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>
                            <?php else: ?>
                              <?php if (can_edit()): ?>
                              <a href="#" class="openUploadModal" data-id="<?= $doc['doc_id']; ?>" title="Upload"><i class="fa fa-upload fa-lg text-secondary"></i></a>
                              <?php else: ?>
                              <span class="badge bg-warning text-dark">View Only</span>
                              <?php endif; ?>
                            <?php endif; ?>
                          </div>
                        </div>
                      <?php endforeach; ?>
                    </div>
                  </div>
                </div>
              </div>
              <?php $i++; endforeach; ?>
            </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>
$(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');
          }
        });
      }
    });
  });
});
</script>