<?php
/**
 * PayPal Success Handler
 * Digital Product Store
 */

require_once __DIR__ . '/../config/database.php';
require_login();

$order_id = isset($_GET['order_id']) ? (int)$_GET['order_id'] : 0;
$token = $_GET['token'] ?? '';

if (!$order_id || !$token) {
    set_flash_message('Invalid payment response.', 'error');
    header('Location: ' . BASE_URL . '/cart.php');
    exit;
}

$order = get_order_by_id($order_id);

if (!$order || $order['user_id'] != get_current_user_id()) {
    set_flash_message('Order not found.', 'error');
    header('Location: ' . BASE_URL . '/cart.php');
    exit;
}

// Get PayPal settings
$paypal = get_payment_gateway('paypal');
$config = $paypal['config'] ?? [];
$client_id = $config['client_id'] ?? '';
$client_secret = $config['client_secret'] ?? '';
$test_mode = $paypal['test_mode'] ?? 1;

$api_url = $test_mode ? 'https://api-m.sandbox.paypal.com' : 'https://api-m.paypal.com';

// Get access token
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url . '/v1/oauth2/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
curl_setopt($ch, CURLOPT_USERPWD, $client_id . ':' . $client_secret);

$headers = [];
$headers[] = 'Accept: application/json';
$headers[] = 'Accept-Language: en_US';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
curl_close($ch);

$token_data = json_decode($result, true);
$access_token = $token_data['access_token'] ?? '';

if (!$access_token) {
    set_flash_message('Payment verification failed.', 'error');
    header('Location: ' . BASE_URL . '/checkout.php');
    exit;
}

// Capture payment
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url . '/v2/checkout/orders/' . $token . '/capture');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

$headers = [];
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer ' . $access_token;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
curl_close($ch);

$capture_data = json_decode($result, true);

if (isset($capture_data['status']) && $capture_data['status'] === 'COMPLETED') {
    // Update order status
    update_order_payment_status($order_id, 'paid', $capture_data['id']);
    
    // Update transaction
    $stmt = $pdo->prepare("UPDATE payment_transactions SET status = 'completed', response_data = ? WHERE transaction_id = ?");
    $stmt->execute([json_encode($capture_data), $token]);
    
    // Create download links
    $order_items = get_order_items($order_id);
    foreach ($order_items as $item) {
        create_download_link($order_id, $item['product_id'], get_current_user_id());
    }
    
    // Send confirmation email
    $subject = 'Order Confirmation - ' . $order['order_number'];
    $body = "<h2>Thank you for your order!</h2>
            <p>Your order <strong>{$order['order_number']}</strong> has been confirmed.</p>
            <p>Total: " . format_price($order['total']) . "</p>
            <p>You can view your order and download your products from your account.</p>";
    send_email($order['customer_email'], $subject, $body);
    
    // Send notification to admin
    $admin_email = get_setting('order_notification_email', get_setting('site_email'));
    if ($admin_email) {
        $admin_subject = 'New Order - ' . $order['order_number'];
        $admin_body = "<h2>New Order Received</h2>
                      <p>Order Number: {$order['order_number']}</p>
                      <p>Customer: {$order['customer_name']}</p>
                      <p>Total: " . format_price($order['total']) . "</p>";
        send_email($admin_email, $admin_subject, $admin_body);
    }
    
    // Create admin notification
    create_admin_notification('order', 'New Order', 'Order ' . $order['order_number'] . ' has been paid', 'orders.php');
    
    set_flash_message('Payment successful! Thank you for your order.', 'success');
    header('Location: ' . BASE_URL . '/order-confirmation.php?order_id=' . $order_id);
    exit;
} else {
    set_flash_message('Payment could not be completed.', 'error');
    header('Location: ' . BASE_URL . '/checkout.php');
    exit;
}
