<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>

<style>
@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&display=swap');

.compliance-container {
    font-family: 'Outfit', sans-serif;
    padding: 1.5rem;
}

/* Page Header Card */
.page-header-card {
    background: linear-gradient(135deg, #1e3a5f 0%, #2d4a6f 100%);
    color: #fff;
    padding: 0.5rem 1rem;
    border-radius: 16px;
    margin-bottom: 1.5rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 1rem;
}

.page-header-card h2 {
    margin: 0;
    font-size: 1.5rem;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 0.75rem;
    color: #fff;
}

.page-header-card h2 i {
    opacity: 0.8;
}

.header-filters {
    display: flex;
    gap: 1rem;
    align-items: center;
    flex-wrap: wrap;
}

.filter-group {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.filter-group label {
    font-size: 0.85rem;
    font-weight: 500;
    opacity: 0.9;
    margin: 0;
}

.filter-group select {
    padding: 0.5rem 1rem;
    border: 1px solid rgba(255,255,255,0.2);
    border-radius: 8px;
    font-size: 0.85rem;
    background: rgba(255,255,255,0.1);
    color: #fff;
    cursor: pointer;
    min-width: 120px;
}

.filter-group select:focus {
    outline: none;
    border-color: rgba(255,255,255,0.4);
    background: rgba(255,255,255,0.15);
}

.filter-group select option {
    background: #1e3a5f;
    color: #fff;
}

/* Summary Cards */
.summary-cards {
    display: grid;
    gap: 1rem;
    margin-bottom: 1.5rem;
}

.summary-card {
    background: #fff;
    display: flex;
    align-items: center;
    gap: 1rem;
}

.summary-card__icon {
    width: 50px;
    height: 50px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.25rem;
}

.summary-card__content h4 {
    margin: 0;
    font-size: 0.8rem;
    color: #64748b;
    font-weight: 500;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.summary-card__content .count {
    font-size: 1.75rem;
    font-weight: 700;
    color: #1e293b;
    line-height: 1.2;
}

/* Main Content Card */
.content-card {
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.05);
    overflow: hidden;
}

.content-card__header {
    padding: 1rem 1.5rem;
    border-bottom: 1px solid #e2e8f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 1rem;
}

.content-card__title {
    font-size: 1rem;
    font-weight: 600;
    color: #1e293b;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.legend {
    display: flex;
    gap: 1.5rem;
    align-items: center;
}

.legend-item {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-size: 0.8rem;
    color: #64748b;
}

.legend-item .swatch {
    width: 20px;
    height: 20px;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.65rem;
}

.legend-item .swatch--compliant {
    background: #d1fae5;
    color: #10b981;
    border: 1px solid #a7f3d0;
}

.legend-item .swatch--pending {
    background: #fef3c7;
    color: #f59e0b;
    border: 1px solid #fcd34d;
}

.legend-item .swatch--overdue {
    background: #fee2e2;
    color: #ef4444;
    border: 1px solid #fca5a5;
}

/* Compliance Table */
.table-responsive {
    overflow-x: auto;
}

.compliance-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 0.85rem;
}

.compliance-table thead {
    background: #f8fafc;
    position: sticky;
    top: 0;
    z-index: 10;
}

.compliance-table th {
    padding: 0.875rem 0.75rem;
    text-align: center;
    font-weight: 600;
    color: #475569;
    font-size: 0.75rem;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    border-bottom: 2px solid #e2e8f0;
    white-space: nowrap;
}

.compliance-table th.col-name {
    text-align: left;
    min-width: 200px;
}

.compliance-table th.col-freq {
    min-width: 100px;
}

.compliance-table th.col-month {
    min-width: 60px;
}

.compliance-table td {
    padding: 0.75rem;
    text-align: center;
    border-bottom: 1px solid #f1f5f9;
    vertical-align: middle;
}

.compliance-table td.col-name {
    text-align: left;
    font-weight: 500;
    color: #1e293b;
}

.compliance-table td.col-freq {
    text-align: center;
}

.compliance-table tbody tr:hover {
    background: #f8fafc;
}

/* Sortable columns */
.compliance-table th.sortable {
    cursor: pointer;
    user-select: none;
    position: relative;
}

.compliance-table th.sortable:hover {
    background: #e2e8f0;
}

.compliance-table th.sortable i.fa-sort {
    margin-left: 5px;
    opacity: 0.4;
}

.compliance-table th.sortable.sort-asc i.fa-sort::before {
    content: "\f0de";
    opacity: 1;
}

.compliance-table th.sortable.sort-desc i.fa-sort::before {
    content: "\f0dd";
    opacity: 1;
}

/* Frequency Badge */
.freq-badge {
    display: inline-block;
    padding: 0.25rem 0.625rem;
    border-radius: 20px;
    font-size: 0.7rem;
    font-weight: 600;
    text-transform: uppercase;
    background: #e0f2fe;
    color: #0369a1;
}

/* Status Badges */
.status-badge {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 28px;
    height: 28px;
    border-radius: 6px;
    font-size: 0.75rem;
    font-weight: 700;
}

.status-badge--compliant {
    background: #d1fae5;
    color: #10b981;
}

.status-badge--pending {
    background: #fef3c7;
    color: #f59e0b;
}

.status-badge--overdue {
    background: #fee2e2;
    color: #ef4444;
}

.status-badge--na {
    background: #f1f5f9;
    color: #94a3b8;
}

/* Merged cells for quarterly/half-yearly/yearly */
.compliance-table td[colspan] {
    padding: 0.875rem;
}

.merged-status {
    display: inline-flex;
    align-items: center;
    gap: 0.375rem;
    padding: 0.375rem 0.75rem;
    border-radius: 6px;
    font-size: 0.75rem;
    font-weight: 600;
}

.merged-status--compliant {
    background: #d1fae5;
    color: #10b981;
}

.merged-status--pending {
    background: #fef3c7;
    color: #f59e0b;
}

.merged-status--overdue {
    background: #fee2e2;
    color: #ef4444;
}

.merged-status--na {
    background: #f1f5f9;
    color: #94a3b8;
    font-weight: 400;
}

/* Empty State */
.empty-state {
    padding: 3rem;
    text-align: center;
    color: #94a3b8;
}

.empty-state i {
    font-size: 3rem;
    margin-bottom: 1rem;
    opacity: 0.5;
}

.empty-state p {
    margin: 0;
    font-size: 0.95rem;
}

/* Column Search Row */
.column-search-row th {
    padding: 0.5rem 0.5rem;
    background: #f1f5f9 !important;
}

.column-search-input {
    width: 100%;
    padding: 0.375rem 0.5rem;
    border: 1px solid #e2e8f0;
    border-radius: 4px;
    font-size: 0.75rem;
    background: #fff;
}

.column-search-input:focus {
    outline: none;
    border-color: #3b82f6;
}

/* Action Buttons */
.btn-action {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.5rem 1rem;
    background: rgba(255,255,255,0.15);
    border: 1px solid rgba(255,255,255,0.3);
    border-radius: 8px;
    color: #fff;
    font-size: 0.85rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s ease;
}

.btn-action:hover {
    background: rgba(255,255,255,0.25);
    border-color: rgba(255,255,255,0.5);
}

/* Print Styles */
@media print {
    .page-header-card,
    .sidebar,
    .topbar,
    .header-filters,
    .column-search-row,
    .btn-action {
        display: none !important;
    }
    
    .compliance-container {
        padding: 0 !important;
    }
    
    .content-card {
        box-shadow: none !important;
        border: 1px solid #e2e8f0;
    }
    
    .summary-cards {
        page-break-after: avoid;
    }
    
    .compliance-table {
        font-size: 11px;
    }
    
    @page {
        margin: 1cm;
        size: landscape;
    }
}

/* Responsive */
@media (max-width: 768px) {
    .page-header-card {
        flex-direction: column;
        text-align: center;
    }
    
    .header-filters {
        width: 100%;
        justify-content: center;
    }
    
    .summary-cards {
        grid-template-columns: repeat(2, 1fr);
    }
}

/* ================= DASHBOARD STYLE SUMMARY CARDS ================= */

.summary-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    gap: 1.2rem;
    margin-bottom: 1.5rem;
}

.summary-card {
    position: relative;
    background: #ffffff;
    border-radius: 16px;
    padding: 18px 22px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;

    /* FULL BORDER */
    border: 2px solid #e5e7eb;   /* light grey outline */
    border-top-width: 6px;       /* thick colored strip */

    box-shadow: 0 6px 14px rgba(0,0,0,0.05);
    transition: all 0.25s ease;
}

.summary-card--view { cursor: default; }

.summary-card__icon {
    width: 52px;
    height: 52px;
    border-radius: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22px;
    transition: all 0.25s ease;
}

.summary-card__content {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.summary-card__content h4 {
    font-size: 14px;
    font-weight: 600;
    margin: 0;
}

.summary-card__content .count {
    padding: 5px 12px;
    border-radius: 999px;
    font-size: 14px;
    font-weight: 700;
}

/* Theme Colors */
.card-pending   { border-top-color: #f59e0b; }
.card-overdue   { border-top-color: #ef4444; }
.card-completed { border-top-color: #10b981; }
.card-upcoming  { border-top-color: #3b82f6; }

.card-pending   .summary-card__icon { background: rgba(245,158,11,0.12); color: #f59e0b; }
.card-overdue   .summary-card__icon { background: rgba(239,68,68,0.12);  color: #ef4444; }
.card-completed .summary-card__icon { background: rgba(16,185,129,0.12); color: #10b981; }
.card-upcoming  .summary-card__icon { background: rgba(59,130,246,0.12); color: #3b82f6; }

.card-pending h4   { color: #b45309; }
.card-pending .count { background: rgba(245,158,11,0.18); color: #b45309; }

.card-overdue h4   { color: #b91c1c; }
.card-overdue .count { background: rgba(239,68,68,0.18); color: #b91c1c; }

.card-completed h4   { color: #047857; }
.card-completed .count { background: rgba(16,185,129,0.18); color: #047857; }

.card-upcoming h4   { color: #1d4ed8; }
.card-upcoming .count { background: rgba(59,130,246,0.18); color: #1d4ed8; }

/* Hover Glow */
.summary-card--view.card-pending:hover   { box-shadow: 0 14px 28px rgba(245,158,11,0.18); transform: translateY(-6px); }
.summary-card--view.card-overdue:hover   { box-shadow: 0 14px 28px rgba(239,68,68,0.18); transform: translateY(-6px); }
.summary-card--view.card-completed:hover { box-shadow: 0 14px 28px rgba(16,185,129,0.18); transform: translateY(-6px); }
.summary-card--view.card-upcoming:hover  { box-shadow: 0 14px 28px rgba(59,130,246,0.18); transform: translateY(-6px); }

.summary-card--view:hover .summary-card__icon {
    transform: translateY(-4px) scale(1.08);
}

.summary-card--view.card-pending:hover {
    border-color: #fcd34d;
    box-shadow: 0 14px 28px rgba(245,158,11,0.18);
    transform: translateY(-6px);
}

.summary-card--view.card-overdue:hover {
    border-color: #fca5a5;
    box-shadow: 0 14px 28px rgba(239,68,68,0.18);
    transform: translateY(-6px);
}

.summary-card--view.card-completed:hover {
    border-color: #6ee7b7;
    box-shadow: 0 14px 28px rgba(16,185,129,0.18);
    transform: translateY(-6px);
}

.summary-card--view.card-upcoming:hover {
    border-color: #93c5fd;
    box-shadow: 0 14px 28px rgba(59,130,246,0.18);
    transform: translateY(-6px);
}

</style>

<?php
// ====================== FISCAL MONTH LOGIC ======================
$fiscalStart = isset($fiscal_start_month) ? (int)$fiscal_start_month : 1;
if ($fiscalStart < 1 || $fiscalStart > 12) {
    $fiscalStart = 1;
}

// Build month order in fiscal sequence
$monthOrder = [];
for ($i = 0; $i < 12; $i++) {
    $m = (($fiscalStart - 1 + $i) % 12) + 1;
    $monthOrder[] = $m;
}

// Build header labels
$months = [];
foreach ($monthOrder as $m) {
    $months[$m] = strtoupper(date('M', mktime(0, 0, 0, $m, 1)));
}

// Check if month is fully compliant
$isFull = function ($cell) {
    return is_array($cell)
        && isset($cell['uploaded'], $cell['total'])
        && (int)$cell['total'] > 0
        && (int)$cell['uploaded'] >= (int)$cell['total'];
};

// Year bounds
$currentYear  = (int) date('Y');
$startYear    = isset($company_start_year) ? (int) $company_start_year : $currentYear;
$selectedYear = isset($year) ? (int) $year : $currentYear;

if ($selectedYear < $startYear) $selectedYear = $startYear;
if ($selectedYear > $currentYear) $selectedYear = $currentYear;

// Get summary stats from dashboard counts (if available)
$currentMonth = (int)date('n');

// Dashboard counts passed from controller
$pendingCount = isset($counts['pending']) ? (int)$counts['pending'] : 0;
$overdueCount = isset($counts['overdue']) ? (int)$counts['overdue'] : 0;
$uploadedCount = isset($counts['uploaded']) ? (int)$counts['uploaded'] : 0;
$upcomingCount = isset($counts['upcoming']) ? (int)$counts['upcoming'] : 0;
?>

<div class="compliance-container content">
    <!-- Page Header -->
    <div class="page-header-card">
        <h2>
            <i class="fa fa-clipboard-check"></i>
            Compliance Status Report
        </h2>
        <div class="header-filters">
            <form method="get" style="display: flex; align-items: center; gap: 1rem;">
                <div class="filter-group">
                    <label for="year">Year:</label>
                    <select name="year" id="year" onchange="this.form.submit()">
                        <?php for ($y = $currentYear; $y >= $startYear; $y--): ?>
                            <option value="<?= $y ?>" <?= ($selectedYear === $y ? 'selected' : '') ?>><?= $y ?></option>
                        <?php endfor; ?>
                    </select>
                </div>
            </form>
            <button type="button" class="btn-action" onclick="resetColumnSearch()" title="Reset Search">
                <i class="fa fa-undo"></i> Reset
            </button>
            <button type="button" class="btn-action" onclick="window.print()" title="Print Report">
                <i class="fa fa-print"></i> Print
            </button>
            <button type="button" class="btn-action" onclick="exportToCSV()" title="Export to CSV">
                <i class="fa fa-download"></i> Export
            </button>
        </div>
    </div>
    
    <!-- Summary Cards - Matching Dashboard Counts -->
    <div class="summary-cards">
        <div class="summary-card summary-card--view card-pending">
            <div class="summary-card__icon">
                <i class="fa fa-clock"></i>
            </div>
            <div class="summary-card__content">
                <h4>Current</h4>
                <div class="count"><?= $pendingCount ?></div>
            </div>
        </div>

        <div class="summary-card summary-card--view card-overdue">
            <div class="summary-card__icon">
                <i class="fa fa-exclamation-triangle"></i>
            </div>
            <div class="summary-card__content">
                <h4>Overdue</h4>
                <div class="count"><?= $overdueCount ?></div>
            </div>
        </div>

        <div class="summary-card summary-card--view card-completed">
            <div class="summary-card__icon">
                <i class="fa fa-check-circle"></i>
            </div>
            <div class="summary-card__content">
                <h4>Completed</h4>
                <div class="count"><?= $uploadedCount ?></div>
            </div>
        </div>
    </div>
    <!-- Main Content Card -->
    <div class="content-card">
        <div class="content-card__header">
            <h3 class="content-card__title">
                <i class="fa fa-table"></i>
                Monthly Compliance Matrix - <?= $selectedYear ?>
            </h3>
            <div class="legend">
                <div class="legend-item">
                    <span class="swatch swatch--pending"><i class="fa fa-clock"></i></span>
                    <span>Current</span>
                </div>
                <div class="legend-item">
                    <span class="swatch swatch--overdue"><i class="fa fa-exclamation-triangle"></i></span>
                    <span>Overdue</span>
                </div>
                <div class="legend-item">
                    <span class="swatch swatch--compliant"><i class="fa fa-check"></i></span>
                    <span>Completed</span>
                </div>
            </div>
        </div>
        
        <div class="table-responsive">
            <table class="compliance-table" id="compliance-table">
                <thead>
                    <tr>
                        <th class="col-name sortable sort-asc" data-sort="name" style="cursor:pointer;">
                            Document Head <i class="fa fa-sort"></i>
                        </th>
                        <th class="col-freq sortable" data-sort="freq" style="cursor:pointer;">
                            Frequency <i class="fa fa-sort"></i>
                        </th>
                        <?php foreach ($months as $m => $code): ?>
                            <th class="col-month"><?= $code ?></th>
                        <?php endforeach; ?>
                        <th style="width:40px; text-align:center;">
                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="resetComplianceTable()" title="Reset Search & Sort" style="border-radius:50%; width:28px; height:28px; padding:0;">
                                <i class="fa fa-undo"></i>
                            </button>
                        </th>
                    </tr>
                    <tr class="column-search-row">
                        <th><input type="text" class="column-search-input" data-column="0" placeholder="Search..."></th>
                        <th><input type="text" class="column-search-input" data-column="1" placeholder="Search..."></th>
                        <?php for ($i = 0; $i < 12; $i++): ?>
                            <th></th>
                        <?php endfor; ?>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($matrix)): ?>
                        <?php foreach ($matrix as $row): ?>
                            <?php $freq = strtolower(trim($row['frequency'] ?? '')); ?>
                            <tr>
                                <td class="col-name"><?= htmlspecialchars($row['name']) ?></td>
                                <td class="col-freq"><span class="freq-badge"><?= htmlspecialchars($row['frequency']) ?></span></td>
                                
                                <?php if ($freq === 'monthly'): ?>
                                    <?php foreach ($monthOrder as $m): ?>
                                        <?php
                                            $cell = $row['months'][$m] ?? null;
                                            $isApplicable = !isset($cell['applicable']) || $cell['applicable'] === true;
                                            $total = (int)($cell['total'] ?? 0);
                                            $uploaded = (int)($cell['uploaded'] ?? 0);
                                            $dueDate = $cell['due_date'] ?? null;

                                            $today = strtotime(date('Y-m-d'));

                                            if (!$isApplicable || $total === 0) {
                                                echo '<td><span class="status-badge status-badge--na">-</span></td>';
                                            }
                                            elseif ($uploaded >= $total) {
                                                echo '<td><span class="status-badge status-badge--compliant"><i class="fa fa-check"></i></span></td>';
                                            }
                                            elseif ($dueDate && $dueDate < $today) {
                                                // 🔴 Due date already passed
                                                echo '<td><span class="status-badge status-badge--overdue"><i class="fa fa-exclamation-triangle"></i></span></td>';
                                            }
                                            elseif ($dueDate && date('Y-m', $dueDate) == date('Y-m')) {
                                                // 🟡 Due this month
                                                echo '<td><span class="status-badge status-badge--pending"><i class="fa fa-clock"></i></span></td>';
                                            }
                                            else {
                                                // ⚪ Future months
                                                echo '<td><span class="status-badge status-badge--na">-</span></td>';
                                            }
                                        ?>
                                    <?php endforeach; ?>

                                <?php elseif ($freq === 'quarterly'): ?>
                                    <?php
                                    // Quarterly: Due months are 3, 6, 9, 12 (Mar, Jun, Sep, Dec)
                                    $quarterDueMonths = [3, 6, 9, 12];
                                    foreach ($monthOrder as $m):
                                        $isDueMonth = in_array($m, $quarterDueMonths);
                                        if (!$isDueMonth):
                                            // Not a due month - show empty cell
                                            echo '<td></td>';
                                        else:
                                            // Due month - check status for this quarter
                                            $cell = $row['months'][$m] ?? null;
                                            $isApplicable = !isset($cell['applicable']) || $cell['applicable'] === true;
                                            $isPast = ($selectedYear < $currentYear) || ($selectedYear == $currentYear && $m < $currentMonth);
                                            $isCurrent = ($selectedYear == $currentYear && $m == $currentMonth);
                                            
                                            if (!$isApplicable):
                                                echo '<td></td>';
                                            elseif ($isFull($cell)):
                                                echo '<td><span class="status-badge status-badge--compliant"><i class="fa fa-check"></i></span></td>';
                                            elseif ($isPast):
                                                echo '<td><span class="status-badge status-badge--overdue"><i class="fa fa-exclamation-triangle"></i></span></td>';
                                            elseif ($isCurrent):
                                                echo '<td><span class="status-badge status-badge--pending"><i class="fa fa-clock"></i></span></td>';
                                            else:
                                                echo '<td></td>';
                                            endif;
                                        endif;
                                    endforeach;
                                    ?>
                                    
                                <?php elseif (in_array($freq, ['half yearly', 'half-yearly', 'half year'])): ?>
                                    <?php
                                    // Half-yearly: Due months are 6 and 12 (Jun, Dec)
                                    $halfDueMonths = [6, 12];
                                    foreach ($monthOrder as $m):
                                        $isDueMonth = in_array($m, $halfDueMonths);
                                        if (!$isDueMonth):
                                            // Not a due month - show empty cell
                                            echo '<td></td>';
                                        else:
                                            // Due month - check status
                                            $cell = $row['months'][$m] ?? null;
                                            $isApplicable = !isset($cell['applicable']) || $cell['applicable'] === true;
                                            $isPast = ($selectedYear < $currentYear) || ($selectedYear == $currentYear && $m < $currentMonth);
                                            $isCurrent = ($selectedYear == $currentYear && $m == $currentMonth);
                                            
                                            if (!$isApplicable):
                                                echo '<td></td>';
                                            elseif ($isFull($cell)):
                                                echo '<td><span class="status-badge status-badge--compliant"><i class="fa fa-check"></i></span></td>';
                                            elseif ($isPast):
                                                echo '<td><span class="status-badge status-badge--overdue"><i class="fa fa-exclamation-triangle"></i></span></td>';
                                            elseif ($isCurrent):
                                                echo '<td><span class="status-badge status-badge--pending"><i class="fa fa-clock"></i></span></td>';
                                            else:
                                                echo '<td></td>';
                                            endif;
                                        endif;
                                    endforeach;
                                    ?>
                                    
                                <?php elseif (in_array($freq, ['yearly', 'annual'])): ?>
                                    <?php
                                    // Yearly: Due month is 12 (December)
                                    $yearDueMonth = 12;
                                    foreach ($monthOrder as $m):
                                        if ($m != $yearDueMonth):
                                            // Not the due month - show empty cell
                                            echo '<td></td>';
                                        else:
                                            // Due month (December) - check status
                                            $cell = $row['months'][$m] ?? null;
                                            $isApplicable = !isset($cell['applicable']) || $cell['applicable'] === true;
                                            $isPast = ($selectedYear < $currentYear) || ($selectedYear == $currentYear && $m < $currentMonth);
                                            $isCurrent = ($selectedYear == $currentYear && $m == $currentMonth);
                                            
                                            if (!$isApplicable):
                                                echo '<td></td>';
                                            elseif ($isFull($cell)):
                                                echo '<td><span class="status-badge status-badge--compliant"><i class="fa fa-check"></i></span></td>';
                                            elseif ($isPast):
                                                echo '<td><span class="status-badge status-badge--overdue"><i class="fa fa-exclamation-triangle"></i></span></td>';
                                            elseif ($isCurrent):
                                                echo '<td><span class="status-badge status-badge--pending"><i class="fa fa-clock"></i></span></td>';
                                            else:
                                                echo '<td></td>';
                                            endif;
                                        endif;
                                    endforeach;
                                    ?>
                                    
                                <?php else: ?>
                                    <!-- Fallback: treat as monthly -->
                                    <?php foreach ($monthOrder as $m): ?>
                                        <?php
                                            $cell = $row['months'][$m] ?? null;
                                            $isApplicable = !isset($cell['applicable']) || $cell['applicable'] === true;
                                            $isPast = ($selectedYear < $currentYear) || ($selectedYear == $currentYear && $m < $currentMonth);
                                            $isCurrent = ($selectedYear == $currentYear && $m == $currentMonth);
                                            
                                            if (!$isApplicable) {
                                                echo '<td><span class="status-badge status-badge--na">-</span></td>';
                                            } elseif ($isFull($cell)) {
                                                echo '<td><span class="status-badge status-badge--compliant"><i class="fa fa-check"></i></span></td>';
                                            } elseif ($isPast) {
                                                echo '<td><span class="status-badge status-badge--overdue"><i class="fa fa-exclamation-triangle"></i></span></td>';
                                            } elseif ($isCurrent) {
                                                echo '<td><span class="status-badge status-badge--pending"><i class="fa fa-clock"></i>EL</span></td>';
                                            } else {
                                                echo '<td><span class="status-badge status-badge--na">-</span></td>';
                                            }
                                        ?>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                                <td></td><!-- Empty cell for reset column -->
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="15">
                                <div class="empty-state">
                                    <i class="fa fa-folder-open"></i>
                                    <p>No data found for <?= $selectedYear ?>.</p>
                                </div>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
// Current sort state
let currentSort = { column: 'name', order: 'asc' };

// Reset both column search and sorting
function resetComplianceTable() {
    // Clear search inputs
    $('#compliance-table .column-search-input').val('');
    $('#compliance-table tbody tr').show();
    
    // Reset sort to default (Document Head A-Z)
    currentSort = { column: 'name', order: 'asc' };
    $('#compliance-table th.sortable').removeClass('sort-asc sort-desc');
    $('#compliance-table th[data-sort="name"]').addClass('sort-asc');
    
    // Re-sort table
    sortComplianceTable(0, 'asc');
}

// Reset column search only (old function for compatibility)
function resetColumnSearch() {
    resetComplianceTable();
}

// Sort compliance table
function sortComplianceTable(colIndex, order) {
    const $tbody = $('#compliance-table tbody');
    const rows = $tbody.find('tr').toArray();
    
    rows.sort(function(a, b) {
        const aText = $(a).find('td').eq(colIndex).text().trim().toLowerCase();
        const bText = $(b).find('td').eq(colIndex).text().trim().toLowerCase();
        
        if (order === 'asc') {
            return aText.localeCompare(bText);
        } else {
            return bText.localeCompare(aText);
        }
    });
    
    $tbody.append(rows);
}

// Column search functionality
$(document).ready(function() {
    // Initialize default sort (Document Head A-Z)
    sortComplianceTable(0, 'asc');
    
    // Column search
    $('#compliance-table .column-search-input').on('keyup change', function() {
        const $inputs = $('#compliance-table .column-search-input');
        const $rows = $('#compliance-table tbody tr');
        
        $rows.each(function() {
            const $row = $(this);
            let show = true;
            
            $inputs.each(function() {
                const col = parseInt($(this).data('column'), 10);
                const searchVal = $(this).val().toLowerCase().trim();
                
                if (searchVal) {
                    const cellText = $row.find('td').eq(col).text().toLowerCase();
                    if (cellText.indexOf(searchVal) === -1) {
                        show = false;
                        return false;
                    }
                }
            });
            
            $row.toggle(show);
        });
    });
    
    // Column header click for sorting
    $('#compliance-table th.sortable').on('click', function() {
        const $th = $(this);
        const sortKey = $th.data('sort');
        const colIndex = $th.index();
        
        // Determine new order
        let newOrder;
        if ($th.hasClass('sort-asc')) {
            newOrder = 'desc';
        } else {
            newOrder = 'asc';
        }
        
        // Update sort indicators
        $('#compliance-table th.sortable').removeClass('sort-asc sort-desc');
        $th.addClass(newOrder === 'asc' ? 'sort-asc' : 'sort-desc');
        
        // Update current sort state
        currentSort = { column: sortKey, order: newOrder };
        
        // Sort the table
        sortComplianceTable(colIndex, newOrder);
    });
});

// Export to CSV functionality
function exportToCSV() {
    const table = document.getElementById('compliance-table');
    const rows = table.querySelectorAll('tbody tr:not(.column-search-row)');
    const headerRow = table.querySelector('thead tr:first-child');
    
    let csv = [];
    
    // Get headers (skip search row)
    let headers = [];
    headerRow.querySelectorAll('th').forEach(th => {
        headers.push('"' + th.textContent.trim().replace(/"/g, '""') + '"');
    });
    csv.push(headers.join(','));
    
    // Get data rows
    rows.forEach(row => {
        if (row.style.display !== 'none') {
            let rowData = [];
            row.querySelectorAll('td').forEach(td => {
                // Get text content, convert status icons to text
                let text = td.textContent.trim();
                if (td.querySelector('.status-badge--compliant, .merged-status--compliant')) {
                    text = 'Compliant';
                } else if (td.querySelector('.status-badge--pending, .merged-status--pending')) {
                    text = 'Pending';
                } else if (td.querySelector('.status-badge--overdue, .merged-status--overdue')) {
                    text = 'Overdue';
                } else if (td.querySelector('.status-badge--na')) {
                    text = 'N/A';
                }
                rowData.push('"' + text.replace(/"/g, '""') + '"');
            });
            csv.push(rowData.join(','));
        }
    });
    
    // Download CSV
    const csvContent = csv.join('\n');
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', 'compliance_status_<?= $selectedYear ?>.csv');
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}
</script>
