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

if (!isset($_SESSION['user_id'])) {
    http_response_code(403);
    die('Akses ditolak. Silakan login.');
}
$user_id = $_SESSION['user_id'];
$lesson_id = $_GET['lesson_id'] ?? null;
if (!$lesson_id) {
    http_response_code(400);
    die('ID Materi tidak valid.');
}

// Ambil path video dan course_id dari database
$stmt = $pdo->prepare("SELECT video_path, course_id FROM lessons WHERE id = ? AND lesson_type = 'video'");
$stmt->execute([$lesson_id]);
$lesson = $stmt->fetch();
if (!$lesson || empty($lesson['video_path'])) {
    http_response_code(404);
    die('Video tidak ditemukan.');
}
$course_id = $lesson['course_id'];
$filepath = $lesson['video_path'];

// --- LOGIKA HAK AKSES ---
$access_stmt = $pdo->prepare("SELECT id FROM orders WHERE user_id = ? AND course_id = ? AND status = 'completed'");
$access_stmt->execute([$user_id, $course_id]);
if (!$access_stmt->fetch()) {
    http_response_code(403);
    die("Akses ditolak. Anda belum terdaftar di kursus ini.");
}
// --- AKHIR LOGIKA HAK AKSES ---

if (file_exists($filepath)) {
    header('Content-Type: video/mp4');
    header('Content-Length: ' . filesize($filepath));
    header('Accept-Ranges: bytes');
    if (ob_get_level()) {
        ob_end_clean();
    }
    readfile($filepath);
    exit;
} else {
    http_response_code(404);
    die('File video tidak ada di server.');
}
?>