<?php
// PERBAIKAN: Path diubah dari 'includes/header.php' menjadi '../includes/header.php'
require_once '../includes/header.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: /auth/login.php');
    exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: /dashboard.php');
    exit;
}
check_csrf();

$user_id = $_SESSION['user_id'];
$course_id = $_POST['course_id'];

if (empty($course_id)) {
    header('Location: /dashboard.php');
    exit;
}

// Ambil harga kursus
$course_stmt = $pdo->prepare("SELECT price FROM courses WHERE id = ?");
$course_stmt->execute([$course_id]);
$course = $course_stmt->fetch();
if (!$course) {
    die("Kursus tidak ditemukan.");
}
$price = $course['price'];

// Cek apakah sudah ada pesanan atau sudah terdaftar
$check_stmt = $pdo->prepare("SELECT id, status FROM orders WHERE user_id = ? AND course_id = ?");
$check_stmt->execute([$user_id, $course_id]);
$existing_order = $check_stmt->fetch();

if ($existing_order) {
    if ($existing_order['status'] === 'completed') {
        header("Location: /course/view.php?id=$course_id");
        exit;
    }
    // Jika masih pending atau awaiting, arahkan ke halaman pembayaran
    header("Location: /course/payment.php?order_id=" . $existing_order['id']);
    exit;
}

// Buat pesanan baru
try {
    if ($price > 0) {
        // Kursus berbayar, status 'pending' (menunggu pembayaran)
        $stmt = $pdo->prepare("INSERT INTO orders (user_id, course_id, amount, status) VALUES (?, ?, ?, 'pending')");
        $stmt->execute([$user_id, $course_id, $price]);
        $order_id = $pdo->lastInsertId();
        header("Location: /course/payment.php?order_id=$order_id");
    } else {
        // Kursus gratis, langsung status 'completed'
        $stmt = $pdo->prepare("INSERT INTO orders (user_id, course_id, amount, status, confirmation_date) VALUES (?, ?, ?, 'completed', CURRENT_TIMESTAMP)");
        $stmt->execute([$user_id, $course_id, 0]);
        header("Location: /course/view.php?id=$course_id");
    }
    exit;
} catch (PDOException $e) {
    error_log($e->getMessage());
    die("Gagal memproses pesanan Anda. Silakan coba lagi.");
}
?>