<?php
/**
 * PayPal Order Creation
 * Creates a PayPal order for publication fee payment
 */

header('Content-Type: application/json; charset=utf-8');
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../common/journal_config_new.php';


try {
    // Read JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    $tracking_code = isset($input['tracking_code']) ? trim($input['tracking_code']) : '';
    $amount = isset($input['amount']) ? trim($input['amount']) : '';
    $currency = isset($input['currency']) ? strtoupper(trim($input['currency'])) : 'USD';
    
    if (!$tracking_code || !$amount) {
        throw new Exception('Missing tracking_code or amount');
    }
    
    // Verify submission exists and not already paid
    $stmt = $pdo->prepare("
        SELECT s.*, a.email, a.name as author_name, j.name as journal_name
        FROM submissions s
        LEFT JOIN authors a ON s.author_id = a.id
        LEFT JOIN journals j ON s.journal_id = j.id
        WHERE s.tracking_code = ? LIMIT 1
    ");
    $stmt->execute([$tracking_code]);
    $submission = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$submission) {
        throw new Exception('Submission not found for tracking code: ' . $tracking_code);
    }
    
    if ($submission['fee_paid'] == 1) {
        throw new Exception('This submission has already been paid');
    }
    
    // Get PayPal access token
    function getPayPalAccessToken() {
        $url = PAYPAL_BASE . '/v1/oauth2/token';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Accept: application/json",
            "Accept-Language: en_US"
        ]);
        curl_setopt($ch, CURLOPT_USERPWD, PAYPAL_CLIENT_ID . ":" . PAYPAL_SECRET);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode != 200) {
            error_log("PayPal token fetch failed: HTTP $httpCode - $response");
            return false;
        }
        
        $data = json_decode($response, true);
        return $data['access_token'] ?? false;
    }
    
    $accessToken = getPayPalAccessToken();
    
    if (!$accessToken) {
        throw new Exception('Could not get PayPal access token');
    }
    
    // Create PayPal order
    $createOrderUrl = PAYPAL_BASE . '/v2/checkout/orders';
    
    $orderPayload = [
        'intent' => 'CAPTURE',
        'purchase_units' => [
            [
                'reference_id' => $tracking_code,
                'invoice_id' => 'RSIS-' . $tracking_code,
                'custom_id' => $tracking_code,
                'description' => 'Publication Fee - ' . ($submission['journal_name'] ?? 'RSIS International'),
                'amount' => [
                    'currency_code' => $currency,
                    'value' => $amount,
                    'breakdown' => [
                        'item_total' => [
                            'currency_code' => $currency,
                            'value' => $amount
                        ]
                    ]
                ],
                'items' => [
                    [
                        'name' => 'Article Publication Fee',
                        'description' => substr($submission['title'] ?? 'Research Article', 0, 127),
                        'quantity' => '1',
                        'unit_amount' => [
                            'currency_code' => $currency,
                            'value' => $amount
                        ],
                        'category' => 'DIGITAL_GOODS'
                    ]
                ]
            ]
        ],
        'application_context' => [
            'brand_name' => 'RSIS International',
            'landing_page' => 'NO_PREFERENCE',
            'shipping_preference' => 'NO_SHIPPING',
            'user_action' => 'PAY_NOW',
            'return_url' => 'https://rsisinternational.org/journals/common/payment/stripe_success.php?tracking_code=' . $tracking_code . '&method=paypal',
            'cancel_url' => 'https://rsisinternational.org/journals/common/payment/payment_form.php?tracking_code=' . $tracking_code
        ]
    ];
    
    $ch = curl_init($createOrderUrl);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Content-Type: application/json",
        "Authorization: Bearer $accessToken"
    ]);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($orderPayload));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);
    
    if ($curlError) {
        throw new Exception('CURL Error: ' . $curlError);
    }
    
    if ($httpCode < 200 || $httpCode >= 300) {
        error_log("PayPal create order failed: HTTP $httpCode - $response");
        throw new Exception('PayPal order creation failed: HTTP ' . $httpCode);
    }
    
    $orderData = json_decode($response, true);
    $orderId = $orderData['id'] ?? null;
    
    if (!$orderId) {
        throw new Exception('Invalid PayPal response - no order ID');
    }
    
    // Optional: Store initial order record in database
    try {
        $insertStmt = $pdo->prepare("
            INSERT INTO paypal_payments 
            (tracking_code, invoice_no, payment_method, order_id, status, amount, currency, raw_response, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
        ");
        
        $insertStmt->execute([
            $tracking_code,
            'RSIS-' . $tracking_code,
            'paypal',
            $orderId,
            'CREATED',
            $amount,
            $currency,
            json_encode($orderData)
        ]);
    } catch (Exception $dbError) {
        // Log but don't fail - order is created
        error_log("DB insert warning: " . $dbError->getMessage());
    }
    
    // Return order ID to client
    echo json_encode([
        'success' => true,
        'id' => $orderId,
        'status' => $orderData['status'] ?? 'CREATED'
    ]);
    
} catch (Exception $e) {
    error_log("PayPal create_order.php error: " . $e->getMessage());
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}