<?php
require_once '../includes/db.php';

// Pastikan user sudah login
if (!isset($_SESSION['user_id'])) {
    header('Location: /auth/login.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$lesson_id = $_GET['lesson_id'] ?? null;
$course_id = $_GET['course_id'] ?? null;

// Validasi input
if (!$lesson_id || !$course_id) {
    header('Location: /dashboard.php');
    exit;
}

try {
    // Cek apakah progres sudah ada sebelumnya untuk menghindari duplikat
    $stmt = $pdo->prepare("SELECT id FROM user_progress WHERE user_id = ? AND lesson_id = ?");
    $stmt->execute([$user_id, $lesson_id]);
    
    if ($stmt->fetch()) {
        // Jika sudah ada, langsung redirect kembali
        header('Location: view.php?id=' . $course_id);
        exit;
    }

    // Jika belum ada, masukkan data progres baru
    $stmt = $pdo->prepare("INSERT INTO user_progress (user_id, lesson_id) VALUES (?, ?)");
    $stmt->execute([$user_id, $lesson_id]);

    // Redirect kembali ke halaman kursus
    header('Location: view.php?id=' . $course_id);
    exit;

} catch (PDOException $e) {
    die("Error: " . $e->getMessage());
}
?>