@extends('layouts/contentNavbarLayout')

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

@section('content')

@php
  $breadcrumbs = [
    ['label' => 'Dashboard', 'url' => route('dashboard-analytics')],
    ['label' => 'KPI Administration'],
    ['label' => 'Create & Manage Report']
  ];
@endphp

@include('layouts.partials.page-header', [
  'title' => 'Create & Manage Report',
  'slot' => view('layouts.partials.breadcrumb', compact('breadcrumbs'))->render()
])

<br>

<style>
    .dropdown-toggle::after {
        display: none !important;
    }
    .dropdown-toggle {
        background-image: none !important;
    }
</style>

<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('kpiAdmin-edit-report', ['create' => 'true']) }}" class="btn btn-primary">Create Report</a>
  </div>

   <!-- Filter Card -->
        <div class="col-12">
            <div class="card shadow-sm">
                <div class="card-body">
                    <!-- First Row: Division, Section, Unit/Office -->
                    <div class="row g-3 mb-3">
                        <!-- Division Dropdown -->
                        <div class="col-md-4">
                            <label for="division" class="form-label fw-semibold">Division</label>
                            <div class="dropdown">
                                <div class="form-control dropdown-toggle d-flex justify-content-between align-items-center" 
                                     data-bs-toggle="dropdown" aria-expanded="false" style="cursor: pointer; min-height: 38px;">
                                    <div class="selected-items" id="divisionSelected">
                                        <span class="text-muted">All</span>
                                    </div>
                                    <i class="bx bx-chevron-down"></i>
                                </div>
                                <div class="dropdown-menu w-100 p-2" style="max-height: 300px; overflow-y: auto;">
                                    <input type="text" class="form-control mb-2" placeholder="Search divisions..." id="divisionSearch">
                                    <div id="divisionOptions">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="EXPORTS PROMOTION & MARKET ACCESS DIVISION" id="div1">
                                            <label class="form-check-label" for="div1">EXPORTS PROMOTION & MARKET ACCESS DIVISION</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="IMPORTS & STANDARDS DIVISION" id="div2">
                                            <label class="form-check-label" for="div2">IMPORTS & STANDARDS DIVISION</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="INTERNATIONAL TRADE DIVISION" id="div3">
                                            <label class="form-check-label" for="div3">INTERNATIONAL TRADE DIVISION</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="EXPORT DEVELOPMENT DIVISION" id="div4">
                                            <label class="form-check-label" for="div4">EXPORT DEVELOPMENT DIVISION</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="TRADE POLICY DIVISION" id="div5">
                                            <label class="form-check-label" for="div5">TRADE POLICY DIVISION</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="BUSINESS DEVELOPMENT DIVISION" id="div6">
                                            <label class="form-check-label" for="div6">BUSINESS DEVELOPMENT DIVISION</label>
                                        </div>
                                    </div>
                                    <hr>
                                    <button type="button" class="btn btn-sm btn-outline-secondary me-2" onclick="clearSelection('division')">Clear All</button>
                                    <button type="button" class="btn btn-sm btn-primary" onclick="selectAll('division')">Select All</button>
                                </div>
                            </div>
                        </div>

                        <!-- Section Dropdown -->
                        <div class="col-md-4">
                            <label for="section" class="form-label fw-semibold">Section</label>
                            <div class="dropdown">
                                <div class="form-control dropdown-toggle d-flex justify-content-between align-items-center" 
                                     data-bs-toggle="dropdown" aria-expanded="false" style="cursor: pointer; min-height: 38px;">
                                    <div class="selected-items" id="sectionSelected">
                                        <span class="text-muted">All</span>
                                    </div>
                                    <i class="bx bx-chevron-down"></i>
                                </div>
                                <div class="dropdown-menu w-100 p-2" style="max-height: 300px; overflow-y: auto;">
                                    <input type="text" class="form-control mb-2" placeholder="Search sections..." id="sectionSearch">
                                    <div id="sectionOptions">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="CHINA & NORTHEAST ASIA SECTION" id="sec1">
                                            <label class="form-check-label" for="sec1">CHINA & NORTHEAST ASIA SECTION</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="EUROPE SECTION" id="sec2">
                                            <label class="form-check-label" for="sec2">EUROPE SECTION</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="MIDDLE EAST SECTION" id="sec3">
                                            <label class="form-check-label" for="sec3">MIDDLE EAST SECTION</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="ASEAN SECTION" id="sec4">
                                            <label class="form-check-label" for="sec4">ASEAN SECTION</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="AMERICAS SECTION" id="sec5">
                                            <label class="form-check-label" for="sec5">AMERICAS SECTION</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="AFRICA SECTION" id="sec6">
                                            <label class="form-check-label" for="sec6">AFRICA SECTION</label>
                                        </div>
                                    </div>
                                    <hr>
                                    <button type="button" class="btn btn-sm btn-outline-secondary me-2" onclick="clearSelection('section')">Clear All</button>
                                    <button type="button" class="btn btn-sm btn-primary" onclick="selectAll('section')">Select All</button>
                                </div>
                            </div>
                        </div>

                        <!-- Unit/Office Dropdown -->
                        <div class="col-md-4">
                            <label for="unit" class="form-label fw-semibold">Unit/Office</label>
                            <div class="dropdown">
                                <div class="form-control dropdown-toggle d-flex justify-content-between align-items-center" 
                                     data-bs-toggle="dropdown" aria-expanded="false" style="cursor: pointer; min-height: 38px;">
                                    <div class="selected-items" id="unitSelected">
                                        <span class="text-muted">All</span>
                                    </div>
                                    <i class="bx bx-chevron-down"></i>
                                </div>
                                <div class="dropdown-menu w-100 p-2" style="max-height: 300px; overflow-y: auto;">
                                    <input type="text" class="form-control mb-2" placeholder="Search units..." id="unitSearch">
                                    <div id="unitOptions">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="UNIT A - STRATEGIC PLANNING" id="unit1">
                                            <label class="form-check-label" for="unit1">UNIT A - STRATEGIC PLANNING</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="UNIT B - OPERATIONS" id="unit2">
                                            <label class="form-check-label" for="unit2">UNIT B - OPERATIONS</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="UNIT C - RESEARCH & DEVELOPMENT" id="unit3">
                                            <label class="form-check-label" for="unit3">UNIT C - RESEARCH & DEVELOPMENT</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="UNIT D - QUALITY ASSURANCE" id="unit4">
                                            <label class="form-check-label" for="unit4">UNIT D - QUALITY ASSURANCE</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="UNIT E - CUSTOMER RELATIONS" id="unit5">
                                            <label class="form-check-label" for="unit5">UNIT E - CUSTOMER RELATIONS</label>
                                        </div>
                                    </div>
                                    <hr>
                                    <button type="button" class="btn btn-sm btn-outline-secondary me-2" onclick="clearSelection('unit')">Clear All</button>
                                    <button type="button" class="btn btn-sm btn-primary" onclick="selectAll('unit')">Select All</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Second Row: Report Title, Report ID -->
                    <div class="row g-3 mb-3">
                        <div class="col-md-6">
                            <label for="reportTitle" class="form-label fw-semibold">Report Title</label>
                            <input type="text" class="form-control" id="reportTitle" placeholder="">
                        </div>

                        <div class="col-md-6">
                            <label for="reportId" class="form-label fw-semibold">Report ID</label>
                            <input type="text" class="form-control" id="reportId" placeholder="">
                        </div>
                    </div>

                    <!-- Third Row: Indicator and Search Button -->
                    <div class="row g-3">
                        <div class="col-md-8">
                            <label for="indicator" class="form-label fw-semibold">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>

                        <div class="col-md-4 d-flex align-items-end">
                            <button type="button" class="btn btn-primary w-100" onclick="performSearch()">
                                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">No <i class="bx bx-sort"></i></th>
            <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>1</td>
            <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-outline-primary btn-sm" data-bs-toggle="modal" data-bs-target="#editReportModal">
                <i class="bx bx-edit-alt"></i>
            </button>
                <button type="button" class="btn btn-outline btn-danger remove-btn">
                  <i class="bx bx-trash"></i> 
                </button>
              </div>
            </td>
          </tr>
          <tr>
            <td>2</td>
            <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-outline-primary btn-sm" data-bs-toggle="modal" data-bs-target="#editReportModal">
                <i class="bx bx-edit-alt"></i>
            </button>
                <button type="button" class="btn btn-outline btn-danger remove-btn">
                  <i class="bx bx-trash"></i> 
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </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>
        
      </div>
    </div>
  </div>

   <!-- Edit Report Modal -->
        <div class="modal fade" id="editReportModal" tabindex="-1" aria-labelledby="editReportModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-xl">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title fw-bold" id="editReportModalLabel">Edit Report</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form id="editReportForm" method="POST">
                            <!-- Title -->
                            <div class="row mb-4">
                                <div class="col-12">
                                    <label for="editTitle" class="form-label fw-semibold">
                                        Title <span class="text-danger">*</span>
                                    </label>
                                    <input type="text" class="form-control" id="editTitle" name="title" required 
                                           placeholder="Enter report title">
                                </div>
                            </div>

                            <!-- Sub-Title -->
                            <div class="row mb-4">
                                <div class="col-12">
                                    <label for="editSubTitle" class="form-label fw-semibold">
                                        Sub-Title <span class="text-danger">*</span>
                                    </label>
                                    <input type="text" class="form-control" id="editSubTitle" name="sub_title" required 
                                           placeholder="Enter report sub-title">
                                </div>
                            </div>

                            <!-- Report Type / Query Mapping -->
                            <div class="row mb-4">
                                <div class="col-12">
                                    <label for="editReportType" class="form-label fw-semibold">
                                        Report Type / Query Mapping <span class="text-danger">*</span>
                                    </label>
                                    <select class="form-select" id="editReportType" name="report_type" required>
                                        <option value="">Please Select</option>
                                        <option value="performance">Performance Report</option>
                                        <option value="financial">Financial Report</option>
                                        <option value="operational">Operational Report</option>
                                        <option value="strategic">Strategic Report</option>
                                        <option value="compliance">Compliance Report</option>
                                    </select>
                                </div>
                            </div>

                            <!-- Type -->
                            <div class="row mb-4">
                                <div class="col-12">
                                    <label for="editType" class="form-label fw-semibold">
                                        Type <span class="text-danger">*</span>
                                    </label>
                                    <div class="form-control bg-light">Table</div>
                                    <input type="hidden" id="editType" name="type" value="table">
                                </div>
                            </div>

                            <!-- Data Configuration Table -->
                            <div class="row mb-4">
                                <div class="col-12">
                                    <label class="form-label fw-semibold mb-3">Data Configuration</label>
                                    <div class="table-responsive">
                                        <table class="table table-bordered data-config-table" id="editDataTable">
                                            <thead>
                                                <tr class="table-header">
                                                    <th class="data-column">Data</th>
                                                    <th class="use-column">Use</th>
                                                    <th class="direction-column">Direction</th>
                                                    <th class="split-column">Split</th>
                                                    <th class="action-column">Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr class="data-row">
                                                    <td class="data-field">No</td>
                                                    <td class="use-field">
                                                        <input type="checkbox" class="form-check-input" name="data_use[]" value="no" checked>
                                                    </td>
                                                    <td class="direction-field">
                                                        <select class="form-select form-select-sm direction-select" name="data_direction[]">
                                                            <option value="row" selected>Row</option>
                                                            <option value="column">Column</option>
                                                        </select>
                                                    </td>
                                                    <td class="split-field">
                                                        <input type="checkbox" class="form-check-input" name="data_split[]" value="no">
                                                    </td>
                                                    <td class="action-field"></td>
                                                </tr>
                                                <tr class="data-row">
                                                    <td class="data-field">Programme</td>
                                                    <td class="use-field">
                                                        <input type="checkbox" class="form-check-input" name="data_use[]" value="programme" checked>
                                                    </td>
                                                    <td class="direction-field">
                                                        <select class="form-select form-select-sm direction-select" name="data_direction[]">
                                                            <option value="row" selected>Row</option>
                                                            <option value="column">Column</option>
                                                        </select>
                                                    </td>
                                                    <td class="split-field">
                                                        <input type="checkbox" class="form-check-input" name="data_split[]" value="programme" checked>
                                                    </td>
                                                    <td class="action-field"></td>
                                                </tr>
                                                <tr class="data-row">
                                                    <td class="data-field">Exporter Target</td>
                                                    <td class="use-field">
                                                        <input type="checkbox" class="form-check-input" name="data_use[]" value="exporter_target" checked>
                                                    </td>
                                                    <td class="direction-field">
                                                        <select class="form-select form-select-sm direction-select" name="data_direction[]">
                                                            <option value="row" selected>Row</option>
                                                            <option value="column">Column</option>
                                                        </select>
                                                    </td>
                                                    <td class="split-field">
                                                        <input type="checkbox" class="form-check-input" name="data_split[]" value="exporter_target">
                                                    </td>
                                                    <td class="action-field"></td>
                                                </tr>
                                                <tr class="data-row">
                                                    <td class="data-field">Exporter Achievement</td>
                                                    <td class="use-field">
                                                        <input type="checkbox" class="form-check-input" name="data_use[]" value="exporter_achievement">
                                                    </td>
                                                    <td class="direction-field">
                                                        <select class="form-select form-select-sm direction-select" name="data_direction[]">
                                                            <option value="row" selected>Row</option>
                                                            <option value="column">Column</option>
                                                        </select>
                                                    </td>
                                                    <td class="split-field">
                                                        <input type="checkbox" class="form-check-input" name="data_split[]" value="exporter_achievement">
                                                    </td>
                                                    <td class="action-field"></td>
                                                </tr>
                                                <tr class="data-row">
                                                    <td class="data-field">Exporter Performance</td>
                                                    <td class="use-field">
                                                        <input type="checkbox" class="form-check-input" name="data_use[]" value="exporter_performance">
                                                    </td>
                                                    <td class="direction-field">
                                                        <select class="form-select form-select-sm direction-select" name="data_direction[]">
                                                            <option value="row" selected>Row</option>
                                                            <option value="column">Column</option>
                                                        </select>
                                                    </td>
                                                    <td class="split-field">
                                                        <input type="checkbox" class="form-check-input" name="data_split[]" value="exporter_performance">
                                                    </td>
                                                    <td class="action-field"></td>
                                                </tr>
                                                <tr class="data-row">
                                                    <td class="data-field">Activities Performance</td>
                        <td class="use-field">
                          <input type="checkbox" class="form-check-input" name="data_use[]" value="activities_performance">
                        </td>
                        <td class="direction-field">
                          <select class="form-select direction-select" name="data_direction[]">
                            <option value="row" selected>Row</option>
                            <option value="column">Column</option>
                          </select>
                        </td>
                        <td class="split-field">
                          <input type="checkbox" class="form-check-input" name="data_split[]" value="activities_performance">
                        </td>
                        <td class="action-field"></td>
                      </tr>
                      <tr class="data-row">
                        <td class="data-field">Budget Target</td>
                        <td class="use-field">
                          <input type="checkbox" class="form-check-input" name="data_use[]" value="budget_target">
                        </td>
                        <td class="direction-field">
                          <select class="form-select direction-select" name="data_direction[]">
                            <option value="row" selected>Row</option>
                            <option value="column">Column</option>
                          </select>
                        </td>
                        <td class="split-field">
                          <input type="checkbox" class="form-check-input" name="data_split[]" value="budget_target">
                        </td>
                        <td class="action-field"></td>
                      </tr>
                      <tr class="data-row">
                        <td class="data-field">Budget Achievement</td>
                        <td class="use-field">
                          <input type="checkbox" class="form-check-input" name="data_use[]" value="budget_achievement">
                        </td>
                        <td class="direction-field">
                          <select class="form-select direction-select" name="data_direction[]">
                            <option value="row" selected>Row</option>
                            <option value="column">Column</option>
                          </select>
                        </td>
                        <td class="split-field">
                          <input type="checkbox" class="form-check-input" name="data_split[]" value="budget_achievement">
                        </td>
                        <td class="action-field"></td>
                      </tr>
                      <tr class="data-row">
                        <td class="data-field">Budget Performance</td>
                        <td class="use-field">
                          <input type="checkbox" class="form-check-input" name="data_use[]" value="budget_performance">
                        </td>
                        <td class="direction-field">
                          <select class="form-select direction-select" name="data_direction[]">
                            <option value="row" selected>Row</option>
                            <option value="column">Column</option>
                          </select>
                        </td>
                        <td class="split-field">
                          <input type="checkbox" class="form-check-input" name="data_split[]" value="budget_performance">
                        </td>
                        <td class="action-field"></td>
                      </tr>
                    </tbody>
                  </table>
                  <div class="mt-3">
                    <button type="button" class="btn btn-primary" onclick="addCustomDataRow()">
                      <i class="bx bx-plus me-1"></i>Add Custom Data
                    </button>
                  </div>
                </div>
              </div>
            </div>

             <!-- Remark -->
            <div class="row mb-4">
              <div class="col-12">
                <label for="remark" class="form-label fw-semibold">
                  Remark (Optional)
                </label>
                <textarea class="form-control" id="remark" name="remark" rows="4" placeholder="Enter any additional remarks or comments about this report..."></textarea>
              </div>
            </div>

            <div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-success" form="editReportForm">Save</button>
</div>

@endsection

@section('page-script')

<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>
<script>
$(document).ready(function() {
    // 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);
            
            // For demo purposes, just remove the row
            row.fadeOut(300, function() {
                $(this).remove();
            });
        }
    });

    // ============================
    // 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
    });

    // Handle checkbox changes
    $('input[type="checkbox"]').on('change', function() {
        const fieldType = $(this).closest('.dropdown').find('.selected-items').attr('id').replace('Selected', '');
        updateSelectedDisplay(fieldType);
    });

    // Handle search functionality
    $('#divisionSearch').on('keyup', function() {
        filterOptions('division', this.value);
    });
    
    $('#sectionSearch').on('keyup', function() {
        filterOptions('section', this.value);
    });
    
    $('#unitSearch').on('keyup', function() {
        filterOptions('unit', this.value);
    });

    // Prevent dropdown from closing when clicking inside
    $('.dropdown-menu').on('click', function(e) {
        e.stopPropagation();
    });

    // Initialize display for all dropdowns
    updateSelectedDisplay('division');
    updateSelectedDisplay('section');
    updateSelectedDisplay('unit');
}); // Main document ready closing brace

// Function declarations outside of document ready
function getColumnIndex(column) {
    // You'll need to implement this function based on your table structure
    const columnMap = {
        'title': 0,
        'updated': 1,
        'status': 2
        // Add more columns as needed
    };
    return columnMap[column] || -1;
}

function updateSelectedDisplay(fieldType) {
    const selectedContainer = $(`#${fieldType}Selected`);
    const checkboxes = $(`#${fieldType}Options input[type="checkbox"]:checked`);
    
    if (checkboxes.length === 0) {
        selectedContainer.html(`<span class="text-muted">Select ${fieldType}s...</span>`);
    } else {
        let selectedHtml = '';
        checkboxes.each(function() {
            const value = $(this).val();
            const shortValue = value.length > 30 ? value.substring(0, 30) + '...' : value;
            selectedHtml += `<span class="badge bg-primary me-1 mb-1 selected-badge" title="${value}">
                ${shortValue} 
                <span class="remove-btn" onclick="removeSelection('${fieldType}', '${escapeQuotes(value)}')">×</span>
            </span>`;
        });
        selectedContainer.html(selectedHtml);
    }
}

function filterOptions(fieldType, searchTerm) {
    const options = $(`#${fieldType}Options .form-check`);
    
    options.each(function() {
        const label = $(this).find('label').text().toLowerCase();
        if (label.includes(searchTerm.toLowerCase())) {
            $(this).show();
        } else {
            $(this).hide();
        }
    });
}

function removeSelection(fieldType, value) {
    $(`#${fieldType}Options input[value="${value}"]`).prop('checked', false);
    updateSelectedDisplay(fieldType);
}

function clearSelection(fieldType) {
    $(`#${fieldType}Options input[type="checkbox"]`).prop('checked', false);
    updateSelectedDisplay(fieldType);
}

function selectAll(fieldType) {
    $(`#${fieldType}Options input[type="checkbox"]:visible`).prop('checked', true);
    updateSelectedDisplay(fieldType);
}

function escapeQuotes(str) {
    return str.replace(/'/g, "\\'").replace(/"/g, '\\"');
}

// Function to get selected values for search
function getSelectedValues() {
    const selectedData = {
        divisions: [],
        sections: [],
        units: []
    };

    $('#divisionOptions input[type="checkbox"]:checked').each(function() {
        selectedData.divisions.push($(this).val());
    });

    $('#sectionOptions input[type="checkbox"]:checked').each(function() {
        selectedData.sections.push($(this).val());
    });

    $('#unitOptions input[type="checkbox"]:checked').each(function() {
        selectedData.units.push($(this).val());
    });

    return selectedData;
}

function performSearch() {
    const selectedData = getSelectedValues();
    
    // Show results section
    $('#searchResults').show();
    
    // Display selected filters
    let resultHtml = '<h6>Selected Filters:</h6>';
    
    if (selectedData.divisions.length > 0) {
        resultHtml += '<p><strong>Divisions:</strong><br>';
        selectedData.divisions.forEach(div => {
            resultHtml += `<span class="badge bg-info me-1">${div}</span>`;
        });
        resultHtml += '</p>';
    }
    
    if (selectedData.sections.length > 0) {
        resultHtml += '<p><strong>Sections:</strong><br>';
        selectedData.sections.forEach(sec => {
            resultHtml += `<span class="badge bg-warning me-1">${sec}</span>`;
        });
        resultHtml += '</p>';
    }
    
    if (selectedData.units.length > 0) {
        resultHtml += '<p><strong>Units:</strong><br>';
        selectedData.units.forEach(unit => {
            resultHtml += `<span class="badge bg-success me-1">${unit}</span>`;
        });
        resultHtml += '</p>';
    }
    
    if (selectedData.divisions.length === 0 && selectedData.sections.length === 0 && selectedData.units.length === 0) {
        resultHtml += '<p class="text-muted">No filters selected. Showing all results.</p>';
    }
    
    resultHtml += '<hr><p class="text-muted">Search functionality is now working! You can integrate this with your backend search logic.</p>';
    
    $('#resultsContent').html(resultHtml);
    
    // Log the selected data for debugging
    console.log('Selected Data:', selectedData);
}

function resetFilters() {
    // Clear all selections
    clearSelection('division');
    clearSelection('section');
    clearSelection('unit');
    
    // Hide results
    $('#searchResults').hide();
    
    // Clear search inputs
    $('#divisionSearch, #sectionSearch, #unitSearch').val('');
    
    // Show all options
    $('#divisionOptions .form-check, #sectionOptions .form-check, #unitOptions .form-check').show();
}



//modal edit out fx
const editModal = new bootstrap.Modal(document.getElementById('editReportModal'));
document.querySelectorAll('.edit-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        editModal.show();
    });
});
</script>
  @endsection