<?php
declare(strict_types=1);

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

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

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

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

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

$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,
$data['payment_intent']
]);

$receiptText =
"Executive Protection Institute

Invoice:
".$orderNumber."

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

Payment Intent:
".$data['payment_intent'];

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

echo json_encode([
'success'=>true
]);
