<?php
require_once '../../config/db.php';
require_once '../../core/Auth.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

try {
    $user_id = Auth::check();
    $data = json_decode(file_get_contents("php://input"));
    
    if (!isset($data->amount) || !isset($data->provider)) {
        throw new Exception("Missing amount or provider");
    }

    $amount = (int)$data->amount; // Diamonds
    $provider = $data->provider; // 'stripe', 'paypal'

    // Verify Provider is Active
    $stmt = $pdo->prepare("SELECT * FROM payment_gateways WHERE provider = ? AND is_active = TRUE");
    $stmt->execute([$provider]);
    $gateway = $stmt->fetch();

    if (!$gateway) {
        throw new Exception("Payment provider not available");
    }

    // Calculate Price (Mock: 100 Diamonds = $1.00)
    $price_usd = $amount / 100;

    $response = [
        'status' => 'pending',
        'amount_diamonds' => $amount,
        'price_usd' => $price_usd,
        'provider' => $provider
    ];

    if ($provider === 'stripe' || $provider === 'paypal') {
        // El frontend procesará Stripe (que incluye Apple Pay y Google Pay nativamente) y PayPal.
        // Simulamos la creación del Intento de Pago.
        $response['intent_id'] = 'pi_mock_' . bin2hex(random_bytes(10));
        $response['client_secret'] = 'secret_mock_' . bin2hex(random_bytes(10));
        
        // Cuando configures Stripe real, aquí iría:
        // \Stripe\Stripe::setApiKey($gateway['secret_key']);
        // $paymentIntent = \Stripe\PaymentIntent::create([...]);
    } else if (in_array($provider, ['zelle', 'bank_transfer', 'bank_transfer_2', 'bank_transfer_3', 'crypto'])) {
        // Pagos manuales (Zelle, Banco 1/2/3, Crypto)
        // Devolvemos la información configurada en el Admin Panel para que el usuario pueda pagar.
        $response['payment_address'] = $gateway['api_key'];
        $response['payment_instructions'] = $gateway['secret_key'];
        $response['message'] = "Por favor realiza el pago exacto y envía tu comprobante (Receipt).";
        $response['intent_id'] = 'manual_' . bin2hex(random_bytes(10));
    }

    // Opcional: Registrar la transacción inicial como pendiente en la DB
    $stmt = $pdo->prepare("INSERT INTO transactions (user_id, amount_usd, diamonds, type, provider, status) VALUES (?, ?, ?, 'purchase', ?, 'pending')");
    $stmt->execute([$user_id, $price_usd, $amount, $provider]);
    $response['transaction_id'] = $pdo->lastInsertId();

    echo json_encode($response);

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
