@extends('layouts/contentNavbarLayout')

@section('title', 'View Report')

@section('content')

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

<div class="row">
  <div class="col-12 d-flex justify-content-between align-items-center">
    <h4 class="fw-bold py-2 mb-3">View Report</h4>
    <a href="{{ route('kpiReport-create') }}" class="btn btn-primary">Create Report</a>
  </div>

  <!-- Single Card with All Fields -->
  <div class="col-12">
    <div class="card shadow-sm">
      <div class="card-body">
        <div class="row g-3">
          <!-- Division -->
          <div class="col-md-4">
            <label for="division" class="form-label">Division</label>
            <div class="input-group">
              <input type="text" class="form-control" id="divisionInput" value="EXPORTS PROMOTION & MARKET ACCESS DIVISION" readonly>
              <button class="btn btn-outline-secondary" type="button" id="divisionDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                <i class="bx bx-chevron-down"></i>
              </button>
              <button class="btn btn-outline-secondary" type="button" onclick="$('#divisionInput').val('')">
                <i class="bx bx-x"></i>
              </button>
              <ul class="dropdown-menu" aria-labelledby="divisionDropdown">
                <li><a class="dropdown-item" href="#" onclick="$('#divisionInput').val($(this).text())">EXPORTS PROMOTION & MARKET ACCESS DIVISION</a></li>
                <li><a class="dropdown-item" href="#" onclick="$('#divisionInput').val($(this).text())">IMPORTS & STANDARDS DIVISION</a></li>
                <li><a class="dropdown-item" href="#" onclick="$('#divisionInput').val($(this).text())">INTERNATIONAL TRADE DIVISION</a></li>
                <li><a class="dropdown-item" href="#" onclick="$('#divisionInput').val($(this).text())">EXPORT DEVELOPMENT DIVISION</a></li>
              </ul>
            </div>
          </div>

          <!-- Section -->
          <div class="col-md-4">
            <label for="section" class="form-label">Section</label>
            <div class="input-group">
              <input type="text" class="form-control" id="sectionInput" value="CHINA & NORTHEAST ASIA SECTION" readonly>
              <button class="btn btn-outline-secondary" type="button" id="sectionDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                <i class="bx bx-chevron-down"></i>
              </button>
              <button class="btn btn-outline-secondary" type="button" onclick="$('#sectionInput').val('')">
                <i class="bx bx-x"></i>
              </button>
              <ul class="dropdown-menu" aria-labelledby="sectionDropdown">
                <li><a class="dropdown-item" href="#" onclick="$('#sectionInput').val($(this).text())">EUROPE SECTION</a></li>
                <li><a class="dropdown-item" href="#" onclick="$('#sectionInput').val($(this).text())">MIDDLE EAST SECTION</a></li>
                <li><a class="dropdown-item" href="#" onclick="$('#sectionInput').val($(this).text())">ASEAN SECTION</a></li>
              </ul>
            </div>
          </div>

          <!-- Unit -->
          <div class="col-md-4">
            <label for="unit" class="form-label">Unit/Office</label>
            <div class="input-group">
              <input type="text" class="form-control" id="unitInput" value="N/A" readonly>
              <button class="btn btn-outline-secondary" type="button" id="unitDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                <i class="bx bx-chevron-down"></i>
              </button>
              <button class="btn btn-outline-secondary" type="button" onclick="$('#unitInput').val('')">
                <i class="bx bx-x"></i>
              </button>
              <ul class="dropdown-menu" aria-labelledby="unitDropdown">
                <li><a class="dropdown-item" href="#" onclick="$('#unitInput').val($(this).text())">UNIT A</a></li>
                <li><a class="dropdown-item" href="#" onclick="$('#unitInput').val($(this).text())">UNIT B</a></li>
                <li><a class="dropdown-item" href="#" onclick="$('#unitInput').val($(this).text())">UNIT C</a></li>
              </ul>
            </div>
          </div>

          <!-- Report Title -->
          <div class="col-md-4">
            <label for="reportTitle" class="form-label">Report Title</label>
            <input type="text" class="form-control" id="reportTitle">
          </div>

          <!-- Report ID -->
          <div class="col-md-4">
            <label for="reportId" class="form-label">Report ID</label>
            <input type="text" class="form-control" id="reportId">
          </div>

          <!-- Achievement -->
          <div class="col-md-4">
            <label for="achievement" class="form-label">Achievement</label>
            <input type="text" class="form-control" id="achievement">
          </div>

          <!-- Indicator -->
          <div class="col-md-10">
            <label for="indicator" class="form-label">Indicator</label>
            <select class="form-select" id="indicator">
              <option selected>Please Select</option>
              <option>Indicator 1</option>
              <option>Indicator 2</option>
              <option>Indicator 3</option>
            </select>
          </div>

          <!-- Search Button -->
          <div class="col-md-2 d-flex align-items-end">
            <button type="button" class="btn btn-primary w-100">Search</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- ACTIVE Section with Display Columns Button -->
<div class="tab-section mt-3" id="reportTableWrapper">
  <div class="card">
    <!-- Add controls above the table -->
    <div class="d-flex justify-content-between align-items-center p-3">
      <div class="d-flex align-items-center">
        <label class="me-2">Show</label>
        <select class="form-select form-select-sm me-2" style="width: 70px;">
          <option value="10">10</option>
          <option value="25">25</option>
          <option value="50">50</option>
          <option value="100">100</option>
        </select>
        <span>Entries</span>
      </div>
      <!-- Display Columns Button -->
      <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#columnSelectorModal">
        <i class="bx bx-columns"></i> Display Columns
      </button>
    </div>
    <div class="table-responsive text-nowrap">
      <table class="table table-hover" id="reportTable">
        <thead>
          <tr>
            <th data-column="id">ID <i class="bx bx-sort"></i></th>
            <th data-column="title">Title <i class="bx bx-sort"></i></th>
            <th data-column="subtitle">Subtitle <i class="bx bx-sort"></i></th>
            <th data-column="remark">Remark <i class="bx bx-sort"></i></th>
            <th data-column="updated">Updated <i class="bx bx-sort"></i></th>
            <th data-column="action">Action <i class="bx bx-sort"></i></th>
          </tr>
        </thead>
        <tbody class="table-border-bottom-0">
          <tr>
            <td>KPI-RPT-AHR-95</td>
            <td>Success Stories of PMU</td>
            <td>For 2021</td>
            <td></td>
            <td>14/06/2022</td>
            <td>
              <div class="d-flex gap-2">
                <button type="button" class="btn btn-sm btn-warning edit-btn">
                  <i class="bx bx-edit"></i> Edit
                </button>
                <button type="button" class="btn btn-sm btn-danger remove-btn">
                  <i class="bx bx-trash"></i> Remove
                </button>
              </div>
            </td>
          </tr>
          <tr>
            <td>KPI-RPT-AHR-100</td>
            <td>Predefined Template Report</td>
            <td>Tahun</td>
            <td></td>
            <td>23/06/2022</td>
            <td>
              <div class="d-flex gap-2">
                <button type="button" class="btn btn-sm btn-warning edit-btn">
                  <i class="bx bx-edit"></i> Edit
                </button>
                <button type="button" class="btn btn-sm btn-danger remove-btn">
                  <i class="bx bx-trash"></i> Remove
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- REMOVED Section -->
<div class="tab-section mt-3 d-none" id="removed-section">
  <div class="card">
    <div class="table-responsive text-nowrap">
      <table class="table table-hover">
      <thead>
  <tr>
    <th>ID <i class="bx bx-sort"></i></th>
    <th>Title <i class="bx bx-sort"></i></th>
    <th>Subtitle <i class="bx bx-sort"></i></th>
    <th>Remark <i class="bx bx-sort"></i></th>
    <th>Updated <i class="bx bx-sort"></i></th>
    <th>Action <i class="bx bx-sort"></i></th>
  </tr>
</thead>
        <tbody>
          <tr>
            <td>KPI-RPT-AHR-177</td>
            <td>dsadasd</td>
            <td>sdsasad dasdas</td>
            <td></td>
            <td>15/08/2022</td>
            <td>
              <button class="btn btn-sm btn-primary">Activate</button>
            </td>
          </tr>
          <tr>
            <td>KPI-RPT-AHR-178</td>
            <td>Report Analysis Sample</td>
            <td>TBU (Year 2020-2021)</td>
            <td></td>
            <td>15/08/2022</td>
            <td>
              <button class="btn btn-sm btn-primary">Activate</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

  <!-- Report View Modal -->
  <div class="modal fade" id="reportViewModal" tabindex="-1" aria-labelledby="reportViewModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="reportViewModalLabel">SUCCESS STORIES OF PMU</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <!-- Report Header -->
          <div class="text-center mb-4">
            <h4 class="fw-bold">SUCCESS STORIES OF PMU</h4>
            <p class="text-muted">For 2021</p>
          </div>

          <!-- Report Controls -->
          <div class="d-flex justify-content-end gap-2 mb-4">
            <button class="btn btn-secondary btn-sm" id="printReport">
              <i class="bx bx-printer"></i> Print
            </button>
            <div class="dropdown">
              <button class="btn btn-secondary btn-sm dropdown-toggle" type="button" id="exportDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                <i class="bx bx-export"></i> Export
              </button>
              <ul class="dropdown-menu" aria-labelledby="exportDropdown">
                <li><a class="dropdown-item" href="#">PDF</a></li>
                <li><a class="dropdown-item" href="#">Excel</a></li>
                <li><a class="dropdown-item" href="#">CSV</a></li>
              </ul>
            </div>
            <div class="dropdown">
              <button class="btn btn-secondary btn-sm dropdown-toggle" type="button" id="annotationDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                <i class="bx bx-comment"></i> Annotation
              </button>
              <ul class="dropdown-menu" aria-labelledby="annotationDropdown">
                <li><a class="dropdown-item" href="#">Add Note</a></li>
                <li><a class="dropdown-item" href="#">View Notes</a></li>
              </ul>
            </div>
          </div>

          <!-- Column Selector Modal for Report Table -->
<div class="modal fade" id="columnSelectorModal" tabindex="-1" aria-labelledby="columnSelectorModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="columnSelectorModalLabel">Display Columns</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body column-selector-modal">
        <p>Select columns to display:</p>
        <div class="form-check">
          <input class="form-check-input column-toggle" type="checkbox" id="idColumn" data-column="id" checked>
          <label class="form-check-label" for="idColumn">
            ID
          </label>
        </div>
        <div class="form-check">
          <input class="form-check-input column-toggle" type="checkbox" id="titleColumn" data-column="title" checked>
          <label class="form-check-label" for="titleColumn">
            Title
          </label>
        </div>
        <div class="form-check">
          <input class="form-check-input column-toggle" type="checkbox" id="subtitleColumn" data-column="subtitle" checked>
          <label class="form-check-label" for="subtitleColumn">
            Subtitle
          </label>
        </div>
        <div class="form-check">
          <input class="form-check-input column-toggle" type="checkbox" id="remarkColumn" data-column="remark" checked>
          <label class="form-check-label" for="remarkColumn">
            Remark
          </label>
        </div>
        <div class="form-check">
          <input class="form-check-input column-toggle" type="checkbox" id="updatedColumn" data-column="updated" checked>
          <label class="form-check-label" for="updatedColumn">
            Updated
          </label>
        </div>
        <div class="form-check">
          <input class="form-check-input column-toggle" type="checkbox" id="actionColumn" data-column="action" checked>
          <label class="form-check-label" for="actionColumn">
            Action
          </label>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" id="applyColumnSettings" data-bs-dismiss="modal">Apply</button>
      </div>
    </div>
  </div>
</div>

          <!-- Report Table -->
          <div class="table-responsive">
            <table class="table table-striped table-bordered">
              <thead class="table-light">
                <tr>
                  <th rowspan="2" class="align-middle">#</th>
                  <th rowspan="2" class="align-middle">Programme</th>
                  <th colspan="2" class="text-center">Exporter</th>
                  <th rowspan="2" class="text-center align-middle">Exporter Performance</th>
                  <th colspan="2" class="text-center">Activities</th>
                  <th rowspan="2" class="text-center align-middle">Activities Performance</th>
                </tr>
                <tr>
                  <th class="text-center">Target</th>
                  <th class="text-center">Achievement</th>
                  <th class="text-center">Target</th>
                  <th class="text-center">Achievement</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>1</td>
                  <td>RW:EDP</td>
                  <td class="text-center">16</td>
                  <td class="text-center">1</td>
                  <td class="text-center">6</td>
                  <td class="text-center">16</td>
                  <td class="text-center">1</td>
                  <td class="text-center">6</td>
                </tr>
                <tr>
                  <td>2</td>
                  <td>e-TRADE</td>
                  <td class="text-center">20</td>
                  <td class="text-center">5</td>
                  <td class="text-center">25</td>
                  <td class="text-center">20</td>
                  <td class="text-center">5</td>
                  <td class="text-center">25</td>
                </tr>
                <tr>
                  <td>3</td>
                  <td>LCSMEFP</td>
                  <td class="text-center">16</td>
                  <td class="text-center">4</td>
                  <td class="text-center">25</td>
                  <td class="text-center">16</td>
                  <td class="text-center">4</td>
                  <td class="text-center">25</td>
                </tr>
                <tr>
                  <td>4</td>
                  <td>MOC</td>
                  <td class="text-center">16</td>
                  <td class="text-center">4</td>
                  <td class="text-center">25</td>
                  <td class="text-center">16</td>
                  <td class="text-center">4</td>
                  <td class="text-center">25</td>
                </tr>
                <tr>
                  <td>5</td>
                  <td>Mid-Tier</td>
                  <td class="text-center">16</td>
                  <td class="text-center">4</td>
                  <td class="text-center">25</td>
                  <td class="text-center">16</td>
                  <td class="text-center">4</td>
                  <td class="text-center">25</td>
                </tr>
                <tr>
                  <td>6</td>
                  <td>Mid-Tier Ramp Up</td>
                  <td class="text-center">16</td>
                  <td class="text-center">4</td>
                  <td class="text-center">25</td>
                  <td class="text-center">16</td>
                  <td class="text-center">4</td>
                  <td class="text-center">25</td>
                </tr>
                <tr>
                  <td>7</td>
                  <td>SEF</td>
                  <td class="text-center">16</td>
                  <td class="text-center">4</td>
                  <td class="text-center">25</td>
                  <td class="text-center">16</td>
                  <td class="text-center">4</td>
                  <td class="text-center">25</td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- Pagination -->
          <div class="d-flex justify-content-between align-items-center mt-3">
            <div>
              Showing 1 to 7 of 7 Entries
            </div>
            <div>
              <nav aria-label="Page navigation">
                <ul class="pagination pagination-sm">
                  <li class="page-item disabled">
                    <a class="page-link" href="#" aria-label="Previous">
                      <span aria-hidden="true">&laquo;</span>
                    </a>
                  </li>
                  <li class="page-item active"><a class="page-link" href="#">1</a></li>
                  <li class="page-item disabled">
                    <a class="page-link" href="#" aria-label="Next">
                      <span aria-hidden="true">&raquo;</span>
                    </a>
                  </li>
                </ul>
              </nav>
            </div>
          </div>

          <!-- Modal Footer -->
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="button" class="btn btn-secondary" id="modifyReportBtn">Modify Report</button>

            <!-- Save Report Dropdown -->
            <div class="dropdown">
              <button class="btn btn-primary dropdown-toggle" type="button" id="saveReportBtn" data-bs-toggle="dropdown" aria-expanded="false">
                Save Report
              </button>
              <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="saveReportBtn">
                <li><a class="dropdown-item" href="#" id="saveExisting">Save Report</a></li>
                <li><a class="dropdown-item" href="#" id="saveNew">Save As New Report</a></li>
              </ul>
            </div>
          </div>

          <!-- Timestamp -->
          <div class="text-end mt-3">
            <small class="text-muted">DATA AS OF 22 JUN 2022, 17:40 PM</small>
          </div>

        </div>
      </div>
    </div>
  </div>
  
  <!-- Modify Report Modal -->
  <div class="modal fade" id="modifyReportModal" tabindex="-1" aria-labelledby="modifyReportModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="modifyReportModalLabel">Modify Ad-Hoc Report</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <form id="modifyReportForm">
            <!-- First Section: Division, Section, Unit -->
            <div class="row mb-3">
              <div class="col-md-4">
                <label for="modifyDivision" class="form-label">Division <span class="text-danger">*</span></label>
                <div class="input-group">
                  <input type="text" class="form-control" id="modifyDivision" name="division" value="STRATEGIC PLANNING DIVISION" readonly>
                  <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"></button>
                  <button class="btn btn-outline-secondary clear-input" type="button" data-target="modifyDivision">
                    <i class="bx bx-x"></i>
                  </button>
                  <ul class="dropdown-menu">
                    <li><a class="dropdown-item" href="#">STRATEGIC PLANNING DIVISION</a></li>
                    <li><a class="dropdown-item" href="#">EXPORTS PROMOTION & MARKET ACCESS DIVISION</a></li>
                    <li><a class="dropdown-item" href="#">INTERNATIONAL TRADE DIVISION</a></li>
                  </ul>
                </div>
              </div>
              <div class="col-md-4">
                <label for="modifySection" class="form-label">Section <span class="text-danger">*</span></label>
                <div class="input-group">
                  <input type="text" class="form-control" id="modifySection" name="section" value="COORDINATION AND MONITORING SECTION" readonly>
                  <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"></button>
                  <button class="btn btn-outline-secondary clear-input" type="button" data-target="modifySection">
                    <i class="bx bx-x"></i>
                  </button>
                  <ul class="dropdown-menu">
                    <li><a class="dropdown-item" href="#">COORDINATION AND MONITORING SECTION</a></li>
                    <li><a class="dropdown-item" href="#">CHINA & NORTHEAST ASIA SECTION</a></li>
                    <li><a class="dropdown-item" href="#">ASEAN SECTION</a></li>
                  </ul>
                </div>
              </div>
              <div class="col-md-4">
                <label for="modifyUnit" class="form-label">Unit <span class="text-danger">*</span></label>
                <div class="input-group">
                  <input type="text" class="form-control" id="modifyUnit" name="unit" value="PERFORMANCE MONITORING UNIT" readonly>
                  <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"></button>
                  <button class="btn btn-outline-secondary clear-input" type="button" data-target="modifyUnit">
                    <i class="bx bx-x"></i>
                  </button>
                  <ul class="dropdown-menu">
                    <li><a class="dropdown-item" href="#">PERFORMANCE MONITORING UNIT</a></li>
                    <li><a class="dropdown-item" href="#">UNIT A</a></li>
                    <li><a class="dropdown-item" href="#">UNIT B</a></li>
                  </ul>
                </div>
              </div>
            </div>

            <!-- Second Section: Report Type, Date Range -->
            <div class="row mb-3">
              <div class="col-md-12">
                <label for="modifyReportType" class="form-label">Report Type / Query Mapping <span class="text-danger">*</span></label>
                <div class="input-group">
                  <input type="text" class="form-control" id="modifyReportType" name="reportType" value="PREDEFINED - [ Remark: List of programme- 2 ]" readonly>
                  <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"></button>
                  <button class="btn btn-outline-secondary clear-input" type="button" data-target="modifyReportType">
                    <i class="bx bx-x"></i>
                  </button>
                  <ul class="dropdown-menu">
                    <li><a class="dropdown-item" href="#">PREDEFINED - [ Remark: List of programme- 2 ]</a></li>
                    <li><a class="dropdown-item" href="#">CUSTOM - [ Remark: Market analysis ]</a></li>
                  </ul>
                </div>
              </div>
            </div>

            <div class="row mb-3">
              <div class="col-md-3">
                <label for="modifyStartYear" class="form-label">Start Year</label>
                <input type="number" class="form-control" id="modifyStartYear" name="startYear" value="2021">
              </div>
              <div class="col-md-3">
                <label for="modifyEndYear" class="form-label">End Year</label>
                <input type="number" class="form-control" id="modifyEndYear" name="endYear" value="2021">
              </div>
              <div class="col-md-3">
                <label for="modifyStartMonth" class="form-label">Start Group of Month</label>
                <select class="form-select" id="modifyStartMonth" name="startMonth">
                  <option value="1" selected>1</option>
                  <option value="2">2</option>
                  <option value="3">3</option>
                  <option value="4">4</option>
                </select>
              </div>
              <div class="col-md-3">
                <label for="modifyEndMonth" class="form-label">End Group of Month</label>
                <select class="form-select" id="modifyEndMonth" name="endMonth">
                  <option value="1">1</option>
                  <option value="2">2</option>
                  <option value="3">3</option>
                  <option value="4" selected>4</option>
                </select>
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="button" class="btn btn-primary">Save Changes</button>
        </div>
      </div>
    </div>
  </div>

@endsection

@section('page-script')
<script>
$(document).ready(function() {
    
    // ============================
    // Dropdown Functionality
    // ============================
    
    // Handle dropdown item clicks for all dropdowns
    $('.dropdown-item').on('click', function(e) {
        e.preventDefault();
        const targetInput = $(this).closest('.input-group').find('input');
        targetInput.val($(this).text());
    });

    // Handle clear buttons for input groups
    $('.clear-input').on('click', function() {
        const targetId = $(this).data('target');
        if (targetId) {
            $('#' + targetId).val('');
        } else {
            $(this).closest('.input-group').find('input').val('');
        }
    });

    // ============================
    // Search Functionality
    // ============================
    
    $('.btn-primary').filter(function() {
        return $(this).text().trim() === 'Search';
    }).on('click', function() {
        performSearch();
    });

    function performSearch() {
        const searchData = {
            division: $('#divisionInput').val(),
            section: $('#sectionInput').val(),
            unit: $('#unitInput').val(),
            reportTitle: $('#reportTitle').val(),
            reportId: $('#reportId').val(),
            achievement: $('#achievement').val(),
            indicator: $('#indicator').val()
        };
        
        console.log('Search Data:', searchData);
        
        // Here you would typically make an AJAX call to your backend
        // Example:
        /*
        $.ajax({
            url: '/api/search-reports',
            method: 'POST',
            data: searchData,
            success: function(response) {
                updateReportTable(response);
            },
            error: function(xhr, status, error) {
                console.error('Search failed:', error);
            }
        });
        */
        
        // For now, just show a message
        alert('Search functionality triggered. Check console for search parameters.');
    }

    // ============================
    // Table Actions
    // ============================
    
    // Edit button functionality
    $(document).on('click', '.edit-btn', function() {
        const row = $(this).closest('tr');
        const reportId = row.find('td:first').text();
        const reportTitle = row.find('td:nth-child(2)').text();
        
        console.log('Edit report:', reportId, reportTitle);
        
        // You would typically navigate to edit page or open edit modal
        // window.location.href = '/reports/edit/' + reportId;
        alert('Edit functionality for report: ' + reportId);
    });

    // Remove button functionality
    $(document).on('click', '.remove-btn', function() {
        const row = $(this).closest('tr');
        const reportId = row.find('td:first').text();
        const reportTitle = row.find('td:nth-child(2)').text();
        
        if (confirm('Are you sure you want to remove report "' + reportTitle + '"?')) {
            console.log('Remove report:', reportId);
            
            // Here you would make an AJAX call to remove the report
            /*
            $.ajax({
                url: '/api/reports/' + reportId,
                method: 'DELETE',
                success: function(response) {
                    row.remove();
                    alert('Report removed successfully');
                },
                error: function(xhr, status, error) {
                    alert('Failed to remove report');
                }
            });
            */
            
            // For demo purposes, just remove the row
            row.fadeOut(300, function() {
                $(this).remove();
            });
        }
    });

    // Activate button functionality (for removed items)
    $(document).on('click', '.btn-primary', function() {
        if ($(this).text().trim() === 'Activate') {
            const row = $(this).closest('tr');
            const reportId = row.find('td:first').text();
            
            if (confirm('Are you sure you want to activate this report?')) {
                console.log('Activate report:', reportId);
                // Similar AJAX call would go here
                alert('Report activated successfully');
            }
        }
    });

    // ============================
    // Column Visibility Toggle
    // ============================
    
    // Apply column settings
    $('#applyColumnSettings').on('click', function() {
        $('.column-toggle').each(function() {
            const columnName = $(this).data('column');
            const isChecked = $(this).is(':checked');
            const columnIndex = getColumnIndex(columnName);
            
            if (columnIndex !== -1) {
                // Hide/show header
                $('#reportTable thead th').eq(columnIndex).toggle(isChecked);
                // Hide/show all cells in that column
                $('#reportTable tbody tr').each(function() {
                    $(this).find('td').eq(columnIndex).toggle(isChecked);
                });
            }
        });
    });

    function getColumnIndex(columnName) {
        const columnMap = {
            'id': 0,
            'title': 1,
            'subtitle': 2,
            'remark': 3,
            'updated': 4,
            'action': 5
        };
        return columnMap[columnName] !== undefined ? columnMap[columnName] : -1;
    }

    // ============================
    // Table Sorting
    // ============================
    
    // Handle table header clicks for sorting
    $('#reportTable thead th[data-column]').on('click', function() {
        const column = $(this).data('column');
        const sortIcon = $(this).find('i');
        
        // Reset all other sort icons
        $('#reportTable thead th i').removeClass('bx-sort-up bx-sort-down').addClass('bx-sort');
        
        // Toggle sort direction
        if (sortIcon.hasClass('bx-sort') || sortIcon.hasClass('bx-sort-down')) {
            sortIcon.removeClass('bx-sort bx-sort-down').addClass('bx-sort-up');
            sortTable(column, 'asc');
        } else {
            sortIcon.removeClass('bx-sort-up').addClass('bx-sort-down');
            sortTable(column, 'desc');
        }
    });

    function sortTable(column, direction) {
        const tbody = $('#reportTable tbody');
        const rows = tbody.find('tr').toArray();
        const columnIndex = getColumnIndex(column);
        
        if (columnIndex === -1) return;
        
        rows.sort(function(a, b) {
            const aVal = $(a).find('td').eq(columnIndex).text().trim();
            const bVal = $(b).find('td').eq(columnIndex).text().trim();
            
            // Handle different data types
            if (column === 'updated') {
                // Date comparison
                const aDate = new Date(aVal.split('/').reverse().join('-'));
                const bDate = new Date(bVal.split('/').reverse().join('-'));
                return direction === 'asc' ? aDate - bDate : bDate - aDate;
            } else {
                // String comparison
                const comparison = aVal.localeCompare(bVal);
                return direction === 'asc' ? comparison : -comparison;
            }
        });
        
        tbody.empty().append(rows);
    }

    // ============================
    // Entries Per Page
    // ============================
    
    $('.form-select').filter(function() {
        return $(this).find('option[value="10"]').length > 0;
    }).on('change', function() {
        const entriesPerPage = $(this).val();
        console.log('Entries per page changed to:', entriesPerPage);
        // Implement pagination logic here
    });

    // ============================
    // Report View Modal
    // ============================
    
    // Show report view modal when clicking on report title or ID
    $(document).on('click', '#reportTable tbody td:first-child, #reportTable tbody td:nth-child(2)', function() {
        $('#reportViewModal').modal('show');
    });

    // Print report functionality
    $('#printReport').on('click', function() {
        const reportContent = $('#reportViewModal .modal-body').html();
        const printWindow = window.open('', '_blank');
        printWindow.document.write(`
            <html>
                <head>
                    <title>Print Report</title>
                    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
                    <style>
                        @media print {
                            .btn, .dropdown, .modal-footer { display: none !important; }
                        }
                    </style>
                </head>
                <body>
                    ${reportContent}
                </body>
            </html>
        `);
        printWindow.document.close();
        printWindow.print();
    });

    // Export functionality
    $('#exportDropdown').next('.dropdown-menu').find('a').on('click', function(e) {
        e.preventDefault();
        const format = $(this).text().toLowerCase();
        console.log('Export to:', format);
        
        switch(format) {
            case 'pdf':
                exportToPDF();
                break;
            case 'excel':
                exportToExcel();
                break;
            case 'csv':
                exportToCSV();
                break;
        }
    });

    function exportToPDF() {
        // Implement PDF export
        alert('PDF export functionality would be implemented here');
    }

    function exportToExcel() {
        // Implement Excel export
        alert('Excel export functionality would be implemented here');
    }

    function exportToCSV() {
        // Simple CSV export implementation
        const table = $('#reportViewModal table');
        let csv = [];
        
        // Get headers
        const headers = [];
        table.find('thead tr').each(function() {
            const row = [];
            $(this).find('th').each(function() {
                row.push('"' + $(this).text().replace(/"/g, '""') + '"');
            });
            if (row.length > 0) csv.push(row.join(','));
        });
        
        // Get data rows
        table.find('tbody tr').each(function() {
            const row = [];
            $(this).find('td').each(function() {
                row.push('"' + $(this).text().replace(/"/g, '""') + '"');
            });
            csv.push(row.join(','));
        });
        
        // Download CSV
        const csvContent = csv.join('\n');
        const blob = new Blob([csvContent], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'report.csv';
        a.click();
        window.URL.revokeObjectURL(url);
    }

    // ============================
    // Modify Report Modal
    // ============================
    
    $('#modifyReportBtn, button:contains("Modify Report")').on('click', function() {
        $('#modifyReportModal').modal('show');
    });

    // Handle modify report form submission
    $('#modifyReportModal .btn-primary').on('click', function() {
        const formData = {
            division: $('#modifyDivision').val(),
            section: $('#modifySection').val(),
            unit: $('#modifyUnit').val(),
            reportType: $('#modifyReportType').val(),
            startYear: $('#modifyStartYear').val(),
            endYear: $('#modifyEndYear').val(),
            startMonth: $('#modifyStartMonth').val(),
            endMonth: $('#modifyEndMonth').val()
        };
        
        console.log('Modify report data:', formData);
        
        // Here you would make an AJAX call to save the changes
        /*
        $.ajax({
            url: '/api/reports/modify',
            method: 'PUT',
            data: formData,
            success: function(response) {
                $('#modifyReportModal').modal('hide');
                alert('Report modified successfully');
                location.reload(); // Refresh the page
            },
            error: function(xhr, status, error) {
                alert('Failed to modify report');
            }
        });
        */
        
        $('#modifyReportModal').modal('hide');
        alert('Report modifications saved successfully');
    });

    // ============================
    // Save Report Functionality
    // ============================
    
    $('#saveExisting').on('click', function(e) {
        e.preventDefault();
        console.log('Save existing report');
        alert('Report saved successfully');
    });

    $('#saveNew').on('click', function(e) {
        e.preventDefault();
        console.log('Save as new report');
        const newReportName = prompt('Enter new report name:');
        if (newReportName) {
            alert('New report "' + newReportName + '" saved successfully');
        }
    });

    // ============================
    // Annotation Functionality
    // ============================
    
    $('#annotationDropdown').next('.dropdown-menu').find('a').on('click', function(e) {
        e.preventDefault();
        const action = $(this).text().toLowerCase();
        
        if (action.includes('add')) {
            const note = prompt('Enter your annotation:');
            if (note) {
                console.log('Add annotation:', note);
                alert('Annotation added successfully');
            }
        } else if (action.includes('view')) {
            console.log('View annotations');
            alert('View annotations functionality would be implemented here');
        }
    });

    // ============================
    // Tab Functionality (Active/Removed)
    // ============================
    
    // You can add tab switching functionality here if needed
    function switchTab(tabName) {
        $('.tab-section').addClass('d-none');
        $('#' + tabName + '-section').removeClass('d-none');
    }

    // ============================
    // Utility Functions
    // ============================
    
    // Function to update report table with new data
    function updateReportTable(data) {
        const tbody = $('#reportTable tbody');
        tbody.empty();
        
        data.forEach(function(report) {
            const row = `
                <tr>
                    <td>${report.id}</td>
                    <td>${report.title}</td>
                    <td>${report.subtitle}</td>
                    <td>${report.remark || ''}</td>
                    <td>${report.updated}</td>
                    <td>
                        <div class="d-flex gap-2">
                            <button type="button" class="btn btn-sm btn-warning edit-btn">
                                <i class="bx bx-edit"></i> Edit
                            </button>
                            <button type="button" class="btn btn-sm btn-danger remove-btn">
                                <i class="bx bx-trash"></i> Remove
                            </button>
                        </div>
                    </td>
                </tr>
            `;
            tbody.append(row);
        });
    }

    // Function to validate form data
    function validateForm(formData) {
        const requiredFields = ['division', 'section', 'unit'];
        
        for (let field of requiredFields) {
            if (!formData[field] || formData[field].trim() === '') {
                alert('Please fill in all required fields');
                return false;
            }
        }
        
        return true;
    }

    // Function to show loading state
    function showLoading(element) {
        const originalText = element.text();
        element.data('originalText', originalText);
        element.prop('disabled', true).text('Loading...');
    }

    // Function to hide loading state
    function hideLoading(element) {
        const originalText = element.data('originalText');
        element.prop('disabled', false).text(originalText);
    }

    // ============================
    // Error Handling
    // ============================
    
    // Global error handler for AJAX requests
    $(document).ajaxError(function(event, xhr, settings, error) {
        console.error('AJAX Error:', error);
        alert('An error occurred. Please try again.');
    });

    // ============================
    // Initialization
    // ============================
    
    console.log('KPI Report View JavaScript initialized');
    
    // Any initialization code can go here
    // For example, loading initial data, setting up intervals, etc.
});

// ============================
// Functions that need to be global
// ============================

// Function to manually trigger search (can be called from HTML)
function triggerSearch() {
    $('.btn-primary').filter(function() {
        return $(this).text().trim() === 'Search';
    }).click();
}

// Function to reset all filters
function resetFilters() {
    $('#divisionInput, #sectionInput, #unitInput, #reportTitle, #reportId, #achievement').val('');
    $('#indicator').prop('selectedIndex', 0);
}

 </script>
  @endsection