<?php
/**
 * Stripe Payment Intent Creation
 * Digital Marketplace
 */

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

header('Content-Type: application/json');

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

$order_id = (int)($data['order_id'] ?? 0);

if (!$order_id) {
    json_response(['success' => false, 'message' => 'Invalid order']);
}

// Get order
$order = get_order_by_id($order_id);

if (!$order || $order['user_id'] != get_current_user_id()) {
    json_response(['success' => false, 'message' => 'Order not found']);
}

// Get Stripe settings
$stripe = get_payment_gateway('stripe');
if (!$stripe || !$stripe['is_active']) {
    json_response(['success' => false, 'message' => 'Stripe is not available']);
}

$config = $stripe['config'];
$secret_key = $config['secret_key'] ?? '';

if (empty($secret_key)) {
    json_response(['success' => false, 'message' => 'Stripe not configured']);
}

// Convert amount to cents
$amount_cents = round($order['total'] * 100);

// Create payment intent using Stripe API
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://api.stripe.com/v1/payment_intents');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
    'amount' => $amount_cents,
    'currency' => strtolower(CURRENCY),
    'metadata' => [
        'order_id' => $order_id,
        'order_number' => $order['order_number']
    ]
]));
curl_setopt($ch, CURLOPT_USERPWD, $secret_key . ':');

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($http_code !== 200) {
    $error = json_decode($response, true);
    json_response(['success' => false, 'message' => $error['error']['message'] ?? 'Failed to create payment intent']);
}

$intent = json_decode($response, true);

json_response([
    'success' => true,
    'client_secret' => $intent['client_secret']
]);
