<?php
// File: index.php - Bel Sekolah Otomatis SMAN 1 Bantaran
// Versi: 5.1 (Redesigned - One Screen Layout)
require_once 'config/database.php';
session_start();

// Cek apakah sudah ada interaksi user untuk audio
if (!isset($_SESSION['audio_enabled'])) {
    $_SESSION['audio_enabled'] = false;
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bel Sekolah Otomatis - 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">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        * {
            font-family: 'Inter', sans-serif;
        }
        
        body {
            background: #f0f7ff;
            height: 100vh;
            overflow: hidden;
            position: relative;
        }
        
        /* Education-themed background elements */
        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            height: 8px;
            background: linear-gradient(90deg, #2B5797, #1E3C72, #4A90E2, #2B5797);
            z-index: 1000;
        }
        
        body::after {
            content: '';
            position: fixed;
            bottom: 0;
            right: 0;
            width: 300px;
            height: 300px;
            background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" opacity="0.1"><path fill="%232B5797" d="M50 0 L61 35 L98 35 L68 57 L79 92 L50 70 L21 92 L32 57 L2 35 L39 35 Z"/></svg>');
            background-repeat: repeat;
            pointer-events: none;
            z-index: 0;
        }

        .container-fluid {
            height: 100vh;
            padding: 1rem;
            position: relative;
            z-index: 1;
            display: flex;
            flex-direction: column;
        }

        /* Header Styling - Lebih Compact */
        .header-card {
            background: linear-gradient(135deg, #1e3c72 0%, #2b5797 100%);
            border-radius: 20px;
            padding: 1rem 1.5rem;
            box-shadow: 0 10px 20px -8px rgba(27, 55, 96, 0.3);
            border: 1px solid rgba(255,255,255,0.2);
            backdrop-filter: blur(5px);
            margin-bottom: 1rem;
        }
        
        .header-card h1 {
            font-weight: 700;
            letter-spacing: -0.5px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.2);
            font-size: 1.8rem;
            margin-bottom: 0.2rem;
        }
        
        .header-card h3 {
            font-weight: 300;
            letter-spacing: 1px;
            opacity: 0.95;
            font-size: 1.1rem;
            margin-bottom: 0;
        }
        
        .logo-wrapper {
            background: rgba(255,255,255,0.15);
            border-radius: 15px;
            padding: 0.5rem;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.3);
            width: 60px;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .logo-wrapper i {
            font-size: 2rem;
        }

        /* Clock Display - Lebih Compact */
        .clock-card {
            background: linear-gradient(145deg, #ffffff, #f8faff);
            border-radius: 25px;
            padding: 1.2rem;
            box-shadow: 0 15px 25px -12px rgba(0,20,50,0.2);
            border: 1px solid rgba(255,255,255,0.8);
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }
        
        .clock-display {
            font-size: 3.2rem;
            font-weight: 700;
            color: #1e3c72;
            line-height: 1;
            letter-spacing: 3px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
        }
        
        .date-display {
            font-size: 1rem;
            color: #2b5797;
            font-weight: 500;
            margin-top: 0.3rem;
        }
        
        .status-wrapper {
            background: #e8f0fe;
            border-radius: 40px;
            padding: 0.4rem 1.2rem;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            margin-top: 0.5rem;
            font-size: 0.9rem;
        }
        
        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            display: inline-block;
            position: relative;
        }
        
        .status-indicator::after {
            content: '';
            position: absolute;
            top: -3px;
            left: -3px;
            right: -3px;
            bottom: -3px;
            border-radius: 50%;
            animation: pulse-ring 2s infinite;
        }
        
        .status-active {
            background: #10b981;
        }
        
        .status-active::after {
            border: 2px solid #10b981;
        }
        
        .status-inactive {
            background: #ef4444;
        }
        
        @keyframes pulse-ring {
            0% { transform: scale(0.8); opacity: 0.5; }
            100% { transform: scale(1.5); opacity: 0; }
        }

        /* Next Bell Card - Lebih Compact */
        .next-bell-card {
            background: linear-gradient(145deg, #ffffff, #fafcff);
            border-radius: 25px;
            padding: 1.2rem;
            box-shadow: 0 15px 25px -12px rgba(27, 55, 96, 0.15);
            border: 1px solid rgba(255,255,255,0.8);
            transition: transform 0.3s ease;
            height: 100%;
        }
        
        .next-bell-card:hover {
            transform: translateY(-3px);
        }
        
        .next-bell-label {
            color: #2b5797;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 1px;
            font-size: 0.75rem;
            margin-bottom: 0.5rem;
        }
        
        .next-bell-time {
            font-size: 2.2rem;
            font-weight: 700;
            color: #1e3c72;
            line-height: 1;
            margin-bottom: 0.3rem;
        }
        
        .next-bell-activity {
            font-size: 0.9rem;
            color: #64748b;
            font-weight: 500;
            background: #f1f5f9;
            padding: 0.3rem 1rem;
            border-radius: 40px;
            display: inline-block;
        }
        
        .countdown-wrapper {
            background: #f8fafc;
            border-radius: 15px;
            padding: 0.8rem;
            margin-top: 0.8rem;
            border: 1px solid #e2e8f0;
        }
        
        .progress {
            background: #e2e8f0;
            border-radius: 15px;
            height: 8px !important;
            overflow: hidden;
        }
        
        .progress-bar {
            background: linear-gradient(90deg, #2b5797, #4a90e2);
            border-radius: 15px;
            position: relative;
            overflow: hidden;
        }
        
        .progress-bar::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
            animation: shimmer 2s infinite;
        }
        
        @keyframes shimmer {
            0% { transform: translateX(-100%); }
            100% { transform: translateX(100%); }
        }

        /* Control Panel - Lebih Compact */
        .control-panel {
            background: white;
            border-radius: 25px;
            padding: 1rem 1.5rem;
            box-shadow: 0 10px 20px -8px rgba(27, 55, 96, 0.1);
            border: 1px solid rgba(255,255,255,0.8);
            height: 100%;
            display: flex;
            align-items: center;
        }
        
        .control-panel h4 {
            color: #1e3c72;
            font-weight: 600;
            margin: 0;
            font-size: 1.1rem;
        }
        
        .btn-custom {
            padding: 0.5rem 1rem;
            border-radius: 12px;
            font-weight: 600;
            font-size: 0.85rem;
            transition: all 0.3s ease;
            border: none;
            position: relative;
            overflow: hidden;
        }
        
        .btn-custom::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
            transition: left 0.5s ease;
        }
        
        .btn-custom:hover::before {
            left: 100%;
        }
        
        .btn-custom-primary {
            background: linear-gradient(135deg, #1e3c72, #2b5797);
            color: white;
        }
        
        .btn-custom-success {
            background: linear-gradient(135deg, #059669, #10b981);
            color: white;
        }
        
        .btn-custom-warning {
            background: linear-gradient(135deg, #d97706, #f59e0b);
            color: white;
        }
        
        .btn-custom-info {
            background: linear-gradient(135deg, #0891b2, #06b6d4);
            color: white;
        }
        
        .btn-custom-secondary {
            background: linear-gradient(135deg, #4b5563, #6b7280);
            color: white;
        }

        /* Schedule Table - Scrollable */
        .schedule-card {
            background: white;
            border-radius: 25px;
            box-shadow: 0 15px 25px -12px rgba(27, 55, 96, 0.15);
            border: none;
            overflow: hidden;
            margin-top: 1rem;
            flex: 1;
            display: flex;
            flex-direction: column;
            min-height: 0;
        }
        
        .schedule-card .card-header {
            background: linear-gradient(135deg, #1e3c72, #2b5797);
            padding: 0.8rem 1.5rem;
            border: none;
        }
        
        .schedule-card .card-header h5 {
            margin: 0;
            font-weight: 600;
            color: white;
            font-size: 1rem;
        }
        
        .table-responsive {
            flex: 1;
            overflow-y: auto;
            max-height: calc(100vh - 380px);
        }
        
        .table {
            margin: 0;
        }
        
        .table thead th {
            background: #f8fafc;
            color: #1e3c72;
            font-weight: 600;
            font-size: 0.8rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            padding: 0.8rem 1rem;
            border-bottom: 2px solid #e2e8f0;
            position: sticky;
            top: 0;
            background: #f8fafc;
            z-index: 2;
        }
        
        .table tbody td {
            padding: 0.6rem 1rem;
            vertical-align: middle;
            color: #334155;
            border-bottom: 1px solid #e2e8f0;
            font-size: 0.85rem;
        }
        
        .badge-schedule {
            padding: 0.3rem 0.8rem;
            border-radius: 40px;
            font-weight: 500;
            font-size: 0.7rem;
        }
        
        .btn-test {
            background: #e8f0fe;
            color: #2b5797;
            border-radius: 10px;
            padding: 0.2rem 0.8rem;
            font-size: 0.7rem;
            font-weight: 600;
            border: 1px solid #2b5797;
            transition: all 0.3s ease;
        }
        
        .btn-test:hover {
            background: #2b5797;
            color: white;
        }

        /* Modal Styling */
        .modal-content {
            border-radius: 25px;
            border: none;
            box-shadow: 0 30px 50px -20px rgba(0,0,0,0.3);
        }
        
        .modal-header {
            border-radius: 25px 25px 0 0;
            padding: 1rem 1.5rem;
        }
        
        .modal-header.bg-success {
            background: linear-gradient(135deg, #059669, #10b981) !important;
        }
        
        .modal-header.bg-warning {
            background: linear-gradient(135deg, #d97706, #f59e0b) !important;
        }
        
        .modal-header.bg-info {
            background: linear-gradient(135deg, #0891b2, #06b6d4) !important;
        }
        
        .modal-header.bg-danger {
            background: linear-gradient(135deg, #b91c1c, #ef4444) !important;
        }
        
        .modal-title {
            font-weight: 600;
            font-size: 1.1rem;
        }
        
        .modal-body {
            padding: 1.5rem;
        }
        
        .modal-footer {
            border-top: 1px solid #e2e8f0;
            padding: 1rem;
        }

        /* Toast Styling */
        .toast-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
        }
        
        .toast {
            background: white;
            border: none;
            border-radius: 15px;
            box-shadow: 0 15px 30px -10px rgba(0,0,0,0.2);
            overflow: hidden;
        }
        
        .toast-header {
            border-bottom: 1px solid #e2e8f0;
            padding: 0.8rem 1rem;
        }
        
        .toast-header.bg-success {
            background: linear-gradient(135deg, #059669, #10b981) !important;
        }
        
        .toast-header.bg-warning {
            background: linear-gradient(135deg, #d97706, #f59e0b) !important;
        }
        
        .toast-header.bg-danger {
            background: linear-gradient(135deg, #b91c1c, #ef4444) !important;
        }
        
        .toast-header.bg-primary {
            background: linear-gradient(135deg, #1e3c72, #2b5797) !important;
        }

        /* Grid Layout */
        .row.g-2 {
            margin: -0.25rem;
        }
        
        .row.g-2 > [class*="col-"] {
            padding: 0.25rem;
        }

        /* Height Management */
        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            min-height: 0;
        }
    </style>
</head>
<body>
<!-- Toast Notification Container -->
<div class="toast-container">
    <div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="toast-header">
            <i class="bi me-2" id="toastIcon"></i>
            <strong class="me-auto" id="toastTitle">Notifikasi</strong>
            <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
        <div class="toast-body" id="toastMessage">
            Pesan notifikasi
        </div>
    </div>
</div>

<div class="container-fluid">
    <!-- Header -->
    <div class="header-card text-white">
        <div class="row align-items-center">
            <div class="col-auto">
                <div class="logo-wrapper">
                    <i class="bi bi-mortarboard-fill"></i>
                </div>
            </div>
            <div class="col">
                <h1 class="fw-bold">🔔 BEL SEKOLAH OTOMATIS</h1>
                <h3 class="fw-light">SMAN 1 BANTARAN</h3>
            </div>
            <div class="col-auto">
                <span class="badge bg-white text-primary px-3 py-2">Sistem Informasi Bel Digital</span>
            </div>
        </div>
    </div>

    <!-- Main Content - Semua dalam satu layar -->
    <div class="main-content">
        <!-- Row 1: Clock, Next Bell, Control Panel -->
        <div class="row g-2 mb-2">
            <!-- Clock Card -->
            <div class="col-md-4">
                <div class="clock-card">
                    <div class="clock-display" id="clock">00:00:00</div>
                    <div class="date-display" id="date">Senin, 1 Jan 2026</div>
                    <div class="status-wrapper">
                        <span class="status-indicator status-active" id="systemStatus"></span>
                        <span class="fw-semibold" id="systemStatusText">Sistem Bel Aktif</span>
                        <span> 
                            <button class="btn btn-custom btn-custom-success" id="btnEnable" onclick="enableAudio()">
                            <i class="bi bi-volume-up"></i> Aktifkan Audio
                            </button>
                        </span>
                    </div>
                </div>
            </div>

            <!-- Next Bell Card -->
            <div class="col-md-5">
                <div class="next-bell-card">
                    <div class="next-bell-label">
                        <i class="bi bi-bell-fill me-1"></i>JADWAL BEL BERIKUTNYA
                    </div>
                    <div class="d-flex align-items-center justify-content-between">
                        <div>
                            <div class="next-bell-time" id="nextBellTime">--:--</div>
                            <div class="next-bell-activity" id="nextBellActivity">-</div>
                        </div>
                        <div class="text-end">
                            <i class="bi bi-hourglass-split text-primary" style="font-size: 2rem; opacity: 0.5;"></i>
                        </div>
                    </div>
                    
                    <div class="countdown-wrapper">
                        <div class="d-flex justify-content-between align-items-center mb-1">
                            <span class="text-muted small">Countdown:</span>
                            <span class="fw-bold text-primary small" id="countdownText">Memuat...</span>
                        </div>
                        <div class="progress">
                            <div class="progress-bar progress-bar-striped" 
                                 id="countdownBar" style="width: 100%"></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Control Panel -->
            <div class="col-md-3">
                <div class="control-panel">
                    <div class="w-100">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <h4><i class="bi bi-sliders2 me-1"></i>Panel Kontrol</h4>
                            <div>
                                <!-- <button class="btn btn-custom btn-custom-success btn-sm" id="btnEnable" onclick="enableAudio()">
                                    <i class="bi bi-volume-up"></i>
                                </button> -->
                                <button class="btn btn-custom btn-custom-warning btn-sm" id="btnMute" onclick="toggleMute()">
                                    <i class="bi bi-volume-mute"> Mute</i>
                                </button>
                            </div>
                        </div>
                        
                        <div class="row g-1">
                            <div class="col-4">
                                <a href="jadwal.php" class="btn btn-custom btn-custom-primary w-100 btn-sm">
                                    <i class="bi bi-calendar3"></i>
                                    <small>Jadwal</small>
                                </a>
                            </div>
                            <div class="col-4">
                                <a href="audio.php" class="btn btn-custom btn-custom-info w-100 btn-sm">
                                    <i class="bi bi-music-note"></i>
                                    <small>Audio</small>
                                </a>
                            </div>
                            <div class="col-4">
                                <a href="log.php" class="btn btn-custom btn-custom-secondary w-100 btn-sm">
                                    <i class="bi bi-journal-text"></i>
                                    <small>Log</small>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Row 2: Today Schedule (Full Width) -->
        <div class="row g-2">
            <div class="col-12">
                <div class="schedule-card">
                    <div class="card-header">
                        <h5><i class="bi bi-calendar-check me-2"></i>Jadwal Bel Hari Ini</h5>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-hover mb-0" id="todaySchedule">
                            <thead>
                                <tr>
                                    <th>Jam</th>
                                    <th>Kegiatan</th>
                                    <th>File Audio</th>
                                    <th>Status</th>
                                    <th>Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr><td colspan="5" class="text-center py-4 text-muted">Memuat jadwal...</td></tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Audio Element -->
<audio id="bellAudio" preload="auto">
    <source src="" type="audio/mpeg">
    Browser Anda tidak mendukung audio element.
</audio>

<!-- Bootstrap Modals -->
<!-- Confirmation Modal -->
<div class="modal fade" id="confirmModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-warning text-white">
                <h5 class="modal-title"><i class="bi bi-exclamation-triangle me-2"></i>Konfirmasi</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p class="fs-5" id="confirmMessage">Apakah Anda yakin?</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Batal</button>
                <button type="button" class="btn btn-warning text-white" id="confirmAction">Ya, Lanjutkan</button>
            </div>
        </div>
    </div>
</div>

<!-- Success Modal -->
<div class="modal fade" id="successModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title"><i class="bi bi-check-circle me-2"></i>Berhasil!</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body text-center py-4">
                <i class="bi bi-check-circle-fill text-success display-1"></i>
                <h5 class="mt-3" id="successMessage">Operasi berhasil!</h5>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-success" data-bs-dismiss="modal">OK</button>
            </div>
        </div>
    </div>
</div>

<!-- Info Modal -->
<div class="modal fade" id="infoModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-info text-white">
                <h5 class="modal-title"><i class="bi bi-info-circle me-2"></i>Informasi</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p class="fs-5" id="infoMessage">Informasi sistem</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-info text-white" data-bs-dismiss="modal">OK</button>
            </div>
        </div>
    </div>
</div>

<!-- Error Modal -->
<div class="modal fade" id="errorModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title"><i class="bi bi-exclamation-octagon me-2"></i>Error</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p class="fs-5" id="errorMessage">Terjadi kesalahan</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Tutup</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// ===== GLOBAL VARIABLES (TIDAK DIUBAH) =====
let audioEnabled = false;
let isMuted = false;
let currentAudio = '';
let nextBellData = null;
let audioElement = document.getElementById('bellAudio');
let audioContext = null;
let pendingAction = null;

// ===== TOAST NOTIFICATION =====
function showToast(title, message, type = 'info') {
    const toast = document.getElementById('liveToast');
    const toastTitle = document.getElementById('toastTitle');
    const toastMessage = document.getElementById('toastMessage');
    const toastIcon = document.getElementById('toastIcon');
    const toastHeader = toast.querySelector('.toast-header');
    
    switch(type) {
        case 'success':
            toastIcon.className = 'bi bi-check-circle-fill me-2 text-success';
            toastHeader.className = 'toast-header bg-success text-white';
            break;
        case 'warning':
            toastIcon.className = 'bi bi-exclamation-triangle-fill me-2 text-warning';
            toastHeader.className = 'toast-header bg-warning text-white';
            break;
        case 'error':
            toastIcon.className = 'bi bi-x-circle-fill me-2 text-danger';
            toastHeader.className = 'toast-header bg-danger text-white';
            break;
        default:
            toastIcon.className = 'bi bi-bell-fill me-2 text-primary';
            toastHeader.className = 'toast-header bg-primary text-white';
    }
    
    toastTitle.textContent = title;
    toastMessage.textContent = message;
    
    const bsToast = new bootstrap.Toast(toast);
    bsToast.show();
}

// ===== CONFIRMATION MODAL =====
function showConfirmModal(message, onConfirm) {
    document.getElementById('confirmMessage').textContent = message;
    const confirmBtn = document.getElementById('confirmAction');
    
    const newBtn = confirmBtn.cloneNode(true);
    confirmBtn.parentNode.replaceChild(newBtn, confirmBtn);
    
    newBtn.addEventListener('click', function() {
        onConfirm();
        bootstrap.Modal.getInstance(document.getElementById('confirmModal')).hide();
    });
    
    const modal = new bootstrap.Modal(document.getElementById('confirmModal'));
    modal.show();
}

// ===== SUCCESS MODAL =====
function showSuccessModal(message) {
    document.getElementById('successMessage').textContent = message;
    const modal = new bootstrap.Modal(document.getElementById('successModal'));
    modal.show();
}

// ===== INFO MODAL =====
function showInfoModal(message) {
    document.getElementById('infoMessage').textContent = message;
    const modal = new bootstrap.Modal(document.getElementById('infoModal'));
    modal.show();
}

// ===== ERROR MODAL =====
function showErrorModal(message) {
    document.getElementById('errorMessage').textContent = message;
    const modal = new bootstrap.Modal(document.getElementById('errorModal'));
    modal.show();
}

// ===== INITIALIZATION =====
document.addEventListener('DOMContentLoaded', function() {
    audioElement.addEventListener('canplaythrough', function() {
        console.log('✅ Audio ready to play');
    });
    
    audioElement.addEventListener('error', function(e) {
        console.error('❌ Audio error:', e);
    });
    
    setInterval(updateClock, 1000);
    updateClock();
    loadTodaySchedule();
});

// ===== UPDATE JAM DIGITAL =====
function updateClock() {
    const now = new Date();
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    document.getElementById('clock').textContent = `${hours}:${minutes}:${seconds}`;
    
    const days = ['Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'];
    const months = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Agu','Sep','Okt','Nov','Des'];
    document.getElementById('date').textContent = `${days[now.getDay()]}, ${now.getDate()} ${months[now.getMonth()]} ${now.getFullYear()}`;
    
    checkBellTime(now);
    updateNextBell(now);
}

// ===== CEK WAKTU BEL =====
function checkBellTime(now) {
    const currentTime = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:00`;
    const currentDay = ['Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'][now.getDay()];
    
    fetch(`api/get_jadwal.php?hari=${currentDay}&jam=${currentTime}`)
        .then(response => response.json())
        .then(data => {
            if (data.found && !data.already_rung) {
                if (audioEnabled && !isMuted) {
                    playBell(data.audio_file);
                    logBell(data.kegiatan, 'Berhasil');
                }
            }
        })
        .catch(error => {
            console.error('❌ Check bell time error:', error);
        });
}

// ===== UPDATE INFORMASI BEL BERIKUTNYA =====
function updateNextBell(now) {
    const currentDay = ['Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'][now.getDay()];
    
    fetch(`api/get_next_bel.php?hari=${currentDay}`)
        .then(response => response.json())
        .then(data => {
            if (data.found) {
                nextBellData = data;
                document.getElementById('nextBellTime').textContent = data.jam;
                document.getElementById('nextBellActivity').textContent = data.kegiatan;
                
                const [hours, minutes] = data.jam.split(':');
                const bellTime = new Date();
                bellTime.setHours(parseInt(hours), parseInt(minutes), 0);
                
                const diff = bellTime - now;
                if (diff > 0) {
                    const minutesLeft = Math.floor(diff / 60000);
                    const secondsLeft = Math.floor((diff % 60000) / 1000);
                    document.getElementById('countdownText').textContent = 
                        `${minutesLeft}m ${secondsLeft}s lagi`;
                    
                    const totalMinutes = 10;
                    const percentage = 100 - (diff / (totalMinutes * 60000)) * 100;
                    document.getElementById('countdownBar').style.width = 
                        `${Math.max(0, Math.min(100, percentage))}%`;
                } else {
                    document.getElementById('countdownText').textContent = 'Segera berbunyi';
                    document.getElementById('countdownBar').style.width = '100%';
                }
            } else {
                document.getElementById('nextBellTime').textContent = '--:--';
                document.getElementById('nextBellActivity').textContent = 'Tidak ada jadwal';
                document.getElementById('countdownText').textContent = 'Tidak ada jadwal';
                document.getElementById('countdownBar').style.width = '0%';
            }
        })
        .catch(error => {
            console.error('❌ Update next bell error:', error);
            document.getElementById('countdownText').textContent = 'Gagal memuat';
        });
}

// ===== PLAY BELL =====
function playBell(audioFile) {
    const audio = document.getElementById('bellAudio');
    
    audio.pause();
    audio.currentTime = 0;
    
    audio.src = `audio/${audioFile}?t=${new Date().getTime()}`;
    audio.load();
    
    audio.volume = 1.0;
    
    const playPromise = audio.play();
    
    if (playPromise !== undefined) {
        playPromise.then(() => {
            console.log('✅ Playing:', audioFile);
            logBell(audioFile, 'Berhasil');
        })
        .catch(error => {
            console.error('❌ Audio play failed:', error);
            if (audioFile !== 'default.mp3') {
                audio.src = 'audio/default.mp3?t=' + new Date().getTime();
                audio.load();
                audio.play().catch(e => console.error('❌ Fallback failed:', e));
            }
        });
    }
}

// ===== ENABLE AUDIO =====
function enableAudio() {
    audioEnabled = true;
    document.getElementById('btnEnable').disabled = true;
    document.getElementById('btnEnable').innerHTML = '<i class="bi bi-check-circle"> Audio Aktif</i>';
    document.getElementById('systemStatus').className = 'status-indicator status-active';
    document.getElementById('systemStatusText').textContent = 'Sistem Bel Aktif';
    
    const audio = document.getElementById('bellAudio');
    audio.volume = 0.5;
    
    const playPromise = audio.play();
    
    if (playPromise !== undefined) {
        playPromise.then(() => {
            console.log('✅ Audio context unlocked');
            audio.pause();
            audio.currentTime = 0;
            showToast('Audio Diaktifkan', 'Sistem bel sekolah siap digunakan', 'success');
        })
        .catch(error => {
            console.error('⚠️ Autoplay prevented:', error);
            showToast('Audio Diaktifkan', 'Klik tombol Test untuk memastikan suara berfungsi', 'info');
        });
    }
}

// ===== TOGGLE MUTE =====
function toggleMute() {
    isMuted = !isMuted;
    const btn = document.getElementById('btnMute');
    const audio = document.getElementById('bellAudio');
    
    if (isMuted) {
        btn.innerHTML = '<i class="bi bi-volume-off"> Muted</i>';
        btn.className = 'btn btn-custom btn-custom-secondary btn-sm';
        audio.volume = 0;
        showToast('Mute Aktif', 'Suara bel dimatikan sementara', 'warning');
    } else {
        btn.innerHTML = '<i class="bi bi-volume-mute"> Mute</i>';
        btn.className = 'btn btn-custom btn-custom-warning btn-sm';
        audio.volume = 1.0;
        showToast('Mute Nonaktif', 'Suara bel diaktifkan kembali', 'success');
    }
}

// ===== BEL MANUAL =====
function showRingNowModal() {
    if (!audioEnabled) {
        showInfoModal('⚠️ Klik "Aktifkan Audio" terlebih dahulu!');
        enableAudio();
        return;
    }
    
    showConfirmModal('🔔 Apakah Anda yakin ingin membunyikan bel manual?', function() {
        playBell('default.mp3');
        logBell('Bel Manual', 'Berhasil');
        showToast('Bel Manual', 'Bel berbunyi atas permintaan manual', 'success');
    });
}

// ===== TEST AUDIO =====
function showTestAudioModal() {
    if (!audioEnabled) {
        showInfoModal('⚠️ Klik "Aktifkan Audio" terlebih dahulu!');
        enableAudio();
        return;
    }
    
    showConfirmModal('🔊 Test Audio akan membunyikan bel default. Lanjutkan?', function() {
        playBell('default.mp3');
        showToast('Test Audio', 'Audio test berhasil diputar', 'success');
    });
}

// ===== TEST AUDIO UNTUK JADWAL =====
function testScheduleAudio(audioFile) {
    if (!audioEnabled) {
        showInfoModal('⚠️ Klik "Aktifkan Audio" terlebih dahulu!');
        enableAudio();
        setTimeout(() => {
            showConfirmModal(`🔊 Test audio: ${audioFile}. Lanjutkan?`, function() {
                playBell(audioFile);
            });
        }, 500);
        return;
    }
    
    showConfirmModal(`🔊 Test audio: ${audioFile}. Lanjutkan?`, function() {
        playBell(audioFile);
    });
}

// ===== LOG AKTIVITAS BEL =====
function logBell(kegiatan, status) {
    fetch('api/log_bel.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({kegiatan, status})
    })
    .then(response => response.json())
    .then(data => {
        console.log('✅ Log saved:', data);
    })
    .catch(error => {
        console.error('❌ Log bell error:', error);
    });
}

// ===== LOAD JADWAL HARI INI =====
function loadTodaySchedule() {
    const currentDay = ['Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'][new Date().getDay()];
    
    fetch(`api/get_jadwal_hari.php?hari=${currentDay}`)
        .then(response => response.json())
        .then(data => {
            const tbody = document.querySelector('#todaySchedule tbody');
            if (data && data.length > 0) {
                tbody.innerHTML = data.map(item => `
                    <tr>
                        <td><span class="fw-semibold">${item.jam}</span></td>
                        <td>${item.kegiatan}</td>
                        <td><code>${item.audio_file}</code></td>
                        <td>
                            <span class="badge-schedule ${item.aktif ? 'bg-success' : 'bg-danger'}">
                                ${item.aktif ? 'Aktif' : 'Nonaktif'}
                            </span>
                        </td>
                        <td>
                            <button class="btn-test" 
                                    onclick="testScheduleAudio('${item.audio_file}')">
                                <i class="bi bi-play-fill me-1"></i>Test
                            </button>
                        </td>
                    </tr>
                `).join('');
            } else {
                tbody.innerHTML = '<tr><td colspan="5" class="text-center py-4 text-muted">Tidak ada jadwal bel hari ini</td></tr>';
            }
        })
        .catch(error => {
            console.error('❌ Load schedule error:', error);
            const tbody = document.querySelector('#todaySchedule tbody');
            tbody.innerHTML = '<tr><td colspan="5" class="text-center py-4 text-danger">Gagal memuat jadwal. Periksa koneksi API.</td></tr>';
        });
}
</script>
</body>
</html>