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

// Handle form submission - CEK DULU APAKAH POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Gunakan null coalescing operator (??) untuk menghindari undefined array key
    $hari = $_POST['hari'] ?? '';
    $jam = $_POST['jam'] ?? '';
    $kegiatan = $_POST['kegiatan'] ?? '';
    $audio = $_POST['audio_file'] ?? 'default.mp3';  // Default value jika kosong
    $aktif = isset($_POST['aktif']) ? 1 : 0;
    
    // Validasi sederhana
    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!";
    }
}

// Delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];  // Sanitasi input
    $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">
</head>
<body>
<div class="container py-4">
    <h2>📋 Kelola Jadwal Bel</h2>
    <a href="index.php" class="btn btn-secondary mb-3">
        <i class="bi bi-arrow-left"></i> Kembali
    </a>
    
    <!-- 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">
                <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>
                                <a href="?delete=<?= $row['id'] ?>" 
                                   class="btn btn-sm btn-danger"
                                   onclick="return confirm('Yakin ingin menghapus jadwal ini?')">
                                    <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>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>