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

if (!isGuru()) {
    redirect('../login.php');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $course_id = isset($_POST['course_id']) ? intval($_POST['course_id']) : 0;
    $judul = isset($_POST['judul']) ? sanitize($_POST['judul']) : '';
    $deskripsi = isset($_POST['deskripsi']) ? sanitize($_POST['deskripsi']) : '';
    
    // Validasi
    if (empty($judul) || empty($course_id)) {
        $_SESSION['error'] = "Nama kursus tidak boleh kosong";
        header("Location: my_courses.php");
        exit();
    }
    
    // Cek apakah kursus milik guru yang login
    $guru_id = $_SESSION['user_id'];
    $check_sql = "SELECT id FROM lms_courses WHERE id = ? AND id_guru = ?";
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->bind_param('ii', $course_id, $guru_id);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result();
    
    if ($check_result->num_rows === 0) {
        $_SESSION['error'] = "Kursus tidak ditemukan atau Anda tidak memiliki akses";
        header("Location: my_courses.php");
        exit();
    }
    
    // Update kursus
    $update_sql = "UPDATE lms_courses SET judul = ?, deskripsi = ?, updated_at = NOW() WHERE id = ?";
    $update_stmt = $conn->prepare($update_sql);
    $update_stmt->bind_param('ssi', $judul, $deskripsi, $course_id);
    
    if ($update_stmt->execute()) {
        $_SESSION['success'] = "Kursus berhasil diperbarui";
    } else {
        $_SESSION['error'] = "Gagal memperbarui kursus: " . $conn->error;
    }
    
    $update_stmt->close();
    $check_stmt->close();
}

header("Location: my_courses.php");
exit();
?>