<?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) ?? [];
$orderID = $input['orderID'] ?? null;
$enrollmentId = (int)($input['enrollment_id'] ?? 0);
if (!$orderID || !$enrollmentId) { echo json_encode(['success' => false, 'message' => 'orderID and 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; }

// Get PayPal token
$paypalTokenUrl = 'https://api-m.sandbox.paypal.com/v1/oauth2/token';
$paypalCaptureUrl = 'https://api-m.sandbox.paypal.com/v2/checkout/orders/' . urlencode($orderID) . '/capture';
$clientId = PAYPAL_CLIENT_ID;
$secret = PAYPAL_CLIENT_SECRET;

$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; }

// Capture
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $paypalCaptureUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
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 capture PayPal order: ' . $err]); exit; }
$captureData = json_decode($response, true);
$status = $captureData['status'] ?? null;
if (strtoupper($status) !== 'COMPLETED' && strtoupper($captureData['status'] ?? '') !== 'COMPLETED') {
    echo json_encode(['success' => false, 'message' => 'Payment not completed', 'response' => $captureData]);
    exit;
}

// Verify amount
$amountPaid = 0;
if (!empty($captureData['purchase_units']) && !empty($captureData['purchase_units'][0]['payments']['captures'][0]['amount']['value'])) {
    $amountPaid = (float)$captureData['purchase_units'][0]['payments']['captures'][0]['amount']['value'];
}

// Basic amount check
if (abs($amountPaid - (float)$enrollment['payment_amount']) > 0.01) {
    // amount mismatch — log and fail
    echo json_encode(['success' => false, 'message' => 'Payment amount mismatch', 'paid' => $amountPaid, 'expected' => (float)$enrollment['payment_amount']]);
    exit;
}

// Mark enrollment as paid and active
$db->update('course_enrollments', ['payment_status' => 'paid', 'payment_id' => $orderID, 'status' => 'active'], 'id = ?', [$enrollmentId]);
// increment course enrollment count
$db->query('UPDATE courses SET enrollment_count = enrollment_count + 1 WHERE id = ?', [$enrollment['course_id']]);

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