<?php
/**
 * Stripe Payment Success Handler
 * Digital Marketplace
 */

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

$order_id = (int)($_GET['order_id'] ?? 0);
$payment_intent = sanitize($_GET['payment_intent'] ?? '');

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

// Get order
$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;
}

// Update order status
try {
    $stmt = $pdo->prepare("UPDATE orders SET 
        payment_status = 'paid',
        payment_id = ?,
        order_status = 'processing',
        paid_at = NOW(),
        updated_at = NOW()
        WHERE id = ?");
    $stmt->execute([$payment_intent, $order_id]);
    
    // Log payment
    $stmt = $pdo->prepare("INSERT INTO payment_logs 
        (order_id, gateway, transaction_id, amount, currency, status, created_at)
        VALUES (?, 'stripe', ?, ?, ?, 'success', NOW())");
    $stmt->execute([
        $order_id,
        $payment_intent,
        $order['total'],
        CURRENCY
    ]);
    
    // Send confirmation email
    send_order_confirmation($order_id);
    
    // Log activity
    log_activity('payment_completed', "Stripe payment received for order #{$order['order_number']}");
    
    set_flash_message('Payment successful! Thank you for your purchase.', 'success');
    header('Location: ' . BASE_URL . '/account/order-view.php?id=' . $order_id);
    exit;
    
} catch (PDOException $e) {
    error_log("Stripe success error: " . $e->getMessage());
    set_flash_message('Payment processed but there was an error updating your order. Please contact support.', 'warning');
    header('Location: ' . BASE_URL . '/account/order-view.php?id=' . $order_id);
    exit;
}
