<?php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../../../config/database.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}
$input = json_decode(file_get_contents('php://input'), true) ?? [];
$enrollmentId = (int)($input['enrollment_id'] ?? 0);
if (!$enrollmentId) { echo json_encode(['success' => false, 'message' => 'enrollment_id required']); exit; }

$db = Database::getInstance();
$enrollment = $db->get('SELECT ce.*, c.title, c.price, c.currency FROM course_enrollments ce JOIN courses c ON ce.course_id = c.id WHERE ce.id = ?', [$enrollmentId]);
if (!$enrollment) { echo json_encode(['success' => false, 'message' => 'Enrollment not found']); exit; }
if ($enrollment['payment_status'] !== 'pending') { echo json_encode(['success' => false, 'message' => 'Enrollment not pending']); exit; }

$agreement = $db->get('SELECT status FROM course_enrollment_agreements WHERE enrollment_id = ?', [$enrollmentId]);
if (!$agreement || $agreement['status'] !== 'signed') { echo json_encode(['success' => false, 'message' => 'Training agreement must be signed before payment.']); exit; }

// PayPal API endpoints
$paypalTokenUrl = 'https://api-m.sandbox.paypal.com/v1/oauth2/token';
$paypalOrderUrl = 'https://api-m.sandbox.paypal.com/v2/checkout/orders';

$clientId = PAYPAL_CLIENT_ID;
$secret = PAYPAL_CLIENT_SECRET;

// Get access token
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $paypalTokenUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $clientId . ':' . $secret);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json', 'Accept-Language: en_US']);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$err = curl_error($ch);
curl_close($ch);
if ($errno) { echo json_encode(['success' => false, 'message' => 'Failed to retrieve PayPal token: ' . $err]); exit; }
$tokenData = json_decode($response, true);
$accessToken = $tokenData['access_token'] ?? null;
if (!$accessToken) { echo json_encode(['success' => false, 'message' => 'Failed to get PayPal access token']); exit; }

// Create order
$amount = number_format((float)$enrollment['payment_amount'], 2, '.', '');
$payload = [
    'intent' => 'CAPTURE',
    'purchase_units' => [[
        'amount' => ['currency_code' => $enrollment['payment_currency'] ?? 'USD', 'value' => $amount],
        'description' => 'Course: ' . ($enrollment['title'] ?? 'Course')
    ]]
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $paypalOrderUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Authorization: Bearer ' . $accessToken]);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$err = curl_error($ch);
curl_close($ch);
if ($errno) { echo json_encode(['success' => false, 'message' => 'Failed to create PayPal order: ' . $err]); exit; }
$orderData = json_decode($response, true);
$orderID = $orderData['id'] ?? null;
if (!$orderID) {
    echo json_encode(['success' => false, 'message' => 'Failed to create PayPal order', 'response' => $orderData]);
    exit;
}

// store order id in enrollment for tracking
$db->update('course_enrollments', ['payment_id' => $orderID], 'id = ?', [$enrollmentId]);

echo json_encode(['success' => true, 'orderID' => $orderID]);
exit;
