<?php

declare(strict_types=1);

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

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

require_once STRIPE_SDK_PATH.'/init.php';

\Stripe\Stripe::setApiKey(STRIPE_SECRET_KEY);

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

if(
empty($data['customer_email']) ||
empty($data['customer_phone']) ||
empty($data['amount'])
){
http_response_code(400);

echo json_encode([
'error'=>'Missing required fields'
]);

exit;
}

try {

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

$paymentIntent =
\Stripe\PaymentIntent::create([
'amount'=>$amount,
'currency'=>'usd',
'payment_method_types'=>['card']
]);

\Stripe\Terminal\Reader::processPaymentIntent(
STRIPE_READER_ID,
[
'payment_intent'=>$paymentIntent->id
]
);

$orderNumber =
'stripepurchase-'.
time().
'-'.
random_int(1000,9999);

$total = $amount / 100;

$stmt = $pdo->prepare("
INSERT INTO orders(
order_number,
payment_method,
subtotal,
tax,
discount,
total,
stripe_payment_intent,
status
)
VALUES(
?,
'stripe',
?,
0,
0,
?,
?,
'paid'
)
");

$stmt->execute([
$orderNumber,
$total,
$total,
$paymentIntent->id
]);

$receiptText =
"Executive Protection Institute

Invoice:
".$orderNumber."

Stripe WisePOS E Payment

Amount:
$".number_format($total,2)."

Payment Intent:
".$paymentIntent->id;

send_receipt_email(
$data['customer_email'],
'Stripe Receipt '.$orderNumber,
$receiptText
);

echo json_encode([
'success'=>true,
'payment_intent'=>$paymentIntent->id,
'invoice'=>$orderNumber
]);

} catch(Exception $e){

http_response_code(500);

echo json_encode([
'error'=>$e->getMessage()
]);

}
