<?php
// api/paystack-init.php

header('Content-Type: application/json');
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../src/Helpers/Auth.php';
require_once __DIR__ . '/../src/Controllers/CourseController.php';
require_once __DIR__ . '/../src/Controllers/PaymentController.php';

if (!Auth::check()) {
    echo json_encode(['success' => false, 'message' => 'Please login or register an account first.']);
    exit;
}

$user = Auth::user();
$courseId = $_POST['course_id'] ?? '';
$currency = $_POST['currency'] ?? 'NGN';

if (empty($courseId)) {
    echo json_encode(['success' => false, 'message' => 'Invalid course selected.']);
    exit;
}

$course = CourseController::getCourseById($courseId);
if (!$course) {
    echo json_encode(['success' => false, 'message' => 'Course not found.']);
    exit;
}

$amount = $currency === 'USD' ? $course['price_usd'] : $course['price_ngn'];
$amountInKobo = $amount * 100; // Paystack expects amount in minor units (kobo/cents)

$result = PaymentController::initiatePaystackTransaction($user['id'], $courseId, $user['email'], $amountInKobo);
echo json_encode($result);
