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

$db = Database::getInstance();
$secret = PAYSTACK_SECRET_KEY;
$verifyUrl = 'https://api.paystack.co/transaction/verify/' . urlencode($reference);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $verifyUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer {$secret}"]); 
$response = curl_exec($ch);
$errno = curl_errno($ch);
$err = curl_error($ch);
curl_close($ch);
if ($errno) { echo json_encode(['success' => false, 'message' => 'Paystack verify failed: ' . $err]); exit; }
$data = json_decode($response, true);
if (empty($data['status']) || $data['status'] !== true) { echo json_encode(['success' => false, 'message' => 'Paystack returned error', 'response' => $data]); exit; }

$refData = $data['data'];
if ($refData['status'] !== 'success') { echo json_encode(['success' => false, 'message' => 'Payment not successful', 'data' => $refData]); exit; }

// verify amount matches
$enrollment = $db->get('SELECT * FROM course_enrollments WHERE id = ?', [$enrollmentId]);
if (!$enrollment) { echo json_encode(['success' => false, 'message' => 'Enrollment not found']); exit; }
$paidAmount = ((float)$refData['amount']) / 100.0; // Paystack returns in kobo
if (abs($paidAmount - (float)$enrollment['payment_amount']) > 0.01) { echo json_encode(['success' => false, 'message' => 'Amount mismatch', 'paid' => $paidAmount, 'expected' => (float)$enrollment['payment_amount']]); exit; }

// mark enrollment paid
$db->update('course_enrollments', ['payment_status' => 'paid', 'payment_id' => $refData['reference'], 'status' => 'active'], 'id = ?', [$enrollmentId]);
$db->query('UPDATE courses SET enrollment_count = enrollment_count + 1 WHERE id = ?', [$enrollment['course_id']]);

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