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

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../src/Helpers/Auth.php';
require_once __DIR__ . '/../src/Controllers/PaymentController.php';

$reference = $_GET['reference'] ?? $_GET['trxref'] ?? '';
$courseId = $_GET['course_id'] ?? '';
$isSimulated = ($_GET['simulated'] ?? '') === 'true';

if (!Auth::check()) {
    header('Location: ' . APP_URL . '/?msg=please_login');
    exit;
}

$user = Auth::user();

if (empty($reference) || empty($courseId)) {
    header('Location: ' . APP_URL . '/?error=invalid_payment');
    exit;
}

if ($isSimulated) {
    // Process simulated payment verification
    PaymentController::verifyAndEnroll($user['id'], $courseId, $reference);
    header('Location: ' . APP_URL . '/index.php?page=portal&enrolled=success');
    exit;
}

// Real Paystack Verification Call
$url = "https://api.paystack.co/transaction/verify/" . rawurlencode($reference);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer " . PAYSTACK_SECRET_KEY,
    "Cache-Control: no-cache"
]);

$result = curl_exec($ch);
curl_close($ch);
$response = json_decode($result, true);

if (isset($response['data']['status']) && $response['data']['status'] === 'success') {
    PaymentController::verifyAndEnroll($user['id'], $courseId, $reference);
    header('Location: ' . APP_URL . '/index.php?page=portal&enrolled=success');
    exit;
} else {
    header('Location: ' . APP_URL . '/?error=payment_failed');
    exit;
}
