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

$secret = PAYSTACK_SECRET_KEY;
$public = PAYSTACK_PUBLIC_KEY;
$initializeUrl = 'https://api.paystack.co/transaction/initialize';

$amount_kobo = (int)round(((float)$enrollment['payment_amount']) * 100);
$email = $db->get('SELECT email FROM users WHERE id = ?', [$enrollment['student_id']])['email'] ?? '';

$payload = ['email' => $email, 'amount' => $amount_kobo, 'metadata' => ['enrollment_id' => $enrollmentId]];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $initializeUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer {$secret}", 'Content-Type: application/json']);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$err = curl_error($ch);
curl_close($ch);
if ($errno) { echo json_encode(['success' => false, 'message' => 'Paystack init 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; }

$auth = $data['data'];
// Return the authorization URL and reference for client to proceed
echo json_encode(['success' => true, 'authorization_url' => $auth['authorization_url'], 'reference' => $auth['reference'], 'public_key' => $public, 'amount' => (float)$enrollment['payment_amount'], 'customer_email' => $email]);
exit;
