<?php

declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');

mb_internal_encoding('UTF-8');

ini_set('default_charset', 'UTF-8');

require_once '../../private/stripe_terminal_config.php';

require_once STRIPE_SDK_PATH . '/init.php';

\Stripe\Stripe::setApiKey(
    STRIPE_SECRET_KEY
);

try {

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

    if(
        !isset($data['amount'])
    ){

        throw new Exception(
            'Amount required'
        );
    }

    $amount =
    round(
        ((float)$data['amount']) * 100
    );

    if($amount < 50){

        throw new Exception(
            'Minimum amount is 0.50'
        );
    }

    $paymentIntent =
    \Stripe\PaymentIntent::create([

        'amount' => $amount,

        'currency' => 'usd',

        'payment_method_types' => [
            'card_present'
        ],

        'capture_method' => 'automatic'

    ]);

    echo json_encode([

        'success' => true,

        'client_secret' =>
        $paymentIntent->client_secret,

        'payment_intent_id' =>
        $paymentIntent->id

    ]);

} catch(Exception $e){

    http_response_code(500);

    echo json_encode([

        'error' => $e->getMessage()

    ]);
}
