@extends('layouts/contentNavbarLayout')

@section('title', 'Exports Promotion - Programme Details')

@section('vendor-style')
@vite('resources/assets/vendor/libs/apex-charts/apex-charts.scss')
@endsection

@section('vendor-script')
@vite('resources/assets/vendor/libs/apex-charts/apexcharts.js')
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
@endsection

@section('page-script')
@vite('resources/assets/js/dashboards-analytics.js')
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.10.0/font/bootstrap-icons.min.css" rel="stylesheet">
@endsection

@php
  $breadcrumbs = [
    ['label' => 'Dashboard', 'url' => route('dashboard-analytics')],
    ['label' => 'Exports Promotion', 'url' => route('exporters-development')],
    ['label' => 'Programme Details']
  ];
@endphp

@section('content')

{{-- Page header & breadcrumbs --}}
@include('layouts.partials.page-header', [
  'title' => 'Programme Details',
  'slot' => view('layouts.partials.breadcrumb', compact('breadcrumbs'))
])

@include ('layouts.partials.print-setup')
@section('page-script')
@vite('resources/assets/js/dashboards-analytics.js')

<!-- Feather Icons CDN -->
<script src="https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js"></script>
<script>
  document.addEventListener('DOMContentLoaded', function () {
    feather.replace();
  });
</script>
@endsection
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<br><br>

<style>
  .table th {
    text-transform: capitalize !important;
  }

  @media print {
    .table {
      font-size: 10px !important;
    }

    th, td {
      font-size: 10px !important;
      white-space: normal !important;
    }

    .table-responsive {
      overflow: visible !important;
    }

    .d-print-none {
      display: none !important;
    }

    #printTitle {
      font-size: 16px;
      font-weight: bold;
      text-align: center;
      text-transform: uppercase;
      margin-bottom: 10px;
    }

    @page {
      margin: 15mm;
    }
  }

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

<div class="container-xxxl">
  <div class="card p-4 mb-4 print-section">

    <!-- ✅ Tajuk untuk versi cetakan -->
    <h3 id="printTitle" class="d-none d-print-block"></h3>

    <div class="d-flex justify-content-between align-items-center mb-3">
      <div class="d-print-none">
        <strong>Year From:</strong> 2022 Duration From: Q1 (January - March) ||
        <strong>Year To:</strong> 2022 Duration To: Q4 (October - December)
      </div>
     <div class="d-flex gap-2 no-print">
         <button class="btn btn-info btn-sm" onclick="printPage()"><i data-feather="printer" class="me-2" style="width: 14px; height: 14px;"></i>Print</button>
        <div class="dropdown">
        <button class="btn btn-danger btn-sm dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false"><i data-feather="download" class="me-2" style="width: 14px; height: 14px;"></i>Export</button>
          <ul class="dropdown-menu">
            <li><a class="dropdown-item" href="#"><i class="fas fa-file-excel me-2 text-success"></i>EXCEL</a></li>
            <li><a class="dropdown-item" href="#"><i class="fas fa-file-pdf me-2 text-danger"></i>PDF</a></li>
            <li><a class="dropdown-item" href="#"><i class="fas fa-file-word me-2 text-primary"></i>WORD</a></li>
            <li><a class="dropdown-item" href="#"><i class="fas fa-file-image me-2 text-warning"></i>JPG</a></li>
          </ul>
        </div>
      </div>
    </div>
<div class="table-responsive">
      <table class="table table-bordered table-hover" id="programmeTable">
        <thead class="table-light align-middle text-center">
          <tr>
            <th class="sortable-header" onclick="sortTable('programmeTable', 0, 'number')">
              No
              <i class="bi bi-arrow-down-up sort-icon"></i>
            </th>
            <th class="sortable-header" onclick="sortTable('programmeTable', 1, 'text')">
              Division
              <i class="bi bi-arrow-down-up sort-icon"></i>
            </th>
            <th class="sortable-header" onclick="sortTable('programmeTable', 2, 'text')">
              Section
              <i class="bi bi-arrow-down-up sort-icon"></i>
            </th>
             <th class="sortable-header" onclick="sortTable('programmeTable', 2, 'text')">
              Unit
              <i class="bi bi-arrow-down-up sort-icon"></i>
            </th>
             <th class="sortable-header" onclick="sortTable('programmeTable', 2, 'text')">
              Activity Name
              <i class="bi bi-arrow-down-up sort-icon"></i>
            </th>
             <th class="sortable-header" onclick="sortTable('programmeTable', 2, 'text')">
              Activity Type
              <i class="bi bi-arrow-down-up sort-icon"></i>
            </th>
            <th class="sortable-header" onclick="sortTable('programmeTable', 4, 'text')">
              Programme Type
              <i class="bi bi-arrow-down-up sort-icon"></i>
            </th>
            <th class="sortable-header" onclick="sortTable('programmeTable', 5, 'text')">
              Start Date
              <i class="bi bi-arrow-down-up sort-icon"></i>
            </th>
            <th class="sortable-header" onclick="sortTable('programmeTable', 6, 'text')">
              End Date
              <i class="bi bi-arrow-down-up sort-icon"></i>
            </th>
            <th class="sortable-header" onclick="sortTable('programmeTable', 7, 'number')">
              Total Sales Generated (RM)<br><small>(Potential + Actual)</small>
              <i class="bi bi-arrow-down-up sort-icon"></i>
            </th>
            <th class="sortable-header" onclick="sortTable('programmeTable', 8, 'number')">
              Total Approved Participants
              <i class="bi bi-arrow-down-up sort-icon"></i>
            </th>
          </tr>
        </thead>
        <tbody style="font-size: 16px;">
          @foreach ($result as $key => $field )
            <tr>
                <td class="text-center">{{ $key +1 }}</td>
                <td>{{ $field->division }}</td>
                <td>{{ $field->section }}</td>
                <td>{{ $field->unit }}</td>
                <td>{{ $field->activity_name }}</td>
                <td>{{ $field->activity_type }}</td>
                <td>{{ $field->programme_type }}</td>
                <td>{{ $field->start_date }}</td>
                <td>{{ $field->end_date }}</td>
                <td>{{ $field->total_sales_generated }}</td>
                <td>{{ $field->total_approved_participants }}</td>
            </tr>
          @endforeach
        </tbody>
      </table>
    </div>
  </div>
</div>
  </div>
</div>

<script>
    let sortDirections = {}; // Track sort direction for each column

    function sortTable(tableId, columnIndex, dataType) {
        const table = document.getElementById(tableId);
        const tbody = table.querySelector('tbody');
        const rows = Array.from(tbody.querySelectorAll('tr'));
        const header = table.querySelector(`thead th:nth-child(${columnIndex + 1})`);
        const sortIcon = header.querySelector('.sort-icon');

        // Clear other active sort icons
        table.querySelectorAll('.sort-icon').forEach(icon => {
            if (icon !== sortIcon) {
                icon.classList.remove('active');
                icon.className = 'bi bi-arrow-down-up sort-icon';
            }
        });

        // Determine sort direction
        const sortKey = `${tableId}_${columnIndex}`;
        const currentDirection = sortDirections[sortKey] || 'asc';
        const newDirection = currentDirection === 'asc' ? 'desc' : 'asc';
        sortDirections[sortKey] = newDirection;

        // Update sort icon
        sortIcon.classList.add('active');
        sortIcon.className = newDirection === 'asc' ?
            'bi bi-arrow-up sort-icon active' :
            'bi bi-arrow-down sort-icon active';

        // Sort rows
        rows.sort((a, b) => {
            const aCell = a.cells[columnIndex];
            const bCell = b.cells[columnIndex];

            let aValue = aCell.textContent.trim();
            let bValue = bCell.textContent.trim();

            // Handle status badges - extract text content
            if (aCell.querySelector('.badge')) {
                aValue = aCell.querySelector('.badge').textContent.trim();
            }
            if (bCell.querySelector('.badge')) {
                bValue = bCell.querySelector('.badge').textContent.trim();
            }

            // Convert to appropriate data type
            if (dataType === 'number') {
                // Handle billions (bil) and thousands (k)
                aValue = extractNumber(aValue);
                bValue = extractNumber(bValue);

                if (newDirection === 'asc') {
                    return aValue - bValue;
                } else {
                    return bValue - aValue;
                }
            } else {
                // Text sorting (alphabetical)
                aValue = aValue.toLowerCase();
                bValue = bValue.toLowerCase();

                if (newDirection === 'asc') {
                    return aValue.localeCompare(bValue);
                } else {
                    return bValue.localeCompare(aValue);
                }
            }
        });

        // Clear tbody and re-append sorted rows
        tbody.innerHTML = '';
        rows.forEach(row => tbody.appendChild(row));

        // Add visual feedback
        header.style.backgroundColor = '#e3f2fd';
        setTimeout(() => {
            header.style.backgroundColor = '';
        }, 300);
    }

    function extractNumber(text) {
        // Handle billions (bil) and thousands (k)
        const num = parseFloat(text.replace(/[^\d.]/g, ''));
        if (text.includes('bil')) {
            return num * 1000000000;
        } else if (text.includes('k')) {
            return num * 1000;
        }
        return num || 0;
    }
</script>
@endsection
