<?php
/**
 * PayPal Payment Verification
 * Digital Product Store
 */

require_once __DIR__ . '/../config/database.php';

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

if (!$data || !isset($data['orderID']) || !isset($data['orderNumber'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid data']);
    exit;
}

$paypal_order_id = sanitize($data['orderID']);
$order_number = sanitize($data['orderNumber']);
$details = $data['details'] ?? [];

// Get order
$order = get_order_by_number($order_number);

if (!$order) {
    echo json_encode(['success' => false, 'message' => 'Order not found']);
    exit;
}

// Get PayPal settings
$paypal_settings = get_payment_settings('paypal');
$paypal_config = $paypal_settings['config'] ?? [];
$test_mode = $paypal_settings['test_mode'] ?? 1;

// Verify payment with PayPal API (optional but recommended)
$paypal_api_url = $test_mode ? 'https://api.sandbox.paypal.com' : 'https://api.paypal.com';

// For simplicity, we'll trust the client-side data but verify the amount matches
$paypal_amount = $details['purchase_units'][0]['payments']['captures'][0]['amount']['value'] ?? 0;
$expected_amount = number_format($order['total'], 2, '.', '');

if (abs(floatval($paypal_amount) - floatval($expected_amount)) > 0.01) {
    echo json_encode(['success' => false, 'message' => 'Amount mismatch']);
    exit;
}

try {
    // Update order status
    $stmt = $pdo->prepare("UPDATE orders SET 
        payment_status = 'completed',
        order_status = 'completed',
        transaction_id = ?,
        updated_at = NOW()
        WHERE order_number = ?");
    $stmt->execute([$paypal_order_id, $order_number]);
    
    // Clear cart and coupon
    clear_cart();
    clear_coupon();
    
    // Send order confirmation email
    send_order_confirmation($order['id']);
    
    // Log activity
    log_activity('Payment Completed', "PayPal payment for order {$order_number}");
    
    echo json_encode(['success' => true]);
    
} catch (PDOException $e) {
    error_log('PayPal verification failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Database error']);
}
?>