<?php 
include 'koneksi.php';
cek_akses(['Guru']);

// Ambil daftar kelas di unit guru
$kelas_list = mysqli_query($conn, "SELECT * FROM classes WHERE unit='{$_SESSION['unit']}' ORDER BY name");

// Daftar mata pelajaran berdasarkan unit
$mata_pelajaran_list = [];
if($_SESSION['unit'] == 'Madrasah Ibtidaiyah') {
    $mata_pelajaran_list = ['Matematika', 'Bahasa Indonesia', 'IPA', 'IPS', 'Bahasa Inggris', 'Pendidikan Agama Islam', 'PKN', 'SBdP', 'Penjaskes', 'Bahasa Arab', 'Al-Qur\'an Hadits', 'Fikih', 'SKI', 'Aqidah Akhlak'];
} elseif($_SESSION['unit'] == 'Madrasah Tsanawiyah') {
    $mata_pelajaran_list = ['Matematika', 'Bahasa Indonesia', 'IPA', 'IPS', 'Bahasa Inggris', 'Pendidikan Agama Islam', 'PKN', 'Penjaskes', 'Bahasa Arab', 'Al-Qur\'an Hadits', 'Fikih', 'SKI', 'Aqidah Akhlak', 'TIK', 'Prakarya'];
} elseif($_SESSION['unit'] == 'Madrasah Aliyah') {
    $mata_pelajaran_list = ['Matematika', 'Bahasa Indonesia', 'Bahasa Inggris', 'Pendidikan Agama Islam', 'PKN', 'Penjaskes', 'Bahasa Arab', 'Al-Qur\'an Hadits', 'Fikih', 'SKI', 'Aqidah Akhlak', 'TIK', 'Fisika', 'Kimia', 'Biologi', 'Ekonomi', 'Sosiologi', 'Geografi', 'Sejarah', 'Seni Budaya'];
} elseif($_SESSION['unit'] == 'Istiqlal Boarding School') {
    $mata_pelajaran_list = ['Matematika', 'Bahasa Indonesia', 'Bahasa Inggris', 'Pendidikan Agama Islam', 'PKN', 'Penjaskes', 'Bahasa Arab', 'Al-Qur\'an Hadits', 'Fikih', 'SKI', 'Aqidah Akhlak', 'Tahfidz', 'Kitab Kuning', 'TIK', 'Fisika', 'Kimia', 'Biologi'];
} else {
    $mata_pelajaran_list = ['Matematika', 'Bahasa Indonesia', 'IPA', 'IPS', 'Bahasa Inggris', 'Pendidikan Agama Islam', 'PKN', 'SBdP', 'Penjaskes'];
}

// Proses simpan jurnal
if(isset($_POST['simpan'])) {
    $tanggal = mysqli_real_escape_string($conn, $_POST['tanggal']);
    $jam_ke = mysqli_real_escape_string($conn, $_POST['jam_ke']);
    $class_id = $_POST['class_id'];
    $mata_pelajaran = mysqli_real_escape_string($conn, $_POST['mata_pelajaran']);
    $jenis_materi = mysqli_real_escape_string($conn, $_POST['jenis_materi']);
    $link_url = mysqli_real_escape_string($conn, $_POST['link_url']);
    $deskripsi = mysqli_real_escape_string($conn, $_POST['deskripsi']);
    $keterangan_target = mysqli_real_escape_string($conn, $_POST['keterangan_target']);
    
    $query = "INSERT INTO teaching_journals (
        teacher_id, class_id, subject, date, material, notes, 
        jam_ke, jenis_materi, link_url, keterangan_target
    ) VALUES (
        '{$_SESSION['user_id']}', '$class_id', '$mata_pelajaran', '$tanggal', '$deskripsi', '$deskripsi',
        '$jam_ke', '$jenis_materi', '$link_url', '$keterangan_target'
    )";
    
    if(mysqli_query($conn, $query)) {
        echo "<script>alert('Jurnal berhasil disimpan!'); window.location='jurnal_mengajar.php';</script>";
    } else {
        echo "<script>alert('Gagal menyimpan: " . mysqli_error($conn) . "');</script>";
    }
}

// Ambil data jurnal untuk ditampilkan
$jurnals = mysqli_query($conn, "SELECT tj.*, c.name as class_name 
    FROM teaching_journals tj 
    JOIN classes c ON tj.class_id = c.id 
    WHERE tj.teacher_id='{$_SESSION['user_id']}' 
    ORDER BY tj.date DESC, tj.jam_ke ASC");
?>

<!DOCTYPE html>
<html>
<head>
    <title>Jurnal Mengajar - SIM ISTIQLAL</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/theme-istiqlal-green.css">
    <style>
        .content-wrapper { background: #f1f5f9; }
        .card { border-radius: 20px; box-shadow: 0 5px 20px rgba(0,0,0,0.08); }
        .form-label { font-weight: 600; font-size: 0.85rem; color: #1e293b; margin-bottom: 0.5rem; }
        .required:after { content: " *"; color: red; }
        .badge-materi { font-size: 0.7rem; padding: 4px 8px; border-radius: 20px; }
        .target-preview { max-width: 250px; word-wrap: break-word; white-space: normal; font-size: 0.85rem; }
        .form-control:focus { border-color: #0b5e4e; box-shadow: 0 0 0 3px rgba(11,94,78,0.1); outline: none; }
        .table tbody tr:hover { background-color: #f8fafc; transition: all 0.3s ease; }
        .modal-header { background: linear-gradient(135deg, #0b5e4e 0%, #10b981 100%); color: white; }
        .btn-detail { background: #0b5e4e; color: white; border: none; padding: 5px 12px; border-radius: 6px; }
        .btn-detail:hover { background: #10b981; }
        .card-header-green { background: linear-gradient(135deg, #0b5e4e 0%, #10b981 100%); color: white; }
        .btn-save-green { background: linear-gradient(135deg, #0b5e4e 0%, #10b981 100%); border: none; color: white; }
        .btn-save-green:hover { transform: translateY(-2px); }
    </style>
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
    <?php include 'sidebar.php'; ?>
    
    <div class="content-wrapper">
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0 font-weight-bold">
                            <i class="fas fa-book-open text-primary"></i> Jurnal Mengajar
                        </h1>
                        <small class="text-muted">Catatan kegiatan pembelajaran harian</small>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
                            <li class="breadcrumb-item active">Jurnal Mengajar</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <div class="content">
            <div class="container-fluid">
                <div class="row">
                    <!-- Form Input Jurnal -->
                    <div class="col-md-5">
                        <div class="card card-primary">
                            <div class="card-header card-header-green">
                                <h4><i class="fas fa-edit"></i> Form Jurnal Mengajar</h4>
                            </div>
                            <div class="card-body">
                                <form method="POST">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="required">Hari/Tanggal</label>
                                                <input type="date" name="tanggal" class="form-control" value="<?= date('Y-m-d') ?>" required>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="required">Jam ke-</label>
                                                <select name="jam_ke" class="form-control" required>
                                                    <option value="">Pilih Jam ke-</option>
                                                    <?php for($i=1; $i<=10; $i++): ?>
                                                    <option value="<?= $i ?>">Jam ke-<?= $i ?></option>
                                                    <?php endfor; ?>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="required">Kelas</label>
                                                <select name="class_id" class="form-control" required>
                                                    <option value="">-- Pilih Kelas --</option>
                                                    <?php while($kelas = mysqli_fetch_assoc($kelas_list)): ?>
                                                    <option value="<?= $kelas['id'] ?>"><?= $kelas['name'] ?></option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="required">Mata Pelajaran</label>
                                                <select name="mata_pelajaran" class="form-control" required>
                                                    <option value="">-- Pilih Mata Pelajaran --</option>
                                                    <?php foreach($mata_pelajaran_list as $mapel): ?>
                                                    <option value="<?= $mapel ?>"><?= $mapel ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label class="required">Jenis Materi</label>
                                        <select name="jenis_materi" class="form-control" required>
                                            <option value="">-- Pilih Jenis Materi --</option>
                                            <option value="RPP">📋 Rencana Pelaksanaan Pembelajaran (RPP)</option>
                                            <option value="Modul Ajar">📘 Modul Ajar</option>
                                            <option value="Video Pembelajaran">🎥 Video Pembelajaran</option>
                                            <option value="Presentasi">📊 Presentasi</option>
                                            <option value="LKS">📝 LKS (Lembar Kerja Siswa)</option>
                                            <option value="Quiz">❓ Quiz / Evaluasi</option>
                                            <option value="Praktikum">🔬 Praktikum</option>
                                            <option value="Diskusi">💬 Diskusi Kelompok</option>
                                            <option value="Lainnya">📌 Lainnya</option>
                                        </select>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label>Link URL Materi</label>
                                        <input type="url" name="link_url" class="form-control" placeholder="https://drive.google.com/... atau https://youtube.com/...">
                                        <small class="text-muted">Opsional: link ke Google Drive, YouTube, atau sumber belajar lainnya</small>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label class="required">Deskripsi / Catatan</label>
                                        <textarea name="deskripsi" class="form-control" rows="3" placeholder="Isi dengan materi yang diajarkan, kegiatan pembelajaran, dan catatan penting" required></textarea>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label class="required">Keterangan Pencapaian Target</label>
                                        <textarea name="keterangan_target" class="form-control" rows="4" placeholder="Isikan keterangan pencapaian target pembelajaran, contoh:
- 85% siswa sudah mencapai KKM (75)
- Masih ada 5 siswa yang perlu remedial
- Pembelajaran berjalan lancar dan kondusif
- Target pembelajaran tercapai sesuai rencana
- Perlu pengulangan pada pertemuan berikutnya" required></textarea>
                                        <small class="text-muted">Isi secara manual sesuai dengan kondisi di kelas</small>
                                    </div>
                                    
                                    <div class="form-group text-center">
                                        <button type="submit" name="simpan" class="btn btn-save-green btn-lg btn-block">
                                            <i class="fas fa-save"></i> Simpan Jurnal
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <!-- Daftar Jurnal -->
                    <div class="col-md-7">
                        <div class="card">
                            <div class="card-header card-header-green d-flex justify-content-between align-items-center">
                                <h4><i class="fas fa-history"></i> Riwayat Jurnal Mengajar</h4>
                                <span class="badge bg-light text-dark">Total: <?= mysqli_num_rows($jurnals) ?> Jurnal</span>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-bordered table-striped table-hover" id="tabelJurnal">
                                        <thead style="background: linear-gradient(135deg, #0b5e4e 0%, #10b981 100%); color: white;">
                                            <tr>
                                                <th width="8%">Tanggal</th>
                                                <th width="5%">Jam</th>
                                                <th width="10%">Kelas</th>
                                                <th width="12%">Mapel</th>
                                                <th width="12%">Jenis Materi</th>
                                                <th width="10%">Link</th>
                                                <th width="28%">Pencapaian Target</th>
                                                <th width="15%">Aksi</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if(mysqli_num_rows($jurnals) > 0): ?>
                                                <?php while($row = mysqli_fetch_assoc($jurnals)): ?>
                                                <tr>
                                                    <td><?= date('d-m-Y', strtotime($row['date'])) ?></td>
                                                    <td><span class="badge badge-success"><?= $row['jam_ke'] ?></span></td>
                                                    <td><?= $row['class_name'] ?></td>
                                                    <td><strong><?= $row['subject'] ?></strong></td>
                                                    <td>
                                                        <span class="badge badge-materi bg-success text-white">
                                                            <?= $row['jenis_materi'] ?>
                                                        </span>
                                                      </td>
                                                    <td>
                                                        <?php if($row['link_url']): ?>
                                                            <a href="<?= $row['link_url'] ?>" target="_blank" title="<?= $row['link_url'] ?>">
                                                                <i class="fas fa-external-link-alt"></i> Link
                                                            </a>
                                                        <?php else: ?>
                                                            <span class="text-muted">-</span>
                                                        <?php endif; ?>
                                                      </td>
                                                    <td>
                                                        <div class="target-preview">
                                                            <?= nl2br(htmlspecialchars(substr($row['keterangan_target'], 0, 100))) ?>
                                                            <?php if(strlen($row['keterangan_target']) > 100): ?>...<?php endif; ?>
                                                        </div>
                                                      </td>
                                                    <td>
                                                        <button class="btn btn-sm btn-detail" onclick="showDetail(<?= htmlspecialchars(json_encode($row)) ?>)">
                                                            <i class="fas fa-eye"></i> Detail
                                                        </button>
                                                      </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            <?php else: ?>
                                                <tr>
                                                    <td colspan="8" class="text-center text-muted">
                                                        <i class="fas fa-inbox fa-3x"></i>
                                                        <br>Belum ada jurnal mengajar
                                                        <br><small>Silakan isi jurnal mengajar melalui form di samping</small>
                                                     </td>
                                                </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <footer class="main-footer">
        <strong>&copy; <?= date('Y') ?> SIM ISTIQLAL - Sistem Administrasi Guru</strong>
    </footer>
</div>

<!-- Modal Detail Jurnal -->
<div class="modal fade" id="modalDetailJurnal" tabindex="-1" aria-labelledby="modalDetailJurnalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalDetailJurnalLabel">
                    <i class="fas fa-book-open"></i> Detail Jurnal Mengajar
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="detailContent">
                <!-- Isi dari JavaScript -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/js/adminlte.min.js"></script>

<script>
function showDetail(data) {
    // Format tanggal
    var tanggal = new Date(data.date);
    var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
    var tanggalFormatted = tanggal.toLocaleDateString('id-ID', options);
    
    var linkHtml = data.link_url ? 
        `<a href="${data.link_url}" target="_blank">${data.link_url}</a>` : 
        '<span class="text-muted">-</span>';
    
    var targetHtml = data.keterangan_target ? 
        data.keterangan_target.replace(/\n/g, '<br>') : 
        '-';
    
    var deskripsiHtml = (data.material || data.notes || '<i>Tidak ada catatan</i>').replace(/\n/g, '<br>');
    
    var html = `
        <div class="row">
            <div class="col-md-6">
                <table class="table table-borderless">
                    <tr><th width="40%"><i class="fas fa-calendar"></i> Hari/Tanggal</th><td>: ${tanggalFormatted}</td></tr>
                    <tr><th><i class="fas fa-clock"></i> Jam ke-</th><td>: ${data.jam_ke}</td></tr>
                    <tr><th><i class="fas fa-school"></i> Kelas</th><td>: ${data.class_name}</td></tr>
                    <tr><th><i class="fas fa-chalkboard"></i> Mata Pelajaran</th><td>: <strong>${data.subject}</strong></td></tr>
                </table>
            </div>
            <div class="col-md-6">
                <table class="table table-borderless">
                    <tr><th width="40%"><i class="fas fa-tag"></i> Jenis Materi</th><td>: <span class="badge bg-success">${data.jenis_materi}</span></td></tr>
                    <tr><th><i class="fas fa-link"></i> Link Materi</th><td>: ${linkHtml}</td></tr>
                    <tr><th><i class="fas fa-chart-line"></i> Pencapaian Target</th><td>: <div style="white-space: normal;">${targetHtml}</div></td></tr>
                </table>
            </div>
        </div>
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header bg-light">
                        <strong><i class="fas fa-align-left"></i> Deskripsi / Catatan</strong>
                    </div>
                    <div class="card-body">
                        ${deskripsiHtml}
                    </div>
                </div>
            </div>
        </div>
    `;
    
    document.getElementById('detailContent').innerHTML = html;
    
    // Tampilkan modal menggunakan Bootstrap 5
    var modal = new bootstrap.Modal(document.getElementById('modalDetailJurnal'), {
        backdrop: true,
        keyboard: true
    });
    modal.show();
}
</script>

</body>
</html>