<?php
include '../config.php';

// Cek apakah user sudah login dan role guru
if (!isGuru()) {
    redirect('../login.php');
}

// Get course ID from URL
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['error'] = "Course ID tidak valid!";
    header("Location: manage_courses.php");
    exit();
}

$course_id = intval($_GET['id']);
$guru_id = $_SESSION['user_id'];

// Cek apakah course ini milik guru yang sedang login
$check_ownership = $conn->query("SELECT id FROM lms_courses WHERE id = $course_id AND id_guru = $guru_id");
if ($check_ownership->num_rows == 0) {
    $_SESSION['error'] = "Anda tidak memiliki akses untuk menghapus kursus ini!";
    header("Location: manage_courses.php");
    exit();
}

// Get course data
$course_data = $conn->query("SELECT judul FROM lms_courses WHERE id = $course_id")->fetch_assoc();

// Cek apakah course memiliki enrollment
$check_lms_enrollments = $conn->query("SELECT COUNT(*) as total FROM lms_enrollments WHERE id_course = $course_id");
$has_lms_enrollments = $check_lms_enrollments->fetch_assoc()['total'] > 0;

// Handle delete confirmation
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['confirm_delete'])) {
        
        if ($has_lms_enrollments) {
            $_SESSION['error'] = "Tidak dapat menghapus kursus yang sudah memiliki peserta!";
            header("Location: manage_courses.php");
            exit();
        }
        
        // Start transaction untuk memastikan semua data terkait terhapus
        $conn->begin_transaction();
        
        try {
            // Delete related lms_questions
            $conn->query("DELETE q FROM lms_questions q 
                         JOIN lms_quizzes qu ON q.id_quiz = qu.id 
                         JOIN lms_lessons l ON qu.id_lesson = l.id 
                         WHERE l.id_course = $course_id");
            
            // Delete related lms_quizzes
            $conn->query("DELETE qu FROM lms_quizzes qu 
                         JOIN lms_lessons l ON qu.id_lesson = l.id 
                         WHERE l.id_course = $course_id");
            
            // Delete related lms_lessons
            $conn->query("DELETE FROM lms_lessons WHERE id_course = $course_id");
            
            // Delete the course
            $conn->query("DELETE FROM lms_courses WHERE id = $course_id");
            
            // Commit transaction
            $conn->commit();
            
            $_SESSION['success'] = "Kursus berhasil dihapus!";
            header("Location: manage_courses.php");
            exit();
            
        } catch (Exception $e) {
            // Rollback transaction jika ada error
            $conn->rollback();
            $_SESSION['error'] = "Terjadi kesalahan saat menghapus kursus: " . $e->getMessage();
            header("Location: manage_courses.php");
            exit();
        }
    } else {
        // User cancelled deletion
        header("Location: manage_courses.php");
        exit();
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hapus Kursus - SMANSAB LMS</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        .danger-zone {
            border: 2px solid #dc3545;
            border-radius: 10px;
            background-color: #f8d7da;
        }
        .course-info {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 1.5rem;
        }
    </style>
</head>
<body>
    <!-- Navbar Guru -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand fw-bold" href="dashboard.php">SMANSAB LMS - Guru</a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="manage_courses.php">Kelola Kursus</a>
                <a class="nav-link" href="../logout.php">Logout</a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header bg-danger text-white">
                        <h4 class="card-title mb-0">
                            <i class="bi bi-exclamation-triangle"></i> Konfirmasi Hapus Kursus
                        </h4>
                    </div>
                    <div class="card-body">
                        
                        <!-- Course Information -->
                        <div class="course-info mb-4">
                            <h5>Informasi Kursus</h5>
                            <p class="mb-1"><strong>Judul:</strong> <?php echo htmlspecialchars($course_data['judul']); ?></p>
                            <p class="mb-0"><strong>ID Kursus:</strong> #<?php echo $course_id; ?></p>
                        </div>

                        <?php if ($has_lms_enrollments): ?>
                            <!-- Tidak bisa menghapus karena ada peserta -->
                            <div class="alert alert-danger">
                                <h5><i class="bi bi-x-circle"></i> Tidak Dapat Menghapus Kursus</h5>
                                <p class="mb-3">
                                    Kursus ini <strong>tidak dapat dihapus</strong> karena sudah memiliki peserta yang terdaftar.
                                </p>
                                <div class="alert alert-warning">
                                    <h6><i class="bi bi-info-circle"></i> Alternatif Solusi:</h6>
                                    <ul class="mb-0">
                                        <li>Nonaktifkan kursus dengan mengubah status menjadi "Draft"</li>
                                        <li>Hapus materi-materi yang tidak diperlukan</li>
                                        <li>Hubungi administrator untuk bantuan lebih lanjut</li>
                                    </ul>
                                </div>
                            </div>
                            
                            <div class="text-center mt-4">
                                <a href="manage_courses.php" class="btn btn-primary">
                                    <i class="bi bi-arrow-left"></i> Kembali ke Kelola Kursus
                                </a>
                            </div>

                        <?php else: ?>
                            <!-- Bisa menghapus karena tidak ada peserta -->
                            <div class="danger-zone p-4 mb-4">
                                <h5 class="text-danger">
                                    <i class="bi bi-exclamation-triangle"></i> Zona Berbahaya
                                </h5>
                                <p class="mb-3">
                                    Anda akan menghapus kursus <strong>"<?php echo htmlspecialchars($course_data['judul']); ?>"</strong>. 
                                    Tindakan ini <strong class="text-danger">tidak dapat dibatalkan</strong>.
                                </p>
                                
                                <div class="alert alert-warning">
                                    <h6><i class="bi bi-lightbulb"></i> Yang akan terhapus:</h6>
                                    <ul class="mb-0">
                                        <li>Semua materi pembelajaran (lms_lessons)</li>
                                        <li>Semua kuis dan pertanyaan</li>
                                        <li>Data kursus secara permanen</li>
                                    </ul>
                                </div>
                            </div>

                            <!-- Confirmation Form -->
                            <form method="POST" action="">
                                <div class="alert alert-info">
                                    <h6><i class="bi bi-shield-check"></i> Konfirmasi Penghapusan</h6>
                                    <p class="mb-2">Untuk melanjutkan penghapusan, ketik <strong>"HAPUS"</strong> pada kolom di bawah:</p>
                                    <input type="text" class="form-control" id="confirmation_text" 
                                           placeholder="Ketik HAPUS di sini" required
                                           oninput="checkConfirmation()">
                                </div>

                                <div class="d-flex justify-content-between">
                                    <a href="manage_courses.php" class="btn btn-secondary">
                                        <i class="bi bi-x-circle"></i> Batalkan
                                    </a>
                                    <button type="submit" name="confirm_delete" id="delete_btn" 
                                            class="btn btn-danger" disabled>
                                        <i class="bi bi-trash"></i> Hapus Permanen
                                    </button>
                                </div>
                            </form>
                        <?php endif; ?>

                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        function checkConfirmation() {
            const confirmationText = document.getElementById('confirmation_text').value;
            const deleteBtn = document.getElementById('delete_btn');
            
            if (confirmationText.toUpperCase() === 'HAPUS') {
                deleteBtn.disabled = false;
            } else {
                deleteBtn.disabled = true;
            }
        }
    </script>

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