<?php
/* ====================================================
SAFETY TALK SYSTEM - PT CITRA LAMPIA MANDIRI
File        : rekap.php
Versi       : 2.5.0 (Attendance Metrics + Progress Bar)
Tanggal     : 20-02-2026
Fitur       : - ✅ Kolom "Peserta Seharusnya" (index 8)
              - ✅ Progress Bar Persentase Kehadiran
              - ✅ Color Coding: <50% merah, 50-79% kuning, ≥80% hijau
              - ✅ Backward Compatible dengan data lama
              - ✅ Export CSV termasuk kolom baru
====================================================
*/

// ===== KONFIGURASI GLOBAL =====
define('APP_VERSION', '2.5.0');

// ===== AUTH & SECURITY CHECK =====
date_default_timezone_set('Asia/Jakarta');

if(session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Cek login
if(!isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

// Session timeout: 30 minutes inactivity
if(isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > 1800)) {
    session_unset();
    session_destroy();
    header('Location: login.php?timeout=1');
    exit;
}
$_SESSION['last_activity'] = time();

// ===== CONFIGURATION =====
$itemsPerPage = 10;

// ===== GET FILTER PARAMETERS (Sanitized) =====
$f_start  = isset($_GET['start']) ? preg_replace('/[^\d\-]/', '', $_GET['start']) : '';
$f_end    = isset($_GET['end']) ? preg_replace('/[^\d\-]/', '', $_GET['end']) : '';
$f_divisi = isset($_GET['divisi']) ? trim($_GET['divisi']) : '';
$f_search = isset($_GET['search']) ? trim($_GET['search']) : '';
$page     = max(1, (int)($_GET['page'] ?? 1));

// ===== LOAD & FILTER DATA =====
$listData = [];
$csvPath = __DIR__ . '/data/safety_talk.csv';

if(file_exists($csvPath) && is_readable($csvPath)) {
    $file = fopen($csvPath, 'r');
    if($file !== FALSE) {
        $rowIndex = 0;
        while(($row = fgetcsv($file, 1000, ",")) !== FALSE) { 
            // ✅ Validasi minimal 9 kolom (data lama) atau 10 kolom (data baru)
            if(!is_array($row) || count($row) < 9) { $rowIndex++; continue; }
            
            $tanggal = trim($row[0] ?? '');
            if(empty($tanggal)) { $rowIndex++; continue; }

            $pass = true;
            if($f_start && $tanggal < $f_start) $pass = false;
            if($f_end && $tanggal > $f_end) $pass = false;
            
            $divisi = trim($row[3] ?? '');
            if($f_divisi && $divisi !== $f_divisi) $pass = false;
            
            if($f_search) {
                $searchStr = (trim($row[4] ?? '')) . " " . (trim($row[6] ?? ''));
                if(stripos($searchStr, $f_search) === false) $pass = false;
            }

            if($pass) {
                $row['db_id'] = $rowIndex;
                $listData[] = $row; 
            }
            $rowIndex++;
        }
        fclose($file);
    }
}

// ===== PAGINATION LOGIC =====
$totalItems = count($listData);
$totalPages = max(1, ceil($totalItems / $itemsPerPage));
$page = min($page, $totalPages);
$offset = ($page - 1) * $itemsPerPage;

$displayStart = $totalItems > 0 ? $offset + 1 : 0;
$displayEnd = min($offset + $itemsPerPage, $totalItems);
$paginatedData = $totalItems > 0 ? array_slice(array_reverse($listData), $offset, $itemsPerPage) : [];

// ===== BUILD QUERY STRING =====
function buildQuery($params = []) {
    $query = array_filter([
        'start' => $_GET['start'] ?? '',
        'end' => $_GET['end'] ?? '',
        'divisi' => $_GET['divisi'] ?? '',
        'search' => $_GET['search'] ?? '',
    ], fn($v) => $v !== '' && $v !== null);
    $query = array_merge($query, $params);
    return http_build_query(array_filter($query));
}

// ===== HELPER FUNCTIONS =====
function formatDateDisplay($date) {
    return $date && strtotime($date) ? date('d M Y', strtotime($date)) : '-';
}

function generatePagination($currentPage, $totalPages, $maxVisible = 5) {
    $pages = [];
    if ($totalPages <= 1) return $pages;
    
    if ($currentPage > $maxVisible + 1) {
        $pages[] = ['label' => '1', 'page' => 1];
        if ($currentPage > $maxVisible + 2) $pages[] = ['label' => '...', 'page' => null];
    }
    
    $start = max(2, $currentPage - floor($maxVisible / 2));
    $end = min($totalPages - 1, $currentPage + floor($maxVisible / 2));
    
    if ($currentPage - floor($maxVisible / 2) < 2) $end = min($totalPages - 1, $maxVisible + 1);
    if ($currentPage + floor($maxVisible / 2) > $totalPages - 1) $start = max(2, $totalPages - $maxVisible);
    
    for ($i = $start; $i <= $end; $i++) $pages[] = ['label' => (string)$i, 'page' => $i];
    
    if ($currentPage < $totalPages - $maxVisible) {
        if ($currentPage < $totalPages - $maxVisible - 1) $pages[] = ['label' => '...', 'page' => null];
        $pages[] = ['label' => (string)$totalPages, 'page' => $totalPages];
    }
    return $pages;
}

// ✅ Helper: Hitung persentase & kelas warna progress bar
function getAttendanceBar(int $hadir, int $seharusnya): array {
    if($seharusnya <= 0) return ['percent' => 0, 'class' => 'low', 'label' => '0%'];
    $percent = min(100, max(0, ($hadir / $seharusnya) * 100));
    $class = match(true) {
        $percent >= 80 => 'high',
        $percent >= 50 => 'medium',
        default => 'low'
    };
    return [
        'percent' => round($percent, 1),
        'class' => $class,
        'label' => round($percent) . '%'
    ];
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rekap Safety Talk v<?= APP_VERSION ?> | PT Citra Lampia Mandiri</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="icon" type="image/x-icon" href="assets/img/clm_logo3.png">
    <style>
        :root {
            --primary: #1e40af; --primary-dark: #1e3a8a; --secondary: #0f766e;
            --accent: #f59e0b; --success: #059669; --danger: #dc2626;
            --gray-50: #f8fafc; --gray-100: #f1f5f9; --gray-200: #e2e8f0;
            --gray-300: #cbd5e1; --gray-500: #64748b; --gray-700: #334155; --gray-900: #0f172a;
            --shadow-sm: 0 1px 2px rgba(0,0,0,0.05);
            --shadow-md: 0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -1px rgba(0,0,0,0.06);
            --shadow-lg: 0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -2px rgba(0,0,0,0.05);
            --radius: 8px; --radius-lg: 12px; --transition: all 0.2s ease;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: 'Inter', system-ui, -apple-system, sans-serif; padding: 24px; font-size: 13px; background: var(--gray-50); color: var(--gray-900); line-height: 1.5; }
        .page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding-bottom: 16px; border-bottom: 2px solid var(--primary); flex-wrap: wrap; gap: 12px; }
        .page-title { display: flex; align-items: center; gap: 12px; }
        .page-title i { font-size: 20px; color: var(--primary); }
        .page-title h1 { font-size: 18px; font-weight: 700; color: var(--gray-900); }
        .page-title small { display: block; font-size: 11px; color: var(--gray-500); font-weight: 400; margin-top: 2px; }
        .back-link { display: inline-flex; align-items: center; gap: 6px; text-decoration: none; color: var(--primary); font-weight: 600; font-size: 12px; padding: 8px 14px; background: white; border-radius: var(--radius); box-shadow: var(--shadow-sm); transition: var(--transition); }
        .back-link:hover { background: var(--primary); color: white; transform: translateX(-2px); }
        .filter-card { background: white; padding: 20px; border-radius: var(--radius-lg); border: 1px solid var(--gray-200); display: flex; flex-wrap: wrap; gap: 16px; align-items: flex-end; box-shadow: var(--shadow-md); margin-bottom: 20px; }
        .filter-group { display: flex; flex-direction: column; gap: 6px; min-width: 140px; flex: 1; max-width: 180px; }
        .filter-group label { font-weight: 600; font-size: 11px; color: var(--gray-700); text-transform: uppercase; letter-spacing: 0.3px; }
        .filter-group input, .filter-group select { padding: 10px 12px; border: 1px solid var(--gray-300); border-radius: 6px; font-size: 13px; background: var(--gray-50); transition: var(--transition); }
        .filter-group input:focus, .filter-group select:focus { outline: none; border-color: var(--primary); background: white; box-shadow: 0 0 0 3px rgba(30, 64, 175, 0.1); }
        .btn { padding: 10px 16px; border-radius: 6px; font-weight: 600; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; text-decoration: none; border: none; transition: var(--transition); font-size: 12px; white-space: nowrap; }
        .btn i { font-size: 11px; }
        .btn-filter { background: var(--primary); color: white; }
        .btn-filter:hover { background: var(--primary-dark); transform: translateY(-1px); box-shadow: var(--shadow-sm); }
        .btn-export { background: var(--success); color: white; }
        .btn-export:hover { background: #047857; transform: translateY(-1px); box-shadow: var(--shadow-sm); }
        .btn-print { background: var(--secondary); color: white; }
        .btn-print:hover { background: #0d9488; transform: translateY(-1px); box-shadow: var(--shadow-sm); }
        .btn-reset { background: var(--gray-200); color: var(--gray-700); }
        .btn-reset:hover { background: var(--gray-300); transform: translateY(-1px); }
        .btn-edit { background: var(--accent); color: white; padding: 6px 12px; font-size: 11px; border-radius: 5px; }
        .btn-edit:hover { background: #d97706; transform: translateY(-1px); }
        .btn-page { background: white; color: var(--gray-700); border: 1px solid var(--gray-300); min-width: 36px; justify-content: center; padding: 8px 12px; }
        .btn-page:hover, .btn-page.active { background: var(--primary); color: white; border-color: var(--primary); }
        .btn-page:disabled { opacity: 0.5; cursor: not-allowed; transform: none !important; }
        .filter-actions { display: flex; gap: 10px; margin-left: auto; flex-wrap: wrap; }
        .corporate-header { background: white; width: 100%; border: 2px solid var(--gray-900); display: flex; margin-bottom: 20px; border-radius: var(--radius); overflow: hidden; box-shadow: var(--shadow-sm); }
        .logo-sec { width: 40%; padding: 16px 20px; border-right: 2px solid var(--gray-900); background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%); color: white; }
        .logo-sec strong { font-size: 15px; font-weight: 700; display: block; line-height: 1.3; }
        .logo-sec small { font-weight: 400; font-size: 11px; opacity: 0.9; display: block; margin-top: 4px; }
        .info-sec { width: 60%; padding: 8px; }
        .p-box { padding: 10px; text-align: center; font-weight: 700; font-size: 14px; border-bottom: 2px solid var(--gray-900); background: var(--gray-100); text-transform: uppercase; letter-spacing: 0.5px; }
        .d-box { padding: 12px; text-align: center; font-weight: 600; font-size: 12px; background: white; color: var(--gray-700); }
        .table-container { background: white; border-radius: var(--radius-lg); border: 1px solid var(--gray-200); box-shadow: var(--shadow-md); overflow: hidden; }
        .table-wrapper { overflow-x: auto; -webkit-overflow-scrolling: touch; }
        table { width: 100%; border-collapse: collapse; font-size: 12px; }
        thead { background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%); color: white; position: sticky; top: 0; z-index: 10; }
        th { padding: 14px 12px; text-align: center; font-weight: 600; text-transform: uppercase; font-size: 11px; letter-spacing: 0.3px; border-bottom: 2px solid rgba(255,255,255,0.2); white-space: nowrap; }
        td { border-bottom: 1px solid var(--gray-200); padding: 12px 12px; text-align: center; vertical-align: middle; transition: background 0.15s ease; }
        tbody tr:hover { background: var(--gray-50); }
        tbody tr:nth-child(even) { background: #fafafa; }
        tbody tr:nth-child(even):hover { background: #f1f5f9; }
        .text-left { text-align: left !important; }
        .font-semibold { font-weight: 600; }
        .text-muted { color: var(--gray-500); font-size: 11px; }
        .badge { display: inline-block; padding: 3px 10px; border-radius: 20px; font-size: 10px; font-weight: 600; background: var(--gray-200); color: var(--gray-700); }
        .badge-hs { background: #dbeafe; color: #1e40af; }
        .badge-ef { background: #d1fae5; color: #065f46; }
        .badge-qms { background: #fef3c7; color: #92400e; }
        .photo-gallery { display: flex; gap: 6px; justify-content: center; flex-wrap: wrap; }
        .img-thumb { width: 50px; height: 40px; object-fit: cover; border: 2px solid var(--gray-200); border-radius: 4px; cursor: zoom-in; transition: var(--transition); box-shadow: var(--shadow-sm); }
        .img-thumb:hover { border-color: var(--primary); transform: scale(1.08); box-shadow: var(--shadow-md); z-index: 2; }
        .photo-placeholder { color: var(--gray-500); font-size: 11px; font-style: italic; }
        
        /* ===== ATTENDANCE PROGRESS BAR ===== */
        .attendance-cell { min-width: 110px; }
        .attendance-bar {
            width: 100px;
            height: 20px;
            background: var(--gray-200);
            border-radius: 10px;
            overflow: hidden;
            position: relative;
            margin: 0 auto;
            box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
        }
        .attendance-fill {
            height: 100%;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: width 0.3s ease;
            position: relative;
        }
        .attendance-fill.low { background: linear-gradient(90deg, var(--danger), #ef4444); }
        .attendance-fill.medium { background: linear-gradient(90deg, var(--warning), #f97316); }
        .attendance-fill.high { background: linear-gradient(90deg, var(--success), #10b981); }
        .attendance-text {
            color: white;
            font-size: 10px;
            font-weight: 700;
            text-shadow: 0 1px 2px rgba(0,0,0,0.3);
            white-space: nowrap;
            z-index: 1;
        }
        .attendance-ratio {
            font-size: 10px;
            color: var(--gray-500);
            margin-top: 4px;
            display: block;
        }
        
        .pagination-wrapper { display: flex; justify-content: space-between; align-items: center; padding: 16px 20px; background: var(--gray-50); border-top: 1px solid var(--gray-200); flex-wrap: wrap; gap: 12px; }
        .pagination-info { font-size: 12px; color: var(--gray-700); }
        .pagination-info strong { color: var(--primary); }
        .pagination-controls { display: flex; gap: 4px; align-items: center; }
        .pagination-ellipsis { padding: 8px 4px; color: var(--gray-500); font-size: 12px; }
        .per-page-selector { display: flex; align-items: center; gap: 8px; font-size: 12px; color: var(--gray-700); }
        .per-page-selector select { padding: 6px 10px; border: 1px solid var(--gray-300); border-radius: 4px; font-size: 11px; background: white; cursor: pointer; }
        #imgModal { display: none; position: fixed; z-index: 9999; top: 0; left: 0; width: 100%; height: 100%; background: rgba(15, 23, 42, 0.95); justify-content: center; align-items: center; backdrop-filter: blur(4px); animation: fadeIn 0.2s ease; }
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        #imgModal img { max-width: 95%; max-height: 90vh; border: 4px solid white; border-radius: 8px; box-shadow: 0 25px 50px -12px rgba(0,0,0,0.5); animation: zoomIn 0.3s ease; }
        @keyframes zoomIn { from { transform: scale(0.95); opacity: 0; } to { transform: scale(1); opacity: 1; } }
        #imgModal .close { position: absolute; top: 24px; right: 32px; color: white; font-size: 36px; cursor: pointer; width: 44px; height: 44px; border-radius: 50%; display: flex; align-items: center; justify-content: center; transition: var(--transition); background: rgba(255,255,255,0.15); }
        #imgModal .close:hover { background: rgba(255,255,255,0.25); transform: rotate(90deg); }
        .modal-caption { position: absolute; bottom: 24px; color: white; font-size: 13px; background: rgba(0,0,0,0.5); padding: 8px 16px; border-radius: 20px; max-width: 80%; text-align: center; }
        .empty-state { padding: 60px 20px; text-align: center; color: var(--gray-500); }
        .empty-state i { font-size: 48px; color: var(--gray-300); margin-bottom: 16px; display: block; }
        .empty-state p { font-size: 14px; font-style: italic; }
        @keyframes fadeInRow { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
        @media (max-width: 768px) {
            body { padding: 16px; font-size: 12px; }
            .filter-card { flex-direction: column; align-items: stretch; }
            .filter-group { max-width: 100%; }
            .filter-actions { margin-left: 0; justify-content: center; }
            .corporate-header { flex-direction: column; }
            .logo-sec, .info-sec { width: 100%; border-right: none; border-bottom: 2px solid var(--gray-900); }
            .logo-sec { border-radius: var(--radius) var(--radius) 0 0; }
            .info-sec { border-radius: 0 0 var(--radius) var(--radius); }
            th, td { padding: 10px 8px; font-size: 11px; }
            .img-thumb { width: 45px; height: 36px; }
            .attendance-bar { width: 80px; height: 18px; }
            .pagination-wrapper { flex-direction: column; text-align: center; }
            .pagination-controls { flex-wrap: wrap; justify-content: center; }
        }
        @media print { 
            .no-print { display: none !important; } 
            body { background: white; padding: 0; font-size: 10px; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            .corporate-header { border: 2px solid #000; }
            table { font-size: 9px; }
            th, td { padding: 4px 6px; border: 1px solid #000; }
            thead { background: #daeef3 !important; color: #000; -webkit-print-color-adjust: exact; }
            .img-thumb { border: 1px solid #000; }
            .page-header { border-bottom: 2px solid #000; padding-bottom: 10px; }
            .attendance-bar { border: 1px solid #000; }
            .attendance-fill { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        }
        .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
        .divider { height: 1px; background: var(--gray-200); margin: 16px 0; }
    </style>
</head>
<body>

    <!-- ===== LIGHTBOX MODAL ===== -->
    <div id="imgModal" role="dialog" aria-modal="true" aria-label="Pratinjau Foto">
        <span class="close" onclick="closeModal()" aria-label="Tutup">&times;</span>
        <img id="modalImg" src="" alt="Foto Safety Talk">
        <div class="modal-caption">Klik di luar gambar atau tekan ESC untuk menutup</div>
    </div>

    <!-- ===== PAGE HEADER ===== -->
    <div class="no-print">
        <div class="page-header">
            <div class="page-title">
                <i class="fas fa-clipboard-list"></i>
                <div>
                    <h1>REKAPITULASI SAFETY TALK</h1>
                    <small>PT Citra Lampia Mandiri • QHSEF Department • v<?= APP_VERSION ?></small>
                </div>
            </div>
            <a href="index.php" class="back-link"><i class="fas fa-chevron-left"></i> Dashboard</a>
        </div>
        
        <!-- ===== FILTER FORM ===== -->
        <form method="GET" class="filter-card" id="filterForm">
            <input type="hidden" name="page" id="pageInput" value="<?= (int)$page ?>">
            <div class="filter-group">
                <label for="start"><i class="far fa-calendar-alt"></i> Dari Tanggal</label>
                <input type="date" id="start" name="start" value="<?= htmlspecialchars($f_start) ?>">
            </div>
            <div class="filter-group">
                <label for="end"><i class="far fa-calendar-check"></i> Sampai Tanggal</label>
                <input type="date" id="end" name="end" value="<?= htmlspecialchars($f_end) ?>">
            </div>
            <div class="filter-group">
                <label for="divisi"><i class="fas fa-sitemap"></i> Divisi</label>
                <select id="divisi" name="divisi">
                    <option value="">Semua Divisi</option>
                    <option value="HS" <?= $f_divisi==='HS'?'selected':'' ?>>Health & Safety</option>
                    <option value="EF" <?= $f_divisi==='EF'?'selected':'' ?>>Environment & Forestry</option>
                    <option value="QMS" <?= $f_divisi==='QMS'?'selected':'' ?>>Quality Management System</option>
                </select>
            </div>
            <div class="filter-group">
                <label for="search"><i class="fas fa-search"></i> Cari Data</label>
                <input type="text" id="search" name="search" placeholder="Nama / Topik..." value="<?= htmlspecialchars($f_search) ?>">
            </div>
            <div class="filter-actions">
                <button type="submit" class="btn btn-filter"><i class="fas fa-filter"></i> Filter</button>
                <a href="rekap.php" class="btn btn-reset"><i class="fas fa-undo"></i> Reset</a>
                <button type="button" onclick="runExport()" class="btn btn-export"><i class="fas fa-file-csv"></i> Export</button>
                <button type="button" onclick="window.print()" class="btn btn-print"><i class="fas fa-print"></i> Cetak</button>
            </div>
        </form>
    </div>

    <!-- ===== CORPORATE HEADER ===== -->
    <div class="corporate-header">
        <div class="logo-sec">
            <strong>PT CITRA LAMPIA MANDIRI</strong>
            <small><i class="fas fa-shield-alt"></i> QHSEF Department</small>
        </div>
        <div class="info-sec">
            <div class="p-box"><i class="fas fa-clipboard-check"></i> Laporan Aktivitas Safety Talk</div>
            <div class="d-box">
                Periode: <?= $f_start ? formatDateDisplay($f_start) : 'Semua' ?> 
                <i class="fas fa-arrow-right" style="margin:0 6px;font-size:10px"></i> 
                <?= $f_end ? formatDateDisplay($f_end) : 'Sekarang' ?>
            </div>
        </div>
    </div>

    <!-- ===== DATA TABLE ===== -->
    <div class="table-container">
        <div class="table-wrapper">
            <table>
                <thead>
                    <tr>
                        <th width="40">No</th>
                        <th>Tanggal</th>
                        <th>Hari</th>
                        <th class="text-left">Nama / Jabatan</th>
                        <th class="text-left">Topik Materi</th>
                        <th width="60"><i class="fas fa-users"></i><br><small>Hadir</small></th>
                        <th width="60"><i class="fas fa-user-check"></i><br><small>Target</small></th>
                        <th width="110"><i class="fas fa-chart-simple"></i><br><small>Kehadiran</small></th>
                        <th width="70">Divisi</th>
                        <th width="120">Foto Bukti</th>
                        <th class="no-print" width="70">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    if(!empty($paginatedData)):
                        $globalNo = $displayStart;
                        foreach($paginatedData as $r): 
                            $divisi = trim($r[3] ?? '');
                            $divisiClass = match($divisi) {
                                'HS' => 'badge-hs', 'EF' => 'badge-ef', 'QMS' => 'badge-qms', default => ''
                            };
                            
                            // ✅ Hitung attendance metrics
                            $peserta = (int)($r[7] ?? 0);
                            // Backward compatible: jika kolom 8 belum ada, anggap sama dengan peserta
                            $peserta_seharusnya = isset($r[8]) ? (int)$r[8] : $peserta;
                            $attendance = getAttendanceBar($peserta, $peserta_seharusnya);
                    ?>
                    <tr>
                        <td><strong><?= (int)$globalNo++ ?></strong></td>
                        <td><?= htmlspecialchars($r[0] ?? '-') ?></td>
                        <td><span class="badge"><?= htmlspecialchars($r[1] ?? '-') ?></span></td>
                        <td class="text-left">
                            <div class="font-semibold"><?= htmlspecialchars($r[4] ?? '-') ?></div>
                            <small class="text-muted"><?= htmlspecialchars($r[5] ?? '') ?></small>
                        </td>
                        <td class="text-left"><?= htmlspecialchars($r[6] ?? '-') ?></td>
                        <td><strong><?= $peserta ?></strong></td>
                        <td><strong><?= $peserta_seharusnya ?></strong></td>
                        <td class="attendance-cell">
                            <div class="attendance-bar" title="<?= $attendance['label'] ?> (<?= $peserta ?>/<?= $peserta_seharusnya ?>)">
                                <div class="attendance-fill <?= $attendance['class'] ?>" style="width: <?= $attendance['percent'] ?>%">
                                    <span class="attendance-text"><?= $attendance['label'] ?></span>
                                </div>
                            </div>
                            <span class="attendance-ratio"><?= $peserta ?>/<?= $peserta_seharusnya ?></span>
                        </td>
                        <td><span class="badge <?= $divisiClass ?>"><?= htmlspecialchars($divisi) ?></span></td>
                        <td>
                            <div class="photo-gallery">
                                <?php 
                                $fotoField = trim($r[9] ?? $r[8] ?? ''); // Support both old (8) and new (9) structure
                                if(!empty($fotoField)): 
                                    $photos = array_filter(explode("|", $fotoField));
                                    foreach(array_slice($photos, 0, 3) as $img):
                                        $imgSafe = preg_replace('/[^a-zA-Z0-9_\.\-]/', '', basename($img));
                                        if(!empty($imgSafe)):
                                ?>
                                    <img src="uploads/<?= htmlspecialchars($imgSafe) ?>" class="img-thumb" alt="Bukti Foto"
                                         onerror="this.src='data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%2250%22 height=%2240%22 viewBox=%220 0 50 40%22%3E%3Crect fill=%22%23e2e8f0%22 width=%2250%22 height=%2240%22/%3E%3Ctext x=%2250%25%22 y=%2250%25%22 dominant-baseline=%22middle%22 text-anchor=%22middle%22 fill=%22%2394a3b8%22 font-size=%2210%22%3ENo Image%3C/text%3E%3C/svg%3E'"
                                         onclick="openModal(this.src)" loading="lazy">
                                <?php 
                                        endif;
                                    endforeach;
                                    if(count($photos) > 3): ?>
                                    <span class="badge" style="align-self:center">+<?= count($photos)-3 ?></span>
                                <?php 
                                    endif;
                                else: echo '<span class="photo-placeholder"><i class="far fa-image"></i> -</span>';
                                endif; ?>
                            </div>
                        </td>
                        <td class="no-print">
                            <?php $dbId = isset($r['db_id']) ? (int)$r['db_id'] : -1; if($dbId >= 0): ?>
                            <a href="formulir/edit_safety_talk.php?id=<?= $dbId ?>" class="btn-edit btn" title="Edit Data"><i class="fas fa-pen"></i></a>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; else: ?>
                    <tr><td colspan="11"><div class="empty-state"><i class="fas fa-inbox"></i><p>Data tidak ditemukan. Coba ubah filter pencarian Anda.</p></div></td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- ===== PAGINATION ===== -->
        <?php if($totalPages > 1): ?>
        <div class="pagination-wrapper no-print">
            <div class="pagination-info">Menampilkan <strong><?= $displayStart ?>-<?= $displayEnd ?></strong> dari <strong><?= $totalItems ?></strong> data</div>
            <div style="display:flex; gap:16px; align-items:center; flex-wrap:wrap;">
                <div class="per-page-selector">
                    <i class="fas fa-list"></i> Tampil:
                    <select onchange="changePerPage(this.value)">
                        <option value="10" <?= $itemsPerPage==10?'selected':'' ?>>10</option>
                        <option value="25" <?= $itemsPerPage==25?'selected':'' ?>>25</option>
                        <option value="50" <?= $itemsPerPage==50?'selected':'' ?>>50</option>
                    </select>
                </div>
                <div class="pagination-controls">
                    <?php if($page > 1): ?><a href="?<?= buildQuery(['page' => 1]) ?>" class="btn btn-page" title="Halaman Pertama"><i class="fas fa-angle-double-left"></i></a>
                    <?php else: ?><span class="btn btn-page" style="opacity:0.5;cursor:not-allowed"><i class="fas fa-angle-double-left"></i></span><?php endif; ?>
                    <?php if($page > 1): ?><a href="?<?= buildQuery(['page' => $page - 1]) ?>" class="btn btn-page" title="Sebelumnya"><i class="fas fa-angle-left"></i></a>
                    <?php else: ?><span class="btn btn-page" style="opacity:0.5;cursor:not-allowed"><i class="fas fa-angle-left"></i></span><?php endif; ?>
                    <?php foreach(generatePagination($page, $totalPages) as $p): 
                        if($p['page'] === null): ?><span class="pagination-ellipsis">...</span>
                        <?php elseif($p['page'] == $page): ?><span class="btn btn-page active"><strong><?= htmlspecialchars($p['label']) ?></strong></span>
                        <?php else: ?><a href="?<?= buildQuery(['page' => $p['page']]) ?>" class="btn btn-page"><?= htmlspecialchars($p['label']) ?></a>
                    <?php endif; endforeach; ?>
                    <?php if($page < $totalPages): ?><a href="?<?= buildQuery(['page' => $page + 1]) ?>" class="btn btn-page" title="Selanjutnya"><i class="fas fa-angle-right"></i></a>
                    <?php else: ?><span class="btn btn-page" style="opacity:0.5;cursor:not-allowed"><i class="fas fa-angle-right"></i></span><?php endif; ?>
                    <?php if($page < $totalPages): ?><a href="?<?= buildQuery(['page' => $totalPages]) ?>" class="btn btn-page" title="Halaman Terakhir"><i class="fas fa-angle-double-right"></i></a>
                    <?php else: ?><span class="btn btn-page" style="opacity:0.5;cursor:not-allowed"><i class="fas fa-angle-double-right"></i></span><?php endif; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- ===== FOOTER INFO ===== -->
    <div class="no-print" style="margin-top:20px; text-align:center; color:var(--gray-500); font-size:11px;">
        <i class="fas fa-info-circle"></i> Total <strong><?= (int)$totalItems ?></strong> data • Halaman <strong><?= (int)$page ?> / <?= (int)$totalPages ?></strong> • Dicetak: <?= date('d/m/Y H:i') ?> • 
        <a href="#" onclick="window.scrollTo({top:0,behavior:'smooth'});return false;" style="color:var(--primary);text-decoration:none"><i class="fas fa-arrow-up"></i> Kembali ke atas</a>
    </div>

    <!-- ===== INCLUDE FOOTER ===== -->
    <?php include __DIR__ . '/footer.php'; ?>

    <script>
    function openModal(src) { const modal = document.getElementById('imgModal'), modalImg = document.getElementById('modalImg'); if(modal && modalImg) { modal.style.display = "flex"; modalImg.src = src; document.body.style.overflow = 'hidden'; } }
    function closeModal() { const modal = document.getElementById('imgModal'); if(modal) { modal.style.display = "none"; document.body.style.overflow = ''; } }
    document.addEventListener('keydown', e => { if(e.key === 'Escape') closeModal(); });
    const imgModal = document.getElementById('imgModal'); if(imgModal) imgModal.addEventListener('click', e => { if(e.target === this) closeModal(); });
    function changePerPage(value) { const params = new URLSearchParams(window.location.search); params.set('per_page', value); params.set('page', '1'); window.location.search = params.toString(); }
    const filterForm = document.getElementById('filterForm'); if(filterForm) filterForm.addEventListener('submit', () => { const pageInput = document.getElementById('pageInput'); if(pageInput) pageInput.value = '1'; });
    function runExport() { const params = new URLSearchParams(window.location.search); params.delete('page'); const queryString = params.toString(); window.location.href = 'export_csv.php' + (queryString ? '?' + queryString : ''); }
    document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('tbody tr').forEach((row, index) => { row.style.animation = `fadeInRow 0.3s ease ${index * 0.03}s both`; }); });
    </script>
</body>
</html>