<?php
require_once '../../vendor/autoload.php';  // Composer autoload for Stripe

\Stripe\Stripe::setApiKey('your-secret-key'); // Replace with your secret key

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

if (!isset($input['payment_method_id']) || !isset($input['amount'])) {
    echo json_encode(['success' => false, 'message' => 'Missing payment data']);
    exit;
}

$paymentMethodId = $input['payment_method_id'];
$amount = $input['amount'];  // amount in cents

try {
    // Create a PaymentIntent
    $paymentIntent = \Stripe\PaymentIntent::create([
        'amount' => $amount,
        'currency' => 'mwk',  // Malawi Kwacha, make sure Stripe supports this, else use 'usd' or 'eur'
        'payment_method' => $paymentMethodId,
        'confirmation_method' => 'manual',
        'confirm' => true,
    ]);

    if ($paymentIntent->status == 'requires_action' && $paymentIntent->next_action->type == 'use_stripe_sdk') {
        // Tell the client to handle the action
        echo json_encode([
            'success' => false,
            'requires_action' => true,
            'payment_intent_client_secret' => $paymentIntent->client_secret,
        ]);
    } elseif ($paymentIntent->status == 'succeeded') {
        // Payment succeeded
        echo json_encode(['success' => true]);
    } else {
        // Unexpected status
        echo json_encode(['success' => false, 'message' => 'Invalid PaymentIntent status']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
