<?php
/**
 * PayPal Order Capture
 * Captures the payment after user approves the PayPal order
 */

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);
    
    $orderID = isset($input['orderID']) ? trim($input['orderID']) : '';
    $tracking_code = isset($input['tracking_code']) ? trim($input['tracking_code']) : '';
    
    if (!$orderID || !$tracking_code) {
        throw new Exception('Missing orderID or tracking_code');
    }
    
    // Verify submission exists
    $stmt = $pdo->prepare("
        SELECT s.*, a.email, a.name as author_name
        FROM submissions s
        LEFT JOIN authors a ON s.author_id = a.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');
    }
    
    // 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');
    }
    
    // Capture the order
    $captureUrl = PAYPAL_BASE . '/v2/checkout/orders/' . $orderID . '/capture';
    
    $ch = curl_init($captureUrl);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Content-Type: application/json",
        "Authorization: Bearer $accessToken"
    ]);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, '{}');
    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 capture failed: HTTP $httpCode - $response");
        throw new Exception('PayPal capture failed: HTTP ' . $httpCode);
    }
    
    $captureData = json_decode($response, true);
    
    // Extract payment details
    $status = $captureData['status'] ?? '';
    $captureID = $captureData['purchase_units'][0]['payments']['captures'][0]['id'] ?? '';
    $amount = $captureData['purchase_units'][0]['payments']['captures'][0]['amount']['value'] ?? '0.00';
    $currency = $captureData['purchase_units'][0]['payments']['captures'][0]['amount']['currency_code'] ?? 'USD';
    $payerEmail = $captureData['payer']['email_address'] ?? '';
    $payerName = ($captureData['payer']['name']['given_name'] ?? '') . ' ' . ($captureData['payer']['name']['surname'] ?? '');
    
    if ($status !== 'COMPLETED') {
        throw new Exception('Payment not completed. Status: ' . $status);
    }
    
    if (!$captureID) {
        throw new Exception('No capture ID received');
    }
    
    // Check if payment already recorded
    $checkStmt = $pdo->prepare("
        SELECT id FROM paypal_payments 
        WHERE capture_id = ? OR order_id = ?
        LIMIT 1
    ");
    $checkStmt->execute([$captureID, $orderID]);
    
    if ($checkStmt->rowCount() > 0) {
        // Update existing record
        $updateStmt = $pdo->prepare("
            UPDATE paypal_payments 
            SET capture_id = ?, status = ?, payer_email = ?, payer_name = ?, 
                amount = ?, currency = ?, raw_response = ?, created_at = NOW()
            WHERE order_id = ?
        ");
        
        $updateStmt->execute([
            $captureID,
            'COMPLETED',
            $payerEmail,
            trim($payerName),
            $amount,
            $currency,
            json_encode($captureData),
            $orderID
        ]);
    } else {
        // Insert new record
        $insertStmt = $pdo->prepare("
            INSERT INTO paypal_payments 
            (tracking_code, invoice_no, payment_method, order_id, capture_id, transaction_id, 
             status, payer_email, payer_name, amount, currency, raw_response, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
        ");
        
        $insertStmt->execute([
            $tracking_code,
            'RSIS-' . $tracking_code,
            'paypal',
            $orderID,
            $captureID,
            $captureID, // Use capture_id as transaction_id for PayPal
            'COMPLETED',
            $payerEmail,
            trim($payerName),
            $amount,
            $currency,
            json_encode($captureData)
        ]);
    }
    
    // Update submissions table - mark as paid
    $updateSubmission = $pdo->prepare("
        UPDATE submissions 
        SET fee_paid = 1, payment_date = NOW(), updated_at = NOW()
        WHERE tracking_code = ?
    ");
    $updateSubmission->execute([$tracking_code]);
    
    // Return success
    echo json_encode([
        'success' => true,
        'status' => 'COMPLETED',
        'capture_id' => $captureID,
        'order_id' => $orderID,
        'tracking_code' => $tracking_code
    ]);
    
} catch (Exception $e) {
    error_log("PayPal capture_order.php error: " . $e->getMessage());
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}