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

// Hanya admin yang boleh mengakses
requireAdmin();

// Handle form submission - TAMBAH JADWAL
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'add') {
        $hari = $_POST['hari'] ?? '';
        $jam = $_POST['jam'] ?? '';
        $kegiatan = $_POST['kegiatan'] ?? '';
        $audio = $_POST['audio_file'] ?? 'default.mp3';
        $aktif = isset($_POST['aktif']) ? 1 : 0;
        
        if (!empty($hari) && !empty($jam) && !empty($kegiatan)) {
            $stmt = $conn->prepare("INSERT INTO belloto_jadwal (hari, jam, nama_kegiatan, audio_file, aktif) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("ssssi", $hari, $jam, $kegiatan, $audio, $aktif);
            
            if ($stmt->execute()) {
                $success_message = "✅ Jadwal berhasil ditambahkan!";
            } else {
                $error_message = "❌ Gagal menambahkan jadwal: " . $stmt->error;
            }
            $stmt->close();
        } else {
            $error_message = "❌ Harap lengkapi semua field wajib!";
        }
    }
    
    // UPDATE JADWAL
    if ($_POST['action'] === 'update') {
        $id = (int)$_POST['id'];
        $hari = $_POST['edit_hari'] ?? '';
        $jam = $_POST['edit_jam'] ?? '';
        $kegiatan = $_POST['edit_kegiatan'] ?? '';
        $audio = $_POST['edit_audio_file'] ?? 'default.mp3';
        $aktif = isset($_POST['edit_aktif']) ? 1 : 0;
        
        if (!empty($hari) && !empty($jam) && !empty($kegiatan)) {
            $stmt = $conn->prepare("UPDATE belloto_jadwal SET hari = ?, jam = ?, nama_kegiatan = ?, audio_file = ?, aktif = ? WHERE id = ?");
            $stmt->bind_param("ssssii", $hari, $jam, $kegiatan, $audio, $aktif, $id);
            
            if ($stmt->execute()) {
                $success_message = "✅ Jadwal berhasil diupdate!";
            } else {
                $error_message = "❌ Gagal mengupdate jadwal: " . $stmt->error;
            }
            $stmt->close();
        } else {
            $error_message = "❌ Harap lengkapi semua field wajib!";
        }
    }
}

// Delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $conn->query("DELETE FROM belloto_jadwal WHERE id = $id");
    header('Location: jadwal.php?deleted=1');
    exit;
}

// Get all schedules
$schedules = $conn->query("SELECT * FROM belloto_jadwal ORDER BY FIELD(hari, 'Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'), jam ASC");

// Get audio files for dropdown
$audios = $conn->query("SELECT * FROM belloto_audio");
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola Jadwal - 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>
        /* 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;
        }
        
        .session-warning i {
            font-size: 1.2rem;
        }
        
        @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;
        }
        
        .back-button {
            position: relative;
            overflow: hidden;
        }
        
        .back-button::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            border-radius: 50%;
            background: rgba(255,255,255,0.3);
            transform: translate(-50%, -50%);
            transition: width 0.3s, height 0.3s;
        }
        
        .back-button:active::after {
            width: 200px;
            height: 200px;
        }
    </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 Jadwal Bel</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 (isset($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 (isset($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> Jadwal berhasil dihapus!
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>
        
        <!-- Form Tambah -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><i class="bi bi-plus-circle"></i> Tambah Jadwal Baru</h5>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="action" value="add">
                    <div class="row g-3">
                        <div class="col-md-2">
                            <label class="form-label">Hari</label>
                            <select name="hari" class="form-select" required>
                                <option value="">Pilih Hari</option>
                                <option value="Senin">Senin</option>
                                <option value="Selasa">Selasa</option>
                                <option value="Rabu">Rabu</option>
                                <option value="Kamis">Kamis</option>
                                <option value="Jumat">Jumat</option>
                                <option value="Sabtu">Sabtu</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">Jam</label>
                            <input type="time" name="jam" class="form-control" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Nama Kegiatan</label>
                            <input type="text" name="kegiatan" class="form-control" placeholder="Contoh: Masuk Sekolah" required>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">Audio</label>
                            <select name="audio_file" class="form-select">
                                <option value="default.mp3">default.mp3</option>
                                <?php 
                                if ($audios && $audios->num_rows > 0):
                                    while ($audio = $audios->fetch_assoc()): 
                                ?>
                                <option value="<?= htmlspecialchars($audio['file_path']) ?>">
                                    <?= htmlspecialchars($audio['nama_audio']) ?>
                                </option>
                                <?php 
                                    endwhile;
                                endif;
                                ?>
                            </select>
                        </div>
                        <div class="col-md-2 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary w-100">
                                <i class="bi bi-save"></i> Simpan
                            </button>
                        </div>
                    </div>
                    <div class="form-check mt-3">
                        <input type="checkbox" name="aktif" class="form-check-input" id="aktif" checked>
                        <label class="form-check-label" for="aktif">
                            <strong>Aktif</strong> (Jadwal akan dibunyikan otomatis)
                        </label>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Table -->
        <div class="card">
            <div class="card-header bg-success text-white">
                <h5 class="mb-0"><i class="bi bi-calendar3"></i> Daftar Jadwal Bel</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover table-bordered">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Hari</th>
                                <th>Jam</th>
                                <th>Kegiatan</th>
                                <th>Audio</th>
                                <th>Status</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            if ($schedules && $schedules->num_rows > 0):
                                $no = 1;
                                while ($row = $schedules->fetch_assoc()): 
                            ?>
                            <tr>
                                <td><?= $no++ ?></td>
                                <td><?= htmlspecialchars($row['hari']) ?></td>
                                <td><?= substr($row['jam'], 0, 5) ?></td>
                                <td><?= htmlspecialchars($row['nama_kegiatan']) ?></td>
                                <td><?= htmlspecialchars($row['audio_file']) ?></td>
                                <td>
                                    <span class="badge <?= $row['aktif'] ? 'bg-success' : 'bg-danger' ?>">
                                        <?= $row['aktif'] ? '<i class="bi bi-check-circle"></i> Aktif' : '<i class="bi bi-x-circle"></i> Nonaktif' ?>
                                    </span>
                                </td>
                                <td>
                                    <!-- Edit Button -->
                                    <button type="button" 
                                            class="btn btn-sm btn-warning" 
                                            onclick="openEditModal(
                                                <?= $row['id'] ?>,
                                                '<?= htmlspecialchars($row['hari'], ENT_QUOTES) ?>',
                                                '<?= substr($row['jam'], 0, 5) ?>',
                                                '<?= htmlspecialchars($row['nama_kegiatan'], ENT_QUOTES) ?>',
                                                '<?= htmlspecialchars($row['audio_file'], ENT_QUOTES) ?>',
                                                <?= $row['aktif'] ?>
                                            )"
                                            title="Edit">
                                        <i class="bi bi-pencil-square"></i> Edit
                                    </button>
                                    
                                    <!-- Delete Button -->
                                    <a href="?delete=<?= $row['id'] ?>" 
                                       class="btn btn-sm btn-danger"
                                       onclick="return confirm('Yakin ingin menghapus jadwal ini?')"
                                       title="Hapus">
                                        <i class="bi bi-trash"></i> Hapus
                                    </a>
                                </td>
                            </tr>
                            <?php 
                                endwhile;
                            else:
                            ?>
                            <tr>
                                <td colspan="7" class="text-center text-muted">
                                    <i class="bi bi-inbox"></i> Belum ada jadwal bel
                                </td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Edit -->
    <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST">
                    <input type="hidden" name="action" value="update">
                    <input type="hidden" name="id" id="edit_id">
                    
                    <div class="modal-header bg-warning">
                        <h5 class="modal-title" id="editModalLabel">
                            <i class="bi bi-pencil-square"></i> Edit Jadwal Bel
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Hari</label>
                            <select name="edit_hari" id="edit_hari" class="form-select" required>
                                <option value="Senin">Senin</option>
                                <option value="Selasa">Selasa</option>
                                <option value="Rabu">Rabu</option>
                                <option value="Kamis">Kamis</option>
                                <option value="Jumat">Jumat</option>
                                <option value="Sabtu">Sabtu</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Jam</label>
                            <input type="time" name="edit_jam" id="edit_jam" class="form-control" required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Nama Kegiatan</label>
                            <input type="text" name="edit_kegiatan" id="edit_kegiatan" class="form-control" required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Audio</label>
                            <select name="edit_audio_file" id="edit_audio_file" class="form-select">
                                <option value="default.mp3">default.mp3</option>
                                <?php 
                                // Reset pointer
                                if ($audios && $audios->num_rows > 0):
                                    $audios->data_seek(0);
                                    while ($audio = $audios->fetch_assoc()): 
                                ?>
                                <option value="<?= htmlspecialchars($audio['file_path']) ?>">
                                    <?= htmlspecialchars($audio['nama_audio']) ?>
                                </option>
                                <?php 
                                    endwhile;
                                endif;
                                ?>
                            </select>
                        </div>
                        
                        <div class="form-check">
                            <input type="checkbox" name="edit_aktif" class="form-check-input" id="edit_aktif">
                            <label class="form-check-label" for="edit_aktif">
                                <strong>Aktif</strong> (Jadwal akan dibunyikan otomatis)
                            </label>
                        </div>
                    </div>
                    
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                            <i class="bi bi-x-circle"></i> Batal
                        </button>
                        <button type="submit" class="btn btn-warning">
                            <i class="bi bi-save"></i> Update
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    // Function to open edit modal and populate with data
    function openEditModal(id, hari, jam, kegiatan, audioFile, aktif) {
        // Set values to form fields
        document.getElementById('edit_id').value = id;
        document.getElementById('edit_hari').value = hari;
        document.getElementById('edit_jam').value = jam;
        document.getElementById('edit_kegiatan').value = kegiatan;
        document.getElementById('edit_audio_file').value = audioFile;
        document.getElementById('edit_aktif').checked = (aktif == 1);
        
        // Show modal
        const editModal = new bootstrap.Modal(document.getElementById('editModal'));
        editModal.show();
    }
    
    // ===== 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('jadwal.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: 'jadwal.php',
            user: '<?= $_SESSION['username'] ?? '' ?>'
        }));
    });
    </script>
</body>
</html>