<?php
// File: audio.php
require_once 'config/database.php';
require_once 'config/auth.php';

// Hanya admin yang boleh mengakses
requireAdmin();

// Konfigurasi upload
$upload_dir = __DIR__ . '/audio/';
$allowed_extensions = ['mp3', 'wav', 'ogg'];
$max_file_size = 5 * 1024 * 1024; // 5MB

// Pesan notifikasi
$success_message = '';
$error_message = '';

// Handle upload audio
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload'])) {
    $nama_audio = $_POST['nama_audio'] ?? '';
    $nama_kegiatan = $_POST['nama_kegiatan'] ?? ''; // NEW: Activity name
    
    // Validasi nama audio
    if (empty($nama_audio)) {
        $error_message = "❌ Nama audio wajib diisi!";
    } elseif (!isset($_FILES['file_audio']) || $_FILES['file_audio']['error'] !== UPLOAD_ERR_OK) {
        $error_message = "❌ File audio gagal diupload!";
    } else {
        $file = $_FILES['file_audio'];
        $file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $file_size = $file['size'];
        
        // Validasi ekstensi
        if (!in_array($file_ext, $allowed_extensions)) {
            $error_message = "❌ Format file tidak diizinkan! Hanya MP3, WAV, atau OGG.";
        } elseif ($file_size > $max_file_size) {
            $error_message = "❌ Ukuran file terlalu besar! Maksimal 5MB.";
        } else {
            // ===== PERBAIKAN: Gunakan nama kegiatan untuk filename =====
            // Sanitize filename dari nama kegiatan
            if (!empty($nama_kegiatan)) {
                // Convert to lowercase, replace spaces with underscore
                $clean_name = strtolower(trim($nama_kegiatan));
                $clean_name = preg_replace('/[^a-z0-9]+/i', '_', $clean_name);
                $clean_name = trim($clean_name, '_');
                $new_filename = $clean_name . '.' . $file_ext;
            } else {
                // Fallback: Use nama_audio
                $clean_name = strtolower(trim($nama_audio));
                $clean_name = preg_replace('/[^a-z0-9]+/i', '_', $clean_name);
                $clean_name = trim($clean_name, '_');
                $new_filename = $clean_name . '.' . $file_ext;
            }
            
            // Check if file already exists, add timestamp if needed
            $upload_path = $upload_dir . $new_filename;
            if (file_exists($upload_path)) {
                $new_filename = pathinfo($new_filename, PATHINFO_FILENAME) . '_' . time() . '.' . $file_ext;
                $upload_path = $upload_dir . $new_filename;
            }
            
            // Pastikan folder audio ada
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            // Move uploaded file
            if (move_uploaded_file($file['tmp_name'], $upload_path)) {
                // Insert to database
                $stmt = $conn->prepare("INSERT INTO belloto_audio (nama_audio, file_path, durasi) VALUES (?, ?, ?)");
                
                // Get duration (optional)
                $durasi = 0;
                
                $stmt->bind_param("ssi", $nama_audio, $new_filename, $durasi);
                
                if ($stmt->execute()) {
                    $success_message = "✅ Audio berhasil diupload!<br>
                                        <strong>File:</strong> $new_filename<br>
                                        <strong>Nama Tampilan:</strong> $nama_audio";
                } else {
                    $error_message = "❌ Gagal menyimpan ke database: " . $stmt->error;
                    // Delete file if database insert fails
                    unlink($upload_path);
                }
                $stmt->close();
            } else {
                $error_message = "❌ Gagal memindahkan file ke folder audio!";
            }
        }
    }
}

// Delete audio
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    
    // Get file path first
    $result = $conn->query("SELECT file_path FROM belloto_audio WHERE id = $id");
    if ($row = $result->fetch_assoc()) {
        $file_path = $upload_dir . $row['file_path'];
        
        // Delete from database
        $conn->query("DELETE FROM belloto_audio WHERE id = $id");
        
        // Delete physical file
        if (file_exists($file_path)) {
            unlink($file_path);
        }
        
        header('Location: audio.php?deleted=1');
        exit;
    }
}

// Get all audio files
$audios = $conn->query("SELECT * FROM belloto_audio ORDER BY uploaded_at DESC");
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola Audio - Bel Sekolah</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>
        .audio-player { width: 100%; margin-top: 5px; }
        .file-size { font-size: 0.85rem; color: #6c757d; }
        .upload-area { 
            border: 2px dashed #0d6efd; 
            border-radius: 10px; 
            padding: 30px; 
            text-align: center;
            background: #f8f9fa;
            transition: all 0.3s;
        }
        .upload-area:hover {
            border-color: #0a58ca;
            background: #e7f1ff;
        }
        .audio-icon { font-size: 3rem; color: #0d6efd; }
        
        /* Auto logout warning styles */
        .session-warning {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            background: #ffc107;
            color: #000;
            padding: 10px 20px;
            border-radius: 50px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
            display: none;
            align-items: center;
            gap: 10px;
            font-weight: 500;
            animation: slideIn 0.3s ease;
        }
        
        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
        
        .session-warning.show {
            display: flex;
        }
        
        .logout-timer {
            background: #fff;
            padding: 2px 10px;
            border-radius: 20px;
            margin-left: 10px;
            font-weight: bold;
            color: #dc3545;
        }
        
        .navbar-user {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 50px;
            padding: 5px 15px;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
    </style>
</head>
<body>
    <!-- Session Warning -->
    <div class="session-warning" id="sessionWarning">
        <i class="bi bi-exclamation-triangle-fill"></i>
        <span>Sesi akan berakhir dalam <span id="logoutTimer" class="logout-timer">60</span> detik</span>
        <button class="btn btn-sm btn-light ms-2" onclick="extendSession()">Perpanjang Sesi</button>
    </div>

    <div class="container py-4">
        <!-- Header with User Info and Logout -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h2 class="mb-1">🎵 Kelola Audio Bel Sekolah</h2>
                <div class="navbar-user">
                    <i class="bi bi-person-circle"></i>
                    <span><?= htmlspecialchars($_SESSION['nama_lengkap'] ?? $_SESSION['username']) ?></span>
                    <span class="badge bg-light text-dark"><?= $_SESSION['user_level'] ?></span>
                </div>
            </div>
            <div>
                <a href="logout.php" class="btn btn-danger" id="logoutBtn">
                    <i class="bi bi-box-arrow-right"></i> Logout
                </a>
            </div>
        </div>
        
        <!-- Alert Messages -->
        <?php if ($success_message): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="bi bi-check-circle"></i> <?= $success_message ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>
        
        <?php if ($error_message): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="bi bi-exclamation-triangle"></i> <?= $error_message ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>
        
        <?php if (isset($_GET['deleted'])): ?>
        <div class="alert alert-info alert-dismissible fade show">
            <i class="bi bi-trash"></i> Audio berhasil dihapus!
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>
        
        <!-- Form Upload -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><i class="bi bi-cloud-upload"></i> Upload Audio Baru</h5>
            </div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <div class="row g-3">
                        <div class="col-md-3">
                            <label class="form-label">Nama Audio (Tampilan)</label>
                            <input type="text" name="nama_audio" class="form-control" 
                                   placeholder="Contoh: Bel Masuk" required>
                            <div class="form-text">Nama yang ditampilkan di dropdown</div>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Nama Kegiatan</label>
                            <input type="text" name="nama_kegiatan" class="form-control" 
                                   placeholder="Contoh: Masuk Sekolah" 
                                   title="Nama file akan dibuat dari ini (opsional)">
                            <div class="form-text">File akan dinamai sesuai kegiatan</div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">File Audio</label>
                            <div class="upload-area">
                                <i class="bi bi-music-note-beamed audio-icon mb-3"></i>
                                <p class="mb-2">Drag & drop file audio di sini atau klik untuk memilih</p>
                                <input type="file" name="file_audio" class="form-control" 
                                       accept=".mp3,.wav,.ogg" required>
                                <div class="file-size mt-2">
                                    <i class="bi bi-info-circle"></i> Format: MP3, WAV, OGG | Maksimal: 5MB
                                </div>
                            </div>
                        </div>
                        <div class="col-12">
                            <button type="submit" name="upload" class="btn btn-primary">
                                <i class="bi bi-upload"></i> Upload Audio
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Daftar Audio -->
        <div class="card">
            <div class="card-header bg-success text-white">
                <h5 class="mb-0"><i class="bi bi-music-note-list"></i> Daftar Audio Tersedia</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover table-bordered">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Nama Audio</th>
                                <th>File Name</th>
                                <th>Durasi</th>
                                <th>Preview</th>
                                <th>Uploaded</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            if ($audios && $audios->num_rows > 0):
                                $no = 1;
                                while ($audio = $audios->fetch_assoc()): 
                            ?>
                            <tr>
                                <td><?= $no++ ?></td>
                                <td><strong><?= htmlspecialchars($audio['nama_audio']) ?></strong></td>
                                <td><code><?= htmlspecialchars($audio['file_path']) ?></code></td>
                                <td>
                                    <?php if ($audio['durasi'] > 0): ?>
                                        <?= gmdate('i:s', $audio['durasi']) ?>
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <audio controls class="audio-player">
                                        <source src="audio/<?= htmlspecialchars($audio['file_path']) ?>" type="audio/mpeg">
                                        Browser Anda tidak mendukung audio player.
                                    </audio>
                                </td>
                                <td>
                                    <small><?= date('d/m/Y H:i', strtotime($audio['uploaded_at'])) ?></small>
                                </td>
                                <td>
                                    <a href="audio/<?= htmlspecialchars($audio['file_path']) ?>" 
                                       class="btn btn-sm btn-info" download
                                       title="Download">
                                        <i class="bi bi-download"></i>
                                    </a>
                                    <a href="?delete=<?= $audio['id'] ?>" 
                                       class="btn btn-sm btn-danger"
                                       onclick="return confirm('Yakin ingin menghapus audio ini? File akan dihapus permanen!')"
                                       title="Hapus">
                                        <i class="bi bi-trash"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php 
                                endwhile;
                            else:
                            ?>
                            <tr>
                                <td colspan="7" class="text-center text-muted">
                                    <i class="bi bi-inbox"></i> Belum ada audio yang diupload
                                </td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        
        <!-- Info Folder -->
        <div class="alert alert-warning mt-4">
            <i class="bi bi-folder"></i> <strong>Info Folder:</strong>
            File audio disimpan di folder <code><?= htmlspecialchars($upload_dir) ?></code>
            <br>
            <i class="bi bi-shield-check"></i> <strong>Keamanan:</strong>
            Hanya file MP3, WAV, dan OGG yang diizinkan. Maksimal ukuran 5MB per file.
            <br>
            <i class="bi bi-file-earmark-music"></i> <strong>PENAMAAN:</strong>
            Nama file otomatis dibuat dari <strong>Nama Kegiatan</strong> (contoh: "Masuk Sekolah" → "masuk_sekolah.mp3")
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    // Auto-fill filename when file selected
    document.querySelector('input[name="file_audio"]').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            const namaAudio = document.querySelector('input[name="nama_audio"]');
            const namaKegiatan = document.querySelector('input[name="nama_kegiatan"]');
            
            if (!namaAudio.value) {
                // Remove extension and capitalize
                const name = file.name.replace(/\.[^/.]+$/, "").replace(/_/g, " ");
                namaAudio.value = name.charAt(0).toUpperCase() + name.slice(1);
            }
            
            // Auto-fill nama kegiatan from filename
            if (!namaKegiatan.value) {
                const name = file.name.replace(/\.[^/.]+$/, "").replace(/_/g, " ");
                namaKegiatan.value = name.charAt(0).toUpperCase() + name.slice(1);
            }
        }
    });

    // Drag and drop functionality
    const uploadArea = document.querySelector('.upload-area');
    const fileInput = document.querySelector('input[name="file_audio"]');

    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        uploadArea.addEventListener(eventName, preventDefaults, false);
    });

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    ['dragenter', 'dragover'].forEach(eventName => {
        uploadArea.addEventListener(eventName, () => {
            uploadArea.style.borderColor = '#198754';
            uploadArea.style.background = '#d1e7dd';
        });
    });

    ['dragleave', 'drop'].forEach(eventName => {
        uploadArea.addEventListener(eventName, () => {
            uploadArea.style.borderColor = '#0d6efd';
            uploadArea.style.background = '#f8f9fa';
        });
    });

    uploadArea.addEventListener('drop', (e) => {
        const dt = e.dataTransfer;
        const files = dt.files;
        if (files.length > 0) {
            fileInput.files = files;
            const event = new Event('change');
            fileInput.dispatchEvent(event);
        }
    });
    
    // ===== AUTO LOGOUT FEATURE =====
    let logoutTimer;
    let warningTimer;
    let timeLeft = 60; // 60 detik warning
    const sessionTimeout = 10 * 60 * 1000; // 10 menit
    const warningTime = 60 * 1000; // 1 menit sebelum logout
    
    const sessionWarning = document.getElementById('sessionWarning');
    const logoutTimerSpan = document.getElementById('logoutTimer');
    
    // Reset timer on user activity
    function resetSessionTimer() {
        clearTimeout(logoutTimer);
        clearTimeout(warningTimer);
        hideWarning();
        
        // Set warning timer
        warningTimer = setTimeout(showWarning, sessionTimeout - warningTime);
        
        // Set logout timer
        logoutTimer = setTimeout(autoLogout, sessionTimeout);
    }
    
    // Show warning
    function showWarning() {
        sessionWarning.classList.add('show');
        timeLeft = 60;
        
        // Update countdown every second
        const countdown = setInterval(() => {
            timeLeft--;
            logoutTimerSpan.textContent = timeLeft;
            
            if (timeLeft <= 0) {
                clearInterval(countdown);
            }
        }, 1000);
    }
    
    // Hide warning
    function hideWarning() {
        sessionWarning.classList.remove('show');
    }
    
    // Extend session
    function extendSession() {
        fetch('api/extend_session.php')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    resetSessionTimer();
                    showNotification('Sesi diperpanjang', 'success');
                }
            })
            .catch(error => console.error('Error:', error));
    }
    
    // Auto logout
    function autoLogout() {
        // Show notification before logout
        showNotification('Sesi berakhir, mengalihkan ke halaman utama...', 'warning');
        
        // Redirect to logout
        setTimeout(() => {
            window.location.href = 'logout.php?auto=1';
        }, 2000);
    }
    
    // Show notification
    function showNotification(message, type = 'info') {
        const toast = document.createElement('div');
        toast.className = `toast align-items-center text-white bg-${type} border-0 position-fixed top-0 end-0 m-3`;
        toast.setAttribute('role', 'alert');
        toast.setAttribute('aria-live', 'assertive');
        toast.setAttribute('aria-atomic', 'true');
        toast.style.zIndex = '9999';
        
        toast.innerHTML = `
            <div class="d-flex">
                <div class="toast-body">
                    ${message}
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
            </div>
        `;
        
        document.body.appendChild(toast);
        const bsToast = new bootstrap.Toast(toast);
        bsToast.show();
        
        // Remove after hidden
        toast.addEventListener('hidden.bs.toast', () => {
            toast.remove();
        });
    }
    
    // Track user activity
    ['click', 'mousemove', 'keypress', 'scroll', 'touchstart'].forEach(event => {
        document.addEventListener(event, resetSessionTimer);
    });
    
    // Start timer on page load
    document.addEventListener('DOMContentLoaded', () => {
        resetSessionTimer();
    });
    
    // Handle page visibility change
    document.addEventListener('visibilitychange', () => {
        if (document.visibilityState === 'visible') {
            // Check session status when page becomes visible again
            fetch('api/check_session.php')
                .then(response => response.json())
                .then(data => {
                    if (!data.valid) {
                        autoLogout();
                    } else {
                        resetSessionTimer();
                    }
                });
        }
    });
    
    // Handle back button (Kembali) - otomatis logout
    document.querySelectorAll('a[href="index.php"]').forEach(link => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            
            // Show confirmation
            if (confirm('Kembali ke halaman utama akan mengakhiri sesi Anda. Lanjutkan?')) {
                window.location.href = 'logout.php?redirect=index';
            }
        });
    });
    
    // Handle browser back/forward
    window.addEventListener('popstate', () => {
        // Check if we're leaving the page
        if (document.referrer && !document.referrer.includes('audio.php')) {
            autoLogout();
        }
    });
    
    // Handle page unload
    window.addEventListener('beforeunload', () => {
        // Optional: Notify server about page unload
        navigator.sendBeacon('api/log_activity.php', JSON.stringify({
            action: 'leave',
            page: 'audio.php',
            user: '<?= $_SESSION['username'] ?? '' ?>'
        }));
    });
    </script>
</body>
</html>