<?php
require_once '../includes/middleware.php';
require_once '../includes/payments.php';
require_once '../config/payment_security.php';
require_once '../config/currency.php';

header('Content-Type: application/json');

// Set security headers for payment endpoints
PaymentSecurity::setSecurityHeaders();

$db = getDB();
$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'POST':
        // Handle payment initiation
        requirePermission('enroll_course'); // Basic permission check

        $data = json_decode(file_get_contents('php://input'), true);

        $userId = $_SESSION['user_id'];
        $itemType = $data['item_type'] ?? 'course'; // 'course', 'exam', or 'cart'
        $itemId = $data['item_id'] ?? null;
        $gatewayName = $data['gateway'] ?? null; // 'paynow' or 'paypal'
        $discountCode = $data['discount_code'] ?? null;

        try {
            $amount = 0.00;
            $currency = 'USD';
            $itemName = '';

            if ($itemType === 'cart') {
                // Handle cart payment - get cart total and items
                require_once '../api/cart.php';
                $cartManager = new CartManager($db, $userId);
                $cart = $cartManager->getCart();

                if (empty($cart['items'])) {
                    echo json_encode(['success' => false, 'error' => 'Cart is empty']);
                    exit;
                }

                // Check if cart has only free items
                if ($cart['total'] == 0.00) {
                    echo json_encode(['success' => false, 'error' => 'Cart contains only free items']);
                    exit;
                }

                $amount = $cart['total'];
                $currency = $cart['currency'];
                $itemNames = array_column($cart['items'], 'title');
                $itemName = count($itemNames) > 1 ? 'Multiple Courses' : $itemNames[0];

                // Store cart items in item_id for reference
                $itemId = json_encode(array_column($cart['items'], 'item_id'));

            } elseif ($itemType === 'course') {
                if (!$itemId) {
                    echo json_encode(['success' => false, 'error' => 'Item ID is required']);
                    exit;
                }

                // Get item details
                $stmt = $db->prepare("SELECT title, price, currency FROM courses WHERE id = ? AND status = 'published'");
                $stmt->execute([$itemId]);
                $item = $stmt->fetch();

                if (!$item) {
                    echo json_encode(['success' => false, 'error' => 'Course not found']);
                    exit;
                }

                $amount = $item['price'];
                $currency = $item['currency'] ?: 'USD';
                $itemName = $item['title'];

            } elseif ($itemType === 'exam') {
                // TODO: Implement exam pricing logic
                echo json_encode(['success' => false, 'error' => 'Exam payments not yet implemented']);
                exit;
            } else {
                echo json_encode(['success' => false, 'error' => 'Invalid item type']);
                exit;
            }

            // Get user email
            $stmt = $db->prepare("SELECT email FROM users WHERE id = ?");
            $stmt->execute([$userId]);
            $user = $stmt->fetch();
            $userEmail = $user['email'];

            // Validate currency support for the selected gateway
            $gateway = getPaymentGateway($gatewayName);
            $gatewaySettings = $gateway->getSettings();
            $actualGatewayName = $gatewaySettings['gateway_name'];

            if (!CurrencyHelper::isSupportedByGateway($currency, $actualGatewayName)) {
                echo json_encode(['success' => false, 'error' => "Currency {$currency} is not supported by {$actualGatewayName}"]);
                exit;
            }

            // Process payment
            if ($actualGatewayName === 'paynow') {
                $result = $gateway->processPaynowPayment(
                    $userId, $itemType, $itemId, $amount, $currency, $discountCode, $userEmail, $itemName
                );
            } elseif ($actualGatewayName === 'paypal') {
                $result = $gateway->processPaypalPayment(
                    $userId, $itemType, $itemId, $amount, $currency, $discountCode, $userEmail, $itemName
                );
            } else {
                echo json_encode(['success' => false, 'error' => 'Unsupported payment gateway']);
                exit;
            }

            echo json_encode($result);

        } catch (Exception $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
        break;

    case 'GET':
        // Check payment status
        $transactionId = $_GET['transaction_id'] ?? null;

        if (!$transactionId) {
            echo json_encode(['success' => false, 'error' => 'Transaction ID is required']);
            exit;
        }

        try {
            $gateway = getPaymentGateway(); // Use default gateway
            $result = $gateway->checkPaymentStatus($transactionId);
            echo json_encode($result);

        } catch (Exception $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
        break;

    default:
        echo json_encode(['success' => false, 'error' => 'Method not allowed']);
        break;
}