<?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) ?? [];
$type = strtolower(trim($input['type'] ?? 'enrollment'));

$db = Database::getInstance();

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

// Build payload depending on payment type
if ($type === 'ai_premium') {
    $userId = (int)($input['user_id'] ?? 0);
    if (!$userId) {
        echo json_encode(['success' => false, 'message' => 'user_id required for ai_premium payments']);
        exit;
    }

    $user = $db->get('SELECT email FROM users WHERE id = ?', [$userId]);
    if (!$user) {
        echo json_encode(['success' => false, 'message' => 'User not found']);
        exit;
    }

    $amount = defined('AI_PREMIUM_PRICE') ? (float)AI_PREMIUM_PRICE : 0.0;
    if ($amount <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid AI Premium amount']);
        exit;
    }

    $currency = defined('AI_PREMIUM_CURRENCY_PAYSTACK') ? strtoupper(AI_PREMIUM_CURRENCY_PAYSTACK) : 'NGN';

    $amount_kobo = (int)round($amount * 100);
    $email = trim($user['email'] ?? '');

    $payload = [
        'email' => $email,
        'amount' => $amount_kobo,
        'currency' => $currency,
        'metadata' => [
            'type' => 'ai_premium',
            'user_id' => $userId,
        ],
    ];

    $displayAmount = $amount;
} elseif ($type === 'appointment') {
    $appointmentId = (int)($input['appointment_id'] ?? 0);
    if (!$appointmentId) {
        echo json_encode(['success' => false, 'message' => 'appointment_id required']);
        exit;
    }

    $appointment = $db->get('SELECT * FROM appointments WHERE id = ?', [$appointmentId]);
    if (!$appointment) {
        echo json_encode(['success' => false, 'message' => 'Appointment not found']);
        exit;
    }

    if (($appointment['payment_status'] ?? 'free') !== 'pending') {
        echo json_encode(['success' => false, 'message' => 'Appointment not pending payment']);
        exit;
    }

    $amount = (float)($appointment['amount'] ?? 0.0);
    if ($amount <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid appointment amount']);
        exit;
    }

    $currency = strtoupper($appointment['currency'] ?? '');
    if ($currency !== 'GHS') {
        echo json_encode(['success' => false, 'message' => 'Paystack is only available for GHS appointments.']);
        exit;
    }

    $amount_kobo = (int)round($amount * 100);
    $email = trim($appointment['email'] ?? '');

    $payload = [
        'email' => $email,
        'amount' => $amount_kobo,
        'currency' => $currency,
        'metadata' => [
            'type' => 'appointment',
            'appointment_id' => $appointmentId,
        ],
    ];

    $displayAmount = $amount;
} else {
    // Default behaviour: course enrollment payments
    $enrollmentId = (int)($input['enrollment_id'] ?? 0);
    if (!$enrollmentId) {
        echo json_encode(['success' => false, 'message' => 'enrollment_id required']);
        exit;
    }

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

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

    $paymentPolicy = $db->get('SELECT status FROM course_enrollment_payment_policies WHERE enrollment_id = ?', [$enrollmentId]);
    if (!$paymentPolicy || $paymentPolicy['status'] !== 'accepted') {
        echo json_encode(['success' => false, 'message' => 'Non-Refundable Payment Policy must be accepted before payment.']);
        exit;
    }

    $privacyPolicy = $db->get('SELECT status FROM course_enrollment_privacy_policies WHERE enrollment_id = ?', [$enrollmentId]);
    if (!$privacyPolicy || $privacyPolicy['status'] !== 'accepted') {
        echo json_encode(['success' => false, 'message' => 'Data Privacy Policy must be accepted before payment.']);
        exit;
    }

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

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

    $displayAmount = (float)$enrollment['payment_amount'];
}

$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, reference, and currency for client to proceed
echo json_encode([
    'success' => true,
    'authorization_url' => $auth['authorization_url'],
    'reference' => $auth['reference'],
    'public_key' => $public,
    'amount' => $displayAmount,
    'currency' => $currency,
    'customer_email' => $email,
]);
exit;
