@extends('layouts/contentNavbarLayout')
@section('title', 'Query Mapping')
@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()
])
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
<style>
    .sortable-header {
    cursor: pointer;
    position: relative;
    user-select: none;
    padding-right: 25px !important;
}

.sortable-header:hover {
    background-color: #f8f9fa;
}

.sort-icon {
    position: absolute;
    right: 8px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 12px;
    color: #6c757d;
    transition: color 0.2s;
}

.sort-icon.active {
    color: #0d6efd;
}

</style>

 <!-- SEPARATOR -->
        <hr class="my-4" style="border-top: 2px solid #dee2e6;">

    <div class="card">
        <div class="card-body">
            <div class="row mb-3">
                <div class="col-md-6 mb-3">
                    <label for="query-name" class="form-label">Report Name</label>
                    <input type="text" class="form-control" id="query-name" name="query_name">
                </div>
                <div class="col-md-6 mb-3">
                    <label for="query-id" class="form-label">Report ID</label>
                    <input type="text" class="form-control" id="query-id" name="query_id">
                </div>
            </div>
            <div class="row">
                <div class="col text-end">
                    <button type="button" class="btn btn-primary" id="search-btn">Search</button>
                </div>
            </div>
        </div>
    </div>

    <div class="d-flex justify-content-between align-items-center mt-4 mb-3">
        <div class="d-flex align-items-center">
            <span>Show</span>
            <select class="form-select form-select-sm mx-2" id="page-size">
                <option value="10" selected>10</option>
                <option value="25">25</option>
                <option value="50">50</option>
                <option value="100">100</option>
            </select>
            <span>Entries</span>
        </div>
        <div>
            <button type="button" class="btn btn-primary me-2" id="create-query-btn">Create Report</button>
            <button type="button" class="btn btn-primary" id="upload-query-btn">Upload Report</button>
        </div>
    </div>

    <div class="card">
        <div class="table-responsive text-nowrap">
<table class="table table-bordered" id="yourTableId">
               <thead>
    <tr class="table-light">
        <th class="sortable-header" onclick="sortTable('yourTableId', 0, 'number')">
            ID <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th class="sortable-header" onclick="sortTable('yourTableId', 1, 'text')">
            Type <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th class="sortable-header" onclick="sortTable('yourTableId', 2, 'text')">
            Name <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th class="sortable-header" onclick="sortTable('yourTableId', 3, 'text')">
            Remark <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th class="sortable-header" onclick="sortTable('yourTableId', 4, 'text')">
            Updated Date <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th class="sortable-header" onclick="sortTable('yourTableId', 5, 'text')">
            Action <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
    </tr>
</thead>
                <tbody class="table-border-bottom-0">
                    <tr>
                        <td>102</td>
                        <td>Advance</td>
                        <td>PREDEFINED-101: Indicator Information</td>
                        <td></td>
                        <td>31/08/2022</td>
                        <td>
                            <div class="d-flex">
                                <button type="button" class="btn btn-primary btn-sm me-2">Open</button>
                                <button type="button" class="btn btn-danger btn-sm me-2 remove-btn" data-id="102" data-name="PREDEFINED-101: Indicator Information">Remove</button>
                                <button type="button" class="btn btn-primary btn-sm download-btn" data-id="102" data-name="PREDEFINED-101: Indicator Information">Download</button>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>108</td>
                        <td>Advance</td>
                        <td>PREDEFINED-102: Achievement Information</td>
                        <td></td>
                        <td>31/08/2022</td>
                        <td>
                            <div class="d-flex">
                                <button type="button" class="btn btn-primary btn-sm me-2">Open</button>
                                <button type="button" class="btn btn-danger btn-sm me-2 remove-btn" data-id="108" data-name="PREDEFINED-102: Achievement Information">Remove</button>
                                <button type="button" class="btn btn-primary btn-sm download-btn" data-id="108" data-name="PREDEFINED-102: Achievement Information">Download</button>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>110</td>
                        <td>Advance</td>
                        <td>PREDEFINED-103: Achievement Information for Specific Indicator</td>
                        <td></td>
                        <td>31/08/2022</td>
                        <td>
                            <div class="d-flex">
                                <button type="button" class="btn btn-primary btn-sm me-2">Open</button>
                                <button type="button" class="btn btn-danger btn-sm me-2 remove-btn" data-id="110" data-name="PREDEFINED-103: Achievement Information for Specific Indicator">Remove</button>
                                <button type="button" class="btn btn-primary btn-sm download-btn" data-id="110" data-name="PREDEFINED-103: Achievement Information for Specific Indicator">Download</button>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>111</td>
                        <td>Advance</td>
                        <td>PREDEFINED-104: Achievement Information By Search Indicator Name</td>
                        <td></td>
                        <td>31/08/2022</td>
                        <td>
                            <div class="d-flex">
                                <button type="button" class="btn btn-primary btn-sm me-2">Open</button>
                                <button type="button" class="btn btn-danger btn-sm me-2 remove-btn" data-id="111" data-name="PREDEFINED-104: Achievement Information By Search Indicator Name">Remove</button>
                                <button type="button" class="btn btn-primary btn-sm download-btn" data-id="111" data-name="PREDEFINED-104: Achievement Information By Search Indicator Name">Download</button>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>114</td>
                        <td>Advance</td>
                        <td>PREDEFINED-105: Achievement Information With Remark</td>
                        <td></td>
                        <td>31/08/2022</td>
                        <td>
                            <div class="d-flex">
                                <button type="button" class="btn btn-primary btn-sm me-2">Open</button>
                                <button type="button" class="btn btn-danger btn-sm me-2 remove-btn" data-id="114" data-name="PREDEFINED-105: Achievement Information With Remark">Remove</button>
                                <button type="button" class="btn btn-primary btn-sm download-btn" data-id="114" data-name="PREDEFINED-105: Achievement Information With Remark">Download</button>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Upload Query Modal -->
    <div class="modal fade" id="uploadQueryModal" tabindex="-1" aria-labelledby="uploadQueryModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="uploadQueryModalLabel">UPLOAD REPORT</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Please select the mapping file to upload:</p>
                    <div class="mb-3">
                        <input class="form-control" type="file" id="queryMappingFile">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" id="uploadBtn">Upload</button>
                    <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Remove Confirmation Modal -->
    <div class="modal fade" id="removeConfirmModal" tabindex="-1" aria-labelledby="removeConfirmModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="removeConfirmModalLabel">
                        <i class="bx bx-warning text-warning me-2"></i>Confirm Removal
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p class="mb-3">Are you sure you want to remove this report?</p>
                    <div class="alert alert-warning" role="alert">
                        <strong>Report ID:</strong> <span id="removeQueryId"></span><br>
                        <strong>Report Name:</strong> <span id="removeQueryName"></span>
                    </div>
                    <p class="text-muted small">This action cannot be undone.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" id="confirmRemoveBtn">
                        <i class="bx bx-trash me-1"></i>Yes, Remove
                    </button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Download Options Modal -->
    <div class="modal fade" id="downloadOptionsModal" tabindex="-1" aria-labelledby="downloadOptionsModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="downloadOptionsModalLabel">
                        <i class="bx bx-download text-primary me-2"></i>Export Options
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p class="mb-3">Select the format you want to export:</p>
                    <div class="alert alert-info" role="alert">
                        <strong>Report ID:</strong> <span id="downloadQueryId"></span><br>
                        <strong>Report Name:</strong> <span id="downloadQueryName"></span>
                    </div>
                    <div class="row g-3">
                        <div class="col-6">
                            <button type="button" class="btn btn-outline-success w-100 download-format-btn" data-format="excel">
                                <i class="bx bx-file me-2"></i>
                                <div>Excel</div>
                                <small class="text-muted">.xlsx</small>
                            </button>
                        </div>
                        <div class="col-6">
                            <button type="button" class="btn btn-outline-danger w-100 download-format-btn" data-format="pdf">
                                <i class="bx bx-file-blank me-2"></i>
                                <div>PDF</div>
                                <small class="text-muted">.pdf</small>
                            </button>
                        </div>
                        <div class="col-6">
                            <button type="button" class="btn btn-outline-primary w-100 download-format-btn" data-format="word">
                                <i class="bx bx-file me-2"></i>
                                <div>Word</div>
                                <small class="text-muted">.docx</small>
                            </button>
                        </div>
                        <div class="col-6">
                            <button type="button" class="btn btn-outline-warning w-100 download-format-btn" data-format="jpg">
                                <i class="bx bx-image me-2"></i>
                                <div>Image</div>
                                <small class="text-muted">.jpg</small>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>
    
    <div class="d-flex justify-content-between align-items-center mt-3">
        <div>Showing 1 to 10 of 39 Entries</div>
        <div>
            <nav aria-label="Page navigation">
                <ul class="pagination">
                    <li class="page-item prev">
                        <a class="page-link" href="javascript:void(0);"><i class="tf-icon bx bx-chevrons-left"></i></a>
                    </li>
                    <li class="page-item active">
                        <a class="page-link" href="javascript:void(0);">1</a>
                    </li>
                    <li class="page-item">
                        <a class="page-link" href="javascript:void(0);">2</a>
                    </li>
                    <li class="page-item">
                        <a class="page-link" href="javascript:void(0);">3</a>
                    </li>
                    <li class="page-item">
                        <a class="page-link" href="javascript:void(0);">4</a>
                    </li>
                    <li class="page-item next">
                        <a class="page-link" href="javascript:void(0);"><i class="tf-icon bx bx-chevrons-right"></i></a>
                    </li>
                </ul>
            </nav>
        </div>
    </div>

    <!-- New Query Configuration Form -->
    <div class="card mt-4">
        <div class="card-header">
            <h5 class="card-title mb-0">Query Configuration</h5>
        </div>
        <div class="card-body">
            
<!-- Data Source Section -->
<div class="mb-4">
    <h6 class="fw-semibold">Data Source</h6>
    <div class="d-flex gap-4 mt-2">
        <div class="form-check">
            <input class="form-check-input" type="radio" name="dataSource" id="simpleQuery" value="simple">
            <label class="form-check-label" for="simpleQuery">Simple Query *</label>
        </div>
        <div class="form-check">
            <input class="form-check-input" type="radio" name="dataSource" id="advanceQuery" value="advance" checked>
            <label class="form-check-label" for="advanceQuery">Advance Query *</label>
        </div>
    </div>
</div>

<!-- Simple Query Interface - Will be hidden by default -->
<div id="simpleQueryInterface" style="display: none;">
    <!-- Table Name Selection -->
    <div class="mb-4">
        <h6 class="fw-semibold">Table Name *</h6>
        <div class="input-group">
            <select class="form-select" id="tableNameSelect">
                <option value="" selected disabled>Select Table</option>
                <option value="users">Users</option>
                <option value="indicators">Indicators</option>
                <option value="achievements">Achievements</option>
                <option value="reports">Reports</option>
            </select>
            <button class="btn btn-primary" id="joinTableBtn">Join Table</button>
        </div>
    </div>

    <!-- Columns Section -->
    <div class="mb-4">
        <h6 class="fw-semibold">Columns [ For Data ]</h6>
        <div class="table-responsive">
            <table class="table table-bordered">
                <thead class="table-light">
                    <tr>
                        <th>Table</th>
                        <th>Column Name</th>
                        <th>Label</th>
                        <th>Function</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody id="columnsTableBody">
                    <tr class="no-data-row">
                        <td colspan="5" class="text-center">No column has been added</td>
                    </tr>
                </tbody>
            </table>
        </div>
        <button type="button" class="btn btn-primary" id="addColumnBtn">Add Column</button>
    </div>

    <!-- Filter Criteria Section -->
    <div class="mb-4">
        <h6 class="fw-semibold">Filter Criteria</h6>
        <div class="table-responsive">
            <table class="table table-bordered">
                <thead class="table-light">
                    <tr>
                        <th>Table</th>
                        <th>Filter Column</th>
                        <th>Label</th>
                        <th>Logic</th>
                        <th>Type</th>
                        <th>Value</th>
                        <th>Operator</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody id="filtersTableBody">
                    <tr class="no-data-row">
                        <td colspan="8" class="text-center">No column has been added</td>
                    </tr>
                </tbody>
            </table>
        </div>
        <button type="button" class="btn btn-primary" id="addFilterBtn">Add Filter</button>
    </div>
</div>

<!-- Advance Query Interface - Will be shown by default -->
<div id="advanceQueryInterface">
    <!-- Query field with code editor look -->
    <div class="mb-4">
        <label for="advancedQueryText" class="form-label">Query *</label>
        <div class="code-editor-container">
            <pre id="queryEditor" class="p-2 bg-dark text-light" style="min-height: 150px; border-radius: 4px;">1</pre>
        </div>
        <div class="d-flex justify-content-end mt-2">
            <button class="btn btn-primary" id="testQueryBtn">Test Query</button>
        </div>
    </div>

    <!-- Column Labelling Section -->
    <div class="mb-4">
        <h6 class="fw-semibold">Column Labelling</h6>
        <div class="table-responsive">
            <table class="table table-bordered">
                <thead class="table-light">
                    <tr>
                        <th>Column</th>
                        <th>Label</th>
                    </tr>
                </thead>
                <tbody id="columnLabellingBody">
                    <tr class="no-data-row">
                        <td colspan="2" class="text-center">No column available</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Filter Criteria Section -->
    <div class="mb-4">
        <h6 class="fw-semibold">Filter Criteria</h6>
        <div class="table-responsive">
            <table class="table table-bordered">
                <thead class="table-light">
                    <tr>
                        <th>Filter Code</th>
                        <th>Label</th>
                        <th>Type</th>
                        <th>Value</th>
                        <th>Multiple Selection</th>
                    </tr>
                </thead>
                <tbody id="advancedFiltersBody">
                    <tr class="no-data-row">
                        <td colspan="5" class="text-center">No column available</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Reporting Unit Section -->
        <div class="mb-4">
            <h6 class="fw-semibold">Reporting Unit</h6>
            <div class="row mt-2">
                <div class="col-md-4 mb-3">
                    <label for="division" class="form-label">Division *</label>
                    <div class="input-group">
                        <input type="text" class="form-control" id="division" value="Please Select" readonly>
                        <button class="btn btn-outline-secondary dropdown-toggle-no-border" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="bx bx-chevron-down"></i>
                        </button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('division', 'Please Select')">Please Select</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('division', 'CEO\'S Office')">CEO'S Office</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('division', 'Management Services')">Management Services</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('division', 'EXPORTER PROMOTION AND MARKET ACCESS')">EXPORTER PROMOTION AND MARKET ACCESS</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('division', 'Strategic Planning')">Strategic Planning</a></li>
                        </ul>
                    </div>
                </div>
                <div class="col-md-4 mb-3">
                    <label for="section" class="form-label">Section *</label>
                    <div class="input-group">
                        <input type="text" class="form-control" id="section" value="Please Select" readonly>
                        <button class="btn btn-outline-secondary dropdown-toggle-no-border" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="bx bx-chevron-down"></i>
                        </button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('section', 'Please Select')">Please Select</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('section', 'ASEAN & Oceania')">ASEAN & Oceania</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('section', 'Central, West, South Asia & Africa Section')">Central, West, South Asia & Africa Section</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('section', 'China & Northeast Asia')">China & Northeast Asia</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('section', 'Construction & Business Services')">Construction & Business Services</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('section', 'Coordination & Monitoring')">Coordination & Monitoring</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('section', 'Corporate Management')">Corporate Management</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('section', 'Customised Programme')">Customised Programme</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('section', 'Development Assistance')">Development Assistance</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('section', 'Digital Trade')">Digital Trade</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('section', 'Electrical & Electronics, ICT, Machinery & Equipment')">Electrical & Electronics, ICT, Machinery & Equipment</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('section', 'Europe & Americas')">Europe & Americas</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('section', 'Export Academy')">Export Academy</a></li>
                        </ul>
                    </div>
                </div>
                <div class="col-md-4 mb-3">
                    <label for="unit" class="form-label">Unit *</label>
                    <div class="input-group">
                        <input type="text" class="form-control" id="unit" value="Please select" readonly>
                        <button class="btn btn-outline-secondary dropdown-toggle-no-border" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="bx bx-chevron-down"></i>
                        </button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Please select')">Please select</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Account')">Account</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Administration')">Administration</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Application System Management Unit')">Application System Management Unit</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Asset Management')">Asset Management</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Business Information Centre (BIC)')">Business Information Centre (BIC)</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Competency & Talent Development')">Competency & Talent Development</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Corporate Communication')">Corporate Communication</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Digital Services')">Digital Services</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'eCommerce Ecosystem')">eCommerce Ecosystem</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Exporters Advisory & Training (EATU)')">Exporters Advisory & Training (EATU)</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Facility Management')">Facility Management</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Finance')">Finance</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Human Resource Management')">Human Resource Management</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'ICT Operation & Support')">ICT Operation & Support</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Integrity')">Integrity</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Internal Audit')">Internal Audit</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'International Collaboration')">International Collaboration</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Johor')">Johor</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Market Development')">Market Development</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Micro, Small and Medium Enterprises (MSME)')">Micro, Small and Medium Enterprises (MSME)</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Mid Tier')">Mid Tier</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'MO - BUDAPEST')">MO - BUDAPEST</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'MO - BUENOS AIRES')">MO - BUENOS AIRES</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'MO - DOHA')">MO - DOHA</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'MO - HANOI')">MO - HANOI</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'MO - KARACHI')">MO - KARACHI</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'MO - KIEV')">MO - KIEV</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'MO - MEDAN')">MO - MEDAN</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'MO - NAIROBI')">MO - NAIROBI</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'MO - OSAKA')">MO - OSAKA</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'MO - PHNOM PENH')">MO - PHNOM PENH</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'MO - TASHKENT')">MO - TASHKENT</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'MyTRADE Digital')">MyTRADE Digital</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'N/A')">N/A</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Network & ICT Security Unit')">Network & ICT Security Unit</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Organisational Planning & Transformation')">Organisational Planning & Transformation</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Penang')">Penang</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Perfomance Monitoring')">Perfomance Monitoring</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Procurement')">Procurement</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Revenue Generation')">Revenue Generation</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Sabah')">Sabah</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Sarawak')">Sarawak</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Strategic Coordination')">Strategic Coordination</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Strategic Development')">Strategic Development</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - ALMATY')">TC - ALMATY</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - BANGKOK')">TC - BANGKOK</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - BEIJING')">TC - BEIJING</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - CAIRO')">TC - CAIRO</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - CHENGDU')">TC - CHENGDU</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - CHENNAI')">TC - CHENNAI</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - DUBAI')">TC - DUBAI</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - FRANKFURT')">TC - FRANKFURT</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - GUANGZHOU')">TC - GUANGZHOU</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - HO CHI MINH CITY')">TC - HO CHI MINH CITY</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - HONG KONG')">TC - HONG KONG</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - ISTANBUL')">TC - ISTANBUL</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - JAKARTA')">TC - JAKARTA</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - JEDDAH')">TC - JEDDAH</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - JOHANNESBURG')">TC - JOHANNESBURG</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - LAGOS')">TC - LAGOS</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - LONDON')">TC - LONDON</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - LOS ANGELES')">TC - LOS ANGELES</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - MANILA')">TC - MANILA</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - MELBOURNE')">TC - MELBOURNE</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - MEXICO CITY')">TC - MEXICO CITY</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - MIAMI')">TC - MIAMI</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - MILAN')">TC - MILAN</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - MOSCOW')">TC - MOSCOW</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - MUMBAI')">TC - MUMBAI</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - NEW YORK')">TC - NEW YORK</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - PARIS')">TC - PARIS</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - ROTTERDAM')">TC - ROTTERDAM</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - SANTIAGO')">TC - SANTIAGO</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - SAO PAULO')">TC - SAO PAULO</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - SEOUL')">TC - SEOUL</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - SHANGHAI')">TC - SHANGHAI</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - SINGAPORE')">TC - SINGAPORE</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - TAIPEI')">TC - TAIPEI</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - TOKYO')">TC - TOKYO</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - WARSAW')">TC - WARSAW</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'TC - YANGON')">TC - YANGON</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Terengganu')">Terengganu</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Trade Ananlysis')">Trade Ananlysis</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Trade Publication')">Trade Publication</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectOption('unit', 'Trade Statistic')">Trade Statistic</a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
 
<!-- Mapping Information Section -->
<div class="mb-4">
    <h6 class="fw-semibold">Mapping Information</h6>
    <div class="row mt-2">
        <div class="col-12 mb-3">
            <label for="mappingName" class="form-label">Name *</label>
            <input type="text" class="form-control" id="mappingName">
        </div>
        <div class="col-12 mb-3">
            <label for="mappingRemark" class="form-label">Remark</label>
            <textarea class="form-control" id="mappingRemark" rows="5"></textarea>
        </div>
    </div>
</div>

<!-- Form Buttons -->
<div class="d-flex justify-content-end gap-2">
    <button type="button" class="btn btn-primary" id="save-btn">Save</button>
    <button type="button" class="btn btn-secondary" id="reset-btn">Reset</button>
</div>

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

@endsection

@section('page-script')
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Initialize variables for modals
    let currentRemoveId = null;
    let currentDownloadId = null;
    let currentDownloadName = null;
    
    // Initialize Bootstrap modals
    const removeConfirmModal = new bootstrap.Modal(document.getElementById('removeConfirmModal'));
    const downloadOptionsModal = new bootstrap.Modal(document.getElementById('downloadOptionsModal'));
    const uploadQueryModal = new bootstrap.Modal(document.getElementById('uploadQueryModal'));
    
    // Remove button click handlers
    document.querySelectorAll('.remove-btn').forEach(button => {
        button.addEventListener('click', function() {
            const queryId = this.getAttribute('data-id');
            const queryName = this.getAttribute('data-name');
            
            // Set the query information in the modal
            document.getElementById('removeQueryId').textContent = queryId;
            document.getElementById('removeQueryName').textContent = queryName;
            
            // Store the current ID for the actual removal
            currentRemoveId = queryId;
            
            // Show the confirmation modal
            removeConfirmModal.show();
        });
    });
    
    // Confirm remove button handler
    document.getElementById('confirmRemoveBtn').addEventListener('click', function() {
        if (currentRemoveId) {
            // Add your removal logic here
            console.log('Removing query with ID:', currentRemoveId);
            
        
            
            // For demonstration, we'll just show an alert
            alert(`Query mapping with ID ${currentRemoveId} has been removed successfully!`);
            
            // Hide the modal
            removeConfirmModal.hide();
            
            // Reset the current ID
            currentRemoveId = null;
        }
    });
    
    // Download button click handlers
    document.querySelectorAll('.download-btn').forEach(button => {
        button.addEventListener('click', function() {
            const queryId = this.getAttribute('data-id');
            const queryName = this.getAttribute('data-name');
            
            // Set the query information in the modal
            document.getElementById('downloadQueryId').textContent = queryId;
            document.getElementById('downloadQueryName').textContent = queryName;
            
            // Store the current info for the actual download
            currentDownloadId = queryId;
            currentDownloadName = queryName;
            
            // Show the download options modal
            downloadOptionsModal.show();
        });
    });
    
    // Download format button handlers
    document.querySelectorAll('.download-format-btn').forEach(button => {
        button.addEventListener('click', function() {
            const format = this.getAttribute('data-format');
            
            if (currentDownloadId && currentDownloadName) {
                // Add your download logic here
                console.log(`Downloading query ${currentDownloadId} in ${format} format`);
                
                // For demonstration, we'll show an alert
                alert(`Downloading "${currentDownloadName}" in ${format.toUpperCase()} format...`);
                
                // Hide the modal
                downloadOptionsModal.hide();
                
                // Reset the current info
                currentDownloadId = null;
                currentDownloadName = null;
            }
        });
    });
    
    // Initialize radio button event handlers for toggling between Simple and Advance Query
    const simpleQueryRadio = document.getElementById('simpleQuery');
    const advanceQueryRadio = document.getElementById('advanceQuery');
    const simpleQueryInterface = document.getElementById('simpleQueryInterface');
    const advanceQueryInterface = document.getElementById('advanceQueryInterface');
    
    // Function to toggle between Simple and Advance Query interfaces
    function toggleQueryInterface() {
        if (simpleQueryRadio.checked) {
            simpleQueryInterface.style.display = 'block';
            advanceQueryInterface.style.display = 'none';
        } else {
            simpleQueryInterface.style.display = 'none';
            advanceQueryInterface.style.display = 'block';
        }
    }
    
    // Add event listeners to radio buttons
    simpleQueryRadio.addEventListener('change', toggleQueryInterface);
    advanceQueryRadio.addEventListener('change', toggleQueryInterface);
    
    // Initialize interface on page load
    toggleQueryInterface();
    
    // Example event listeners for search and query buttons
    document.getElementById('search-btn')?.addEventListener('click', function() {
        // Search functionality
        console.log('Search button clicked');
    });
    
    document.getElementById('create-query-btn')?.addEventListener('click', function() {
        // Create query functionality
        console.log('Create Query button clicked');
    });
    
    document.getElementById('upload-query-btn')?.addEventListener('click', function() {
        // Show upload modal
        uploadQueryModal.show();
    });
    
    // Test Query button for advanced interface
    document.getElementById('testQueryBtn')?.addEventListener('click', function() {
        console.log('Test Query button clicked');
        // Add functionality to test the query
    });
    
    // Query configuration form buttons
    document.getElementById('save-btn')?.addEventListener('click', function() {
        console.log('Save button clicked');
    });
    
    document.getElementById('reset-btn')?.addEventListener('click', function() {
        console.log('Reset button clicked');
    });
    
    // Function to handle dropdown item selection
    function setupDropdownSelection(inputId) {
        const dropdownItems = document.querySelectorAll(`#${inputId} + button + .dropdown-menu .dropdown-item`);
        const inputField = document.getElementById(inputId);
        
        dropdownItems.forEach(item => {
            item.addEventListener('click', function(e) {
                e.preventDefault();
                
                // Remove active class from all items
                dropdownItems.forEach(el => el.classList.remove('active'));
                
                // Add active class to clicked item
                this.classList.add('active');
                
                // Update input field value
                inputField.value = this.textContent;
            });
        });
    }
    
    // Set up for each dropdown
    setupDropdownSelection('division');
    setupDropdownSelection('section');
    setupDropdownSelection('unit');
    
    // Add event listeners for "Add Column" and "Add Filter" buttons if they exist
    document.getElementById('addColumnBtn')?.addEventListener('click', function() {
        console.log('Add Column button clicked');
        // Add your code to add a new column row
    });
    
    document.getElementById('addFilterBtn')?.addEventListener('click', function() {
        console.log('Add Filter button clicked');
        // Add your code to add a new filter row
    });
    
    document.getElementById('joinTableBtn')?.addEventListener('click', function() {
        console.log('Join Table button clicked');
        // Add your code for joining tables
    });
    
    // Handle file upload
    const uploadBtn = document.getElementById('uploadBtn');
    uploadBtn?.addEventListener('click', function() {
        const fileInput = document.getElementById('queryMappingFile');
        const file = fileInput.files[0];
        
        if (file) {
            // Create FormData object to send file
            const formData = new FormData();
            formData.append('query_file', file);
            
            // Add CSRF token for Laravel if available
            const csrfToken = document.querySelector('meta[name="csrf-token"]');
            if (csrfToken) {
                formData.append('_token', csrfToken.getAttribute('content'));
            }
            
            // Send file to server using fetch API
            fetch('/upload-query-mapping', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Show success message and refresh the page or update the table
                    alert('File uploaded successfully!');
                    location.reload();
                } else {
                    // Show error message
                    alert('Error uploading file: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred while uploading the file.');
            })
            .finally(() => {
                // Hide modal after upload attempt
                uploadQueryModal.hide();
            });
        } else {
            alert('Please select a file to upload.');
        }
    });
});

function sortTable(tableId, column, type) {
    const table = document.getElementById(tableId);
    const tbody = table.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));
    const header = table.querySelectorAll('th')[column];
    const sortIcon = header.querySelector('.sort-icon');
    
    // Determine current sort direction
    let isAscending = true;
    if (sortIcon.classList.contains('active')) {
        isAscending = !sortIcon.classList.contains('desc');
    }
    
    // Clear all active sort icons
    table.querySelectorAll('.sort-icon').forEach(icon => {
        icon.classList.remove('active', 'desc');
    });
    
    // Set current sort icon as active
    sortIcon.classList.add('active');
    if (!isAscending) {
        sortIcon.classList.add('desc');
    }
    
    // Sort rows based on column and type
    rows.sort((a, b) => {
        let aValue = a.cells[column].textContent.trim();
        let bValue = b.cells[column].textContent.trim();
        
        // Handle different data types
        switch(type) {
            case 'number':
                aValue = parseFloat(aValue) || 0;
                bValue = parseFloat(bValue) || 0;
                break;
            case 'date':
                // Handle date format DD/MM/YYYY
                aValue = new Date(aValue.split('/').reverse().join('-'));
                bValue = new Date(bValue.split('/').reverse().join('-'));
                break;
            case 'text':
            default:
                aValue = aValue.toLowerCase();
                bValue = bValue.toLowerCase();
                break;
        }
        
        // Compare values
        if (aValue < bValue) return isAscending ? -1 : 1;
        if (aValue > bValue) return isAscending ? 1 : -1;
        return 0;
    });
    
    // Re-append sorted rows to tbody
    rows.forEach(row => tbody.appendChild(row));
}
function sortTable(tableId, column, type) {
    const table = document.getElementById(tableId);
    const tbody = table.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));
    const header = table.querySelectorAll('th')[column];
    const sortIcon = header.querySelector('.sort-icon');
    
    // Determine current sort direction
    let isAscending = true;
    if (sortIcon.classList.contains('active')) {
        isAscending = !sortIcon.classList.contains('desc');
    }
    
    // Clear all active sort icons
    table.querySelectorAll('.sort-icon').forEach(icon => {
        icon.classList.remove('active', 'desc');
    });
    
    // Set current sort icon as active
    sortIcon.classList.add('active');
    if (!isAscending) {
        sortIcon.classList.add('desc');
    }
    
    // Sort rows based on column and type
    rows.sort((a, b) => {
        let aValue = a.cells[column].textContent.trim();
        let bValue = b.cells[column].textContent.trim();
        
        // Handle different data types
        switch(type) {
            case 'number':
                aValue = parseFloat(aValue) || 0;
                bValue = parseFloat(bValue) || 0;
                break;
            case 'date':
                // Handle date format DD/MM/YYYY
                aValue = new Date(aValue.split('/').reverse().join('-'));
                bValue = new Date(bValue.split('/').reverse().join('-'));
                break;
            case 'text':
            default:
                aValue = aValue.toLowerCase();
                bValue = bValue.toLowerCase();
                break;
        }
        
        // Compare values
        if (aValue < bValue) return isAscending ? -1 : 1;
        if (aValue > bValue) return isAscending ? 1 : -1;
        return 0;
    });
    
    // Re-append sorted rows to tbody
    rows.forEach(row => tbody.appendChild(row));
}
</script>
@endsection