<?php

declare(strict_types=1);

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

ini_set('display_errors','0');

error_reporting(E_ALL);

mb_internal_encoding('UTF-8');

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

try {

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

    require_once STRIPE_SDK_PATH . '/init.php';

    \Stripe\Stripe::setApiKey(
        STRIPE_SECRET_KEY
    );

    $raw =
    file_get_contents('php://input');

    if(!$raw){

        throw new Exception(
            'Missing request body'
        );
    }

    $data = json_decode(
        $raw,
        true
    );

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

        throw new Exception(
            'Amount missing'
        );
    }

    $amount =
    (float)$data['amount'];

    if($amount <= 0){

        throw new Exception(
            'Invalid amount'
        );
    }

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

        'amount' =>
        (int)round($amount * 100),

        '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(Throwable $e){

    http_response_code(500);

    echo json_encode([

        'success' => false,

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

    ]);
}
