<?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';

try {

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

if(empty($data['payment_intent'])){
throw new Exception('Missing payment intent');
}

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

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

$customerEmail =
trim((string)($data['email'] ?? ''));

$customerPhone =
trim((string)($data['phone'] ?? ''));

$cart =
$data['cart'] ?? [];

/*
|--------------------------------------------------------------------------
| SAVE ORDER
|--------------------------------------------------------------------------
| FIX:
| save customer email + phone directly into orders table
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
INSERT INTO orders(

order_number,
payment_method,
subtotal,
tax,
total,
stripe_payment_intent,
customer_email,
customer_phone,
status

)
VALUES(
?,
'credit',
?,
0,
?,
?,
?,
?,
'paid'
)
");

$stmt->execute([

$orderNumber,
$amount,
$amount,
$data['payment_intent'],
$customerEmail,
$customerPhone

]);

$orderId =
(int)$pdo->lastInsertId();

/*
|--------------------------------------------------------------------------
| SAVE ORDER ITEMS
|--------------------------------------------------------------------------
*/

if(is_array($cart)){

foreach($cart as $item){

$productId =
(int)($item['id'] ?? 0);

$quantity =
(int)($item['quantity'] ?? 1);

if($quantity < 1){
$quantity = 1;
}

$price =
(float)($item['price'] ?? 0);

$itemStmt =
$pdo->prepare("
INSERT INTO order_items(

order_id,
product_id,
quantity,
price

)
VALUES(
?,
?,
?,
?
)
");

$itemStmt->execute([

$orderId,
$productId,
$quantity,
$price

]);

}
}

/*
|--------------------------------------------------------------------------
| EMAIL RECEIPT
|--------------------------------------------------------------------------
*/

$receiptText =
"Executive Protection Institute

Invoice:
".$orderNumber."

Total:
$".number_format($amount,2)."

Items Purchased:
";

foreach($cart as $item){

$receiptText .=
"- ".
($item['name'] ?? 'Product').
" | Qty: ".
((int)($item['quantity'] ?? 1)).
" | Price: $".
number_format(
(float)($item['price'] ?? 0),
2
).
"\n";

}

/*
|--------------------------------------------------------------------------
| SEND TO CUSTOMER EMAIL
|--------------------------------------------------------------------------
*/

if(
$customerEmail !== ''
&&
filter_var($customerEmail, FILTER_VALIDATE_EMAIL)
){

send_receipt_email(
$customerEmail,
'Receipt '.$orderNumber,
$receiptText
);

}

echo json_encode([
'success' => true,
'order_id' => $orderId
]);

} catch(Throwable $e){

http_response_code(500);

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

}
?>