<?php
require 'config.php';
require 'vendor/autoload.php';

// -----------------------------
// Database Connection
// -----------------------------
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) {
    die(json_encode(['error' => 'DB Connection Failed']));
}

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

$amount_cents = $data['amount'] ?? 0;
$currency = $data['currency'] ?? 'USD';
$invoiceId = $data['invoice_id'] ?? null;

// -----------------------------
// Fetch invoice & payment method
// -----------------------------
$stmt = $conn->prepare("SELECT payment_method, payment_method_id FROM invoices WHERE id = ?");
$stmt->bind_param("i", $invoiceId);
$stmt->execute();
$result = $stmt->get_result();
$invoice = $result->fetch_assoc();
$stmt->close();

if (!$invoice) {
    echo json_encode(['error' => 'Invoice not found']);
    exit;
}

// Gateway name
$paymentMethod = strtolower($invoice['payment_method']);

// Default IDs
$defaultIds = [
    'square' => 1,
    'stripe' => 2,
    'paypal' => 3
];

// Actual payment_method_id
$pmId = $invoice['payment_method_id'] ?? null;
if (empty($pmId)) {
    $pmId = $defaultIds[$paymentMethod] ?? null;
}

// -----------------------------
// Fetch payment method record
// -----------------------------
$stmt = $conn->prepare("SELECT * FROM payment_methods WHERE id = ? AND status = 1");
$stmt->bind_param("i", $pmId);
$stmt->execute();
$gateway = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$gateway) {
    echo json_encode(['error' => 'Payment method not active']);
    exit;
}

// -----------------------------
// Stripe Key from DB
// -----------------------------
$stripeSecret = trim($gateway['stripe_secret_key'] ?? '');

// $stripeSecret = trim("sk_test_51NxGHQIrZYESSIgqOH9qryUbDk14t7YGfH0R2EEGVOVkPRcSkxIS1zeZ1LxNiU82e2ZHnbXHbZ1Ur5xUZMRUZGQk00WSXtcCIU" ?? ''); //sandbox secretkey

if (empty($stripeSecret)) {
    echo json_encode(['error' => 'Stripe secret key missing in DB']);
    exit;
}

// Set Stripe secret key
\Stripe\Stripe::setApiKey($stripeSecret);

// -----------------------------
// Create Stripe Payment Intent
// -----------------------------
header('Content-Type: application/json');

try {
    if ($amount_cents <= 0) {
        throw new Exception('Invalid amount');
    }

    $intent = \Stripe\PaymentIntent::create([
        'amount' => $amount_cents,
        'currency' => strtolower($currency),
        'metadata' => ['invoice_id' => $invoiceId]
    ]);

    echo json_encode([
        'client_secret' => $intent->client_secret
    ]);

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