<?php
// File: log.php - Log Aktivitas Bel Sekolah SMAN 1 Bantaran
// Versi: 4.0 (Fixed Audio Player)
require_once 'config/database.php';

// Filter tanggal
$filter_date = $_GET['date'] ?? date('Y-m-d');
$filter_status = $_GET['status'] ?? '';

// Pagination settings
$rows_per_page = isset($_GET['rows']) && in_array($_GET['rows'], [10, 30, 50, 100]) ? (int)$_GET['rows'] : 10;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $rows_per_page;

// Build query for count
$count_query = "SELECT COUNT(*) as total FROM belloto_log WHERE tanggal = ?";
$count_params = [$filter_date];
$count_types = "s";

if (!empty($filter_status)) {
    $count_query .= " AND status = ?";
    $count_params[] = $filter_status;
    $count_types .= "s";
}

$count_stmt = $conn->prepare($count_query);
$count_stmt->bind_param($count_types, ...$count_params);
$count_stmt->execute();
$total_records = $count_stmt->get_result()->fetch_assoc()['total'];
$total_pages = $rows_per_page > 0 ? ceil($total_records / $rows_per_page) : 1;

// Build main query with pagination - IMPROVED to get audio_file
$query = "SELECT l.*, 
          COALESCE(j.audio_file, l.kegiatan) as audio_file,
          j.nama_kegiatan, 
          j.jam as jadwal_jam 
          FROM belloto_log l 
          LEFT JOIN belloto_jadwal j ON l.jadwal_bel_id = j.id 
          WHERE l.tanggal = ?";
$params = [$filter_date];
$types = "s";

if (!empty($filter_status)) {
    $query .= " AND l.status = ?";
    $params[] = $filter_status;
    $types .= "s";
}

$query .= " ORDER BY l.id DESC"; // ✅ Urutkan berdasarkan data masuk terakhir

if ($rows_per_page > 0) {
    $query .= " LIMIT ? OFFSET ?";
    $params[] = $rows_per_page;
    $params[] = $offset;
    $types .= "ii";
}

$stmt = $conn->prepare($query);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$logs = $stmt->get_result();

// Statistik
$stats = $conn->query("SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'Berhasil' THEN 1 ELSE 0 END) as berhasil,
    SUM(CASE WHEN status = 'Gagal' THEN 1 ELSE 0 END) as gagal
    FROM belloto_log 
    WHERE tanggal = '$filter_date'")->fetch_assoc();
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Log Bel Sekolah - SMAN 1 Bantaran</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <style>
        body { 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            min-height: 100vh; 
        }
        .log-card { 
            background: rgba(255,255,255,0.95); 
            border-radius: 15px; 
        }
        .stat-box { 
            background: white; 
            border-radius: 10px; 
            padding: 20px; 
            text-align: center; 
        }
        .audio-player { 
            width: 200px; 
            height: 40px;
        }
        .pagination-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 20px;
            flex-wrap: wrap;
            gap: 10px;
        }
        .rows-per-page {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .btn-test-audio {
            white-space: nowrap;
        }
        /* Fix untuk audio player */
        audio::-webkit-media-controls-panel {
            display: flex !important;
        }
        audio::--webkit-media-controls-play-button {
            display: flex !important;
        }
    </style>
</head>
<body>
<div class="container py-4">
    <!-- Header -->
    <div class="text-center mb-4">
        <h1 class="text-white fw-bold">📊 LOG AKTIVITAS BEL</h1>
        <h3 class="text-white">SMAN 1 BANTARAN</h3>
    </div>

    <!-- Kembali -->
    <div class="mb-3">
        <a href="index.php" class="btn btn-light">
            <i class="bi bi-arrow-left"></i> Kembali ke Dashboard
        </a>
    </div>

    <!-- Statistik -->
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="stat-box shadow">
                <h3 class="text-primary"><?= $stats['total'] ?? 0 ?></h3>
                <p class="text-muted mb-0">Total Bel</p>
            </div>
        </div>
        <div class="col-md-4">
            <div class="stat-box shadow">
                <h3 class="text-success"><?= $stats['berhasil'] ?? 0 ?></h3>
                <p class="text-muted mb-0">Berhasil</p>
            </div>
        </div>
        <div class="col-md-4">
            <div class="stat-box shadow">
                <h3 class="text-danger"><?= $stats['gagal'] ?? 0 ?></h3>
                <p class="text-muted mb-0">Gagal</p>
            </div>
        </div>
    </div>

    <!-- Filter -->
    <div class="log-card p-4 shadow mb-4">
        <h4 class="mb-3"><i class="bi bi-funnel"></i> Filter Log</h4>
        <form method="GET" class="row g-3">
            <div class="col-md-3">
                <label class="form-label">Tanggal</label>
                <input type="date" name="date" class="form-control" value="<?= htmlspecialchars($filter_date) ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label">Status</label>
                <select name="status" class="form-select">
                    <option value="">Semua</option>
                    <option value="Berhasil" <?= $filter_status == 'Berhasil' ? 'selected' : '' ?>>Berhasil</option>
                    <option value="Gagal" <?= $filter_status == 'Gagal' ? 'selected' : '' ?>>Gagal</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Baris</label>
                <select name="rows" class="form-select" onchange="this.form.submit()">
                    <option value="10" <?= $rows_per_page == 10 ? 'selected' : '' ?>>10</option>
                    <option value="30" <?= $rows_per_page == 30 ? 'selected' : '' ?>>30</option>
                    <option value="50" <?= $rows_per_page == 50 ? 'selected' : '' ?>>50</option>
                    <option value="100" <?= $rows_per_page == 100 ? 'selected' : '' ?>>100</option>
                    <option value="0" <?= $rows_per_page == 0 ? 'selected' : '' ?>>All</option>
                </select>
            </div>
            <div class="col-md-3 d-flex align-items-end">
                <button type="submit" class="btn btn-primary w-100">
                    <i class="bi bi-search"></i> Filter
                </button>
            </div>
            <div class="col-md-2 d-flex align-items-end">
                <button type="button" class="btn btn-success w-100" onclick="unlockAudio()">
                    <i class="bi bi-volume-up"></i> Aktifkan Audio
                </button>
            </div>
        </form>
    </div>

    <!-- Tabel Log -->
    <div class="log-card p-4 shadow">
        <h4 class="mb-3">
            <i class="bi bi-journal-text"></i> Riwayat Log - <?= date('d/m/Y', strtotime($filter_date)) ?>
            <span class="badge bg-info float-end"><?= $total_records ?> Data</span>
        </h4>
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Jam</th>
                        <th>Kegiatan</th>
                        <th>Jadwal</th>
                        <th>Status</th>
                        <th>Preview Audio</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    if ($logs && $logs->num_rows > 0):
                        $no = $offset + 1;
                        while ($log = $logs->fetch_assoc()): 
                            // Pastikan audio_file ada, fallback ke default.mp3
                            $audio_file = !empty($log['audio_file']) ? $log['audio_file'] : 'default.mp3';
                            $audio_path = 'audio/' . $audio_file;
                            // Cek apakah file ada
                            $file_exists = file_exists(__DIR__ . '/' . $audio_path);
                    ?>
                    <tr>
                        <td><?= $no++ ?></td>
                        <td><?= substr($log['jam'], 0, 5) ?></td>
                        <td><?= htmlspecialchars($log['kegiatan']) ?></td>
                        <td><?= $log['jadwal_jam'] ? substr($log['jadwal_jam'], 0, 5) : '-' ?></td>
                        <td>
                            <span class="badge <?= $log['status'] == 'Berhasil' ? 'bg-success' : 'bg-danger' ?>">
                                <?= $log['status'] ?>
                            </span>
                        </td>
                        <td>
                            <?php if ($file_exists): ?>
                                <!-- ✅ AUDIO PLAYER dengan source yang benar -->
                                <audio controls class="audio-player" preload="metadata">
                                    <source src="<?= htmlspecialchars($audio_path) ?>?t=<?= time() ?>" type="audio/mpeg">
                                    Browser Anda tidak mendukung audio player.
                                </audio>
                            <?php else: ?>
                                <small class="text-muted">
                                    <i class="bi bi-exclamation-triangle"></i> 
                                    File tidak ditemukan: <?= htmlspecialchars($audio_file) ?>
                                </small>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php 
                        endwhile;
                    else:
                    ?>
                    <tr>
                        <td colspan="6" class="text-center text-muted">
                            <i class="bi bi-inbox"></i> Tidak ada log untuk tanggal ini
                        </td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- ✅ PAGINATION -->
        <?php if ($total_pages > 1): ?>
        <div class="pagination-container">
            <div class="rows-per-page">
                <span class="text-muted">Menampilkan <?= min($offset + 1, $total_records) ?> - <?= min($offset + $rows_per_page, $total_records) ?> dari <?= $total_records ?> data</span>
            </div>
            <nav>
                <ul class="pagination mb-0">
                    <!-- Previous -->
                    <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                        <a class="page-link" href="?date=<?= htmlspecialchars($filter_date) ?>&status=<?= htmlspecialchars($filter_status) ?>&rows=<?= $rows_per_page ?>&page=<?= $page - 1 ?>">
                            <i class="bi bi-chevron-left"></i> Prev
                        </a>
                    </li>
                    
                    <!-- Page Numbers -->
                    <?php 
                    $start_page = max(1, $page - 2);
                    $end_page = min($total_pages, $page + 2);
                    
                    if ($start_page > 1):
                    ?>
                    <li class="page-item">
                        <a class="page-link" href="?date=<?= htmlspecialchars($filter_date) ?>&status=<?= htmlspecialchars($filter_status) ?>&rows=<?= $rows_per_page ?>&page=1">1</a>
                    </li>
                    <?php if ($start_page > 2): ?>
                    <li class="page-item disabled"><span class="page-link">...</span></li>
                    <?php endif; ?>
                    <?php endif; ?>
                    
                    <?php for ($i = $start_page; $i <= $end_page; $i++): ?>
                    <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                        <a class="page-link" href="?date=<?= htmlspecialchars($filter_date) ?>&status=<?= htmlspecialchars($filter_status) ?>&rows=<?= $rows_per_page ?>&page=<?= $i ?>"><?= $i ?></a>
                    </li>
                    <?php endfor; ?>
                    
                    <?php if ($end_page < $total_pages): ?>
                    <?php if ($end_page < $total_pages - 1): ?>
                    <li class="page-item disabled"><span class="page-link">...</span></li>
                    <?php endif; ?>
                    <li class="page-item">
                        <a class="page-link" href="?date=<?= htmlspecialchars($filter_date) ?>&status=<?= htmlspecialchars($filter_status) ?>&rows=<?= $rows_per_page ?>&page=<?= $total_pages ?>"><?= $total_pages ?></a>
                    </li>
                    <?php endif; ?>
                    
                    <!-- Next -->
                    <li class="page-item <?= $page >= $total_pages ? 'disabled' : '' ?>">
                        <a class="page-link" href="?date=<?= htmlspecialchars($filter_date) ?>&status=<?= htmlspecialchars($filter_status) ?>&rows=<?= $rows_per_page ?>&page=<?= $page + 1 ?>">
                            Next <i class="bi bi-chevron-right"></i>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
        <?php endif; ?>
    </div>

    <!-- Export -->
    <div class="text-center mt-4">
        <button class="btn btn-success" onclick="window.print()">
            <i class="bi bi-printer"></i> Cetak Log
        </button>
        <button class="btn btn-info text-white" onclick="exportCSV()">
            <i class="bi bi-download"></i> Export CSV
        </button>
    </div>
</div>

<!-- Audio Element for Test (Hidden) -->
<audio id="globalAudio" preload="auto">
    <source src="" type="audio/mpeg">
</audio>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// ===== GLOBAL VARIABLES =====
let audioUnlocked = false;

// ===== UNLOCK AUDIO (WAJIB KLIK DULU) =====
function unlockAudio() {
    const audio = document.getElementById('globalAudio');
    audio.volume = 0.5;
    
    // Set source ke default.mp3 untuk test
    audio.src = 'audio/default.mp3?t=' + new Date().getTime();
    audio.load();
    
    const playPromise = audio.play();
    
    if (playPromise !== undefined) {
        playPromise.then(() => {
            console.log('✅ Audio context unlocked');
            audio.pause();
            audio.currentTime = 0;
            audioUnlocked = true;
            
            alert('✅ Audio sudah diaktifkan! Sekarang Anda bisa memutar preview audio.');
        })
        .catch(error => {
            console.error('❌ Failed to unlock audio:', error);
            alert('⚠️ Klik tombol lagi atau pastikan browser tidak memblokir audio.');
        });
    }
}

// ===== SETUP AUDIO PLAYERS =====
document.addEventListener('DOMContentLoaded', function() {
    const audioPlayers = document.querySelectorAll('audio.audio-player');
    
    audioPlayers.forEach(player => {
        // Pause other audios when this one plays
        player.addEventListener('play', function() {
            audioPlayers.forEach(other => {
                if (other !== player) {
                    other.pause();
                }
            });
        });
        
        // Error handling
        player.addEventListener('error', function(e) {
            console.error('Audio error:', e);
            console.error('Source:', player.querySelector('source')?.src);
        });
        
        // Log when loaded
        player.addEventListener('loadedmetadata', function() {
            console.log('Audio loaded:', player.querySelector('source')?.src);
            console.log('Duration:', player.duration);
        });
    });
});

// ===== EXPORT CSV FUNCTION =====
function exportCSV() {
    const table = document.querySelector('table');
    let csv = [];
    
    // Header
    const headers = [];
    table.querySelectorAll('thead th').forEach(th => {
        headers.push(th.textContent.trim());
    });
    csv.push(headers.join(','));
    
    // Rows
    table.querySelectorAll('tbody tr').forEach(tr => {
        const row = [];
        tr.querySelectorAll('td').forEach(td => {
            row.push('"' + td.textContent.trim().replace(/"/g, '""') + '"');
        });
        csv.push(row.join(','));
    });
    
    // Download
    const csvContent = csv.join('\n');
    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `log_bel_<?= $filter_date ?>.csv`;
    a.click();
}
</script>
</body>
</html>