<?php
session_start();
include 'config.php';

if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'wali_kelas') {
    header("Location: index.php");
    exit;
}

$username = $_SESSION['username'];

// Ambil data wali kelas
$qWaliKelas = mysqli_query($conn, "SELECT kelas, nama_wali FROM wali_kelas WHERE nip_wali='$username'");
if (!$qWaliKelas || mysqli_num_rows($qWaliKelas) === 0) {
    die("Data wali kelas tidak ditemukan.");
}
$wali_kelas = mysqli_fetch_assoc($qWaliKelas);
$kelas_diampu = $wali_kelas['kelas'];

// Handle form actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['approve_bimbingan'])) {
        $bimbingan_id = intval($_POST['bimbingan_id']);
        $query = "UPDATE bimbingan_konseling SET status = 'approved' WHERE id = $bimbingan_id";
        if (mysqli_query($conn, $query)) {
            $success = "Sesi bimbingan disetujui!";
        } else {
            $error = "Gagal menyetujui bimbingan: " . mysqli_error($conn);
        }
    } elseif (isset($_POST['reject_bimbingan'])) {
        $bimbingan_id = intval($_POST['bimbingan_id']);
        $alasan_penolakan = mysqli_real_escape_string($conn, $_POST['alasan_penolakan']);
        $query = "UPDATE bimbingan_konseling SET status = 'rejected', catatan_guru = '$alasan_penolakan' WHERE id = $bimbingan_id";
        if (mysqli_query($conn, $query)) {
            $success = "Bimbingan ditolak!";
        } else {
            $error = "Gagal menolak bimbingan: " . mysqli_error($conn);
        }
    } elseif (isset($_POST['complete_bimbingan'])) {
        $bimbingan_id = intval($_POST['bimbingan_id']);
        $catatan_guru = mysqli_real_escape_string($conn, $_POST['catatan_guru']);
        $query = "UPDATE bimbingan_konseling SET status = 'completed', catatan_guru = '$catatan_guru' WHERE id = $bimbingan_id";
        if (mysqli_query($conn, $query)) {
            $success = "Sesi bimbingan diselesaikan!";
        } else {
            $error = "Gagal menyelesaikan bimbingan: " . mysqli_error($conn);
        }
    }
}

// Ambil daftar bimbingan pending
$qBimbinganPending = mysqli_query($conn, "
    SELECT bk.*, s.nama as siswa_nama, s.nis 
    FROM bimbingan_konseling bk 
    JOIN siswa s ON bk.siswa_id = s.id 
    WHERE s.kelas = '$kelas_diampu' 
    AND bk.status = 'pending'
    ORDER BY bk.created_at DESC
");

$bimbingan_pending = [];
if ($qBimbinganPending) {
    while ($row = mysqli_fetch_assoc($qBimbinganPending)) {
        $bimbingan_pending[] = $row;
    }
}

// Ambil riwayat bimbingan
$qBimbinganRiwayat = mysqli_query($conn, "
    SELECT bk.*, s.nama as siswa_nama, s.nis 
    FROM bimbingan_konseling bk 
    JOIN siswa s ON bk.siswa_id = s.id 
    WHERE s.kelas = '$kelas_diampu' 
    AND bk.status != 'pending'
    ORDER BY bk.updated_at DESC 
    LIMIT 50
");

$bimbingan_riwayat = [];
if ($qBimbinganRiwayat) {
    while ($row = mysqli_fetch_assoc($qBimbinganRiwayat)) {
        $bimbingan_riwayat[] = $row;
    }
}

$total_pending = count($bimbingan_pending);
$total_riwayat = count($bimbingan_riwayat);
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bimbingan Konseling - <?php echo $kelas_diampu; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <style>
        .table-responsive {
            max-height: 600px;
            overflow-y: auto;
        }
        .badge-pending {
            background: #ffc107;
            color: #000;
        }
        .badge-approved {
            background: #17a2b8;
            color: #fff;
        }
        .badge-completed {
            background: #28a745;
            color: #fff;
        }
        .badge-rejected {
            background: #dc3545;
            color: #fff;
        }
        .btn-sm {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }
    </style>
</head>
<body class="container mt-4">
    <h2>👥 Bimbingan Konseling - Kelas <?php echo $kelas_diampu; ?></h2>
    <a href="dashboard_wali_kelas.php" class="btn btn-secondary mb-3">← Kembali</a>

    <?php if (isset($success)): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle"></i> <?php echo $success; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if (isset($error)): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-circle"></i> <?php echo $error; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Bimbingan Pending -->
    <div class="card mb-4">
        <div class="card-header bg-warning text-dark">
            <strong>⏳ Ajuan Menunggu Persetujuan</strong>
            <span class="badge bg-dark"><?php echo $total_pending; ?> Ajuan</span>
        </div>
        <div class="card-body p-0">
            <?php if (empty($bimbingan_pending)): ?>
                <div class="text-center text-success py-4">
                    <i class="fas fa-check-circle fa-2x mb-2"></i><br>
                    <strong>Tidak ada ajuan bimbingan yang menunggu persetujuan.</strong>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-bordered table-hover table-sm mb-0">
                        <thead class="table-light">
                            <tr>
                                <th width="5%">No</th>
                                <th width="10%">Tanggal</th>
                                <th width="15%">Siswa</th>
                                <th width="10%">NIS</th>
                                <th width="15%">Topik</th>
                                <th width="25%">Keterangan</th>
                                <th width="15%">Ajuan</th>
                                <th width="10%">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($bimbingan_pending as $index => $bimbingan): ?>
                                <tr>
                                    <td class="text-center"><?php echo $index + 1; ?></td>
                                    <td><?php echo date('d/m/Y', strtotime($bimbingan['tanggal'])); ?></td>
                                    <td><?php echo htmlspecialchars($bimbingan['siswa_nama']); ?></td>
                                    <td><?php echo htmlspecialchars($bimbingan['nis']); ?></td>
                                    <td><?php echo htmlspecialchars($bimbingan['topik']); ?></td>
                                    <td><?php echo htmlspecialchars($bimbingan['keterangan']); ?></td>
                                    <td><?php echo date('d/m/Y H:i', strtotime($bimbingan['created_at'])); ?></td>
                                    <td class="text-center">
                                        <form method="POST" class="d-inline">
                                            <input type="hidden" name="bimbingan_id" value="<?php echo $bimbingan['id']; ?>">
                                            <button type="submit" name="approve_bimbingan" class="btn btn-success btn-sm" title="Setujui">
                                                <i class="fas fa-check"></i>
                                            </button>
                                        </form>
                                        <button type="button" class="btn btn-danger btn-sm" 
                                                onclick="openRejectModal(<?php echo $bimbingan['id']; ?>)" title="Tolak">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Riwayat Bimbingan -->
    <div class="card">
        <div class="card-header bg-info text-white">
            <strong>📊 Riwayat Bimbingan</strong>
            <span class="badge bg-light text-dark"><?php echo $total_riwayat; ?> Sesi</span>
        </div>
        <div class="card-body p-0">
            <?php if (empty($bimbingan_riwayat)): ?>
                <div class="text-center text-muted py-4">
                    <i class="fas fa-comments fa-2x mb-2"></i><br>
                    <strong>Belum ada riwayat bimbingan.</strong>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-bordered table-hover table-sm mb-0">
                        <thead class="table-light">
                            <tr>
                                <th width="5%">No</th>
                                <th width="10%">Tanggal</th>
                                <th width="15%">Siswa</th>
                                <th width="10%">NIS</th>
                                <th width="15%">Topik</th>
                                <th width="20%">Keterangan</th>
                                <th width="10%">Status</th>
                                <th width="20%">Catatan Guru</th>
                                <th width="5%">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($bimbingan_riwayat as $index => $bimbingan): ?>
                                <tr>
                                    <td class="text-center"><?php echo $index + 1; ?></td>
                                    <td>
                                        <?php echo date('d/m/Y', strtotime($bimbingan['tanggal'])); ?>
                                        <br><small class="text-muted"><?php echo date('H:i', strtotime($bimbingan['updated_at'])); ?></small>
                                    </td>
                                    <td><?php echo htmlspecialchars($bimbingan['siswa_nama']); ?></td>
                                    <td><?php echo htmlspecialchars($bimbingan['nis']); ?></td>
                                    <td><?php echo htmlspecialchars($bimbingan['topik']); ?></td>
                                    <td><?php echo htmlspecialchars($bimbingan['keterangan']); ?></td>
                                    <td class="text-center">
                                        <span class="badge badge-<?php echo $bimbingan['status']; ?>">
                                            <?php echo ucfirst($bimbingan['status']); ?>
                                        </span>
                                    </td>
                                    <td><?php echo htmlspecialchars($bimbingan['catatan_guru'] ?? '-'); ?></td>
                                    <td class="text-center">
                                        <?php if ($bimbingan['status'] === 'approved'): ?>
                                            <button type="button" class="btn btn-primary btn-sm" 
                                                    onclick="openCompleteModal(<?php echo $bimbingan['id']; ?>)" title="Selesaikan">
                                                <i class="fas fa-check-double"></i>
                                            </button>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Modal Penolakan -->
    <div id="rejectModal" class="modal fade" tabindex="-1">
        <div class="modal-dialog modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-times-circle text-danger"></i> Tolak Ajuan</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" id="rejectForm">
                    <div class="modal-body">
                        <input type="hidden" name="bimbingan_id" id="modal_bimbingan_id">
                        <div class="mb-3">
                            <label for="alasan_penolakan" class="form-label">Alasan Penolakan</label>
                            <textarea class="form-control" id="alasan_penolakan" name="alasan_penolakan" 
                                      rows="3" placeholder="Berikan alasan penolakan..." required></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" name="reject_bimbingan" class="btn btn-danger btn-sm">
                            <i class="fas fa-times"></i> Tolak
                        </button>
                        <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">
                            Batal
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal Penyelesaian -->
    <div id="completeModal" class="modal fade" tabindex="-1">
        <div class="modal-dialog modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-check-double text-success"></i> Selesaikan Sesi</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" id="completeForm">
                    <div class="modal-body">
                        <input type="hidden" name="bimbingan_id" id="modal_complete_id">
                        <div class="mb-3">
                            <label for="catatan_guru" class="form-label">Catatan Hasil</label>
                            <textarea class="form-control" id="catatan_guru" name="catatan_guru" 
                                      rows="3" placeholder="Tuliskan hasil sesi bimbingan..." required></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" name="complete_bimbingan" class="btn btn-success btn-sm">
                            <i class="fas fa-check-double"></i> Selesaikan
                        </button>
                        <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">
                            Batal
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function openRejectModal(bimbinganId) {
            document.getElementById('modal_bimbingan_id').value = bimbinganId;
            new bootstrap.Modal(document.getElementById('rejectModal')).show();
        }

        function openCompleteModal(bimbinganId) {
            document.getElementById('modal_complete_id').value = bimbinganId;
            new bootstrap.Modal(document.getElementById('completeModal')).show();
        }

        // Reset form ketika modal ditutup
        document.getElementById('rejectModal').addEventListener('hidden.bs.modal', function () {
            document.getElementById('alasan_penolakan').value = '';
        });

        document.getElementById('completeModal').addEventListener('hidden.bs.modal', function () {
            document.getElementById('catatan_guru').value = '';
        });

        // Auto-hide alerts after 4 seconds
        setTimeout(() => {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(alert => {
                const bsAlert = new bootstrap.Alert(alert);
                bsAlert.close();
            });
        }, 4000);
    </script>
</body>
</html>