<?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/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 =
    'stripepurchase-' .
    time() .
    '-' .
    random_int(1000,9999);

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

    $overrideReason =
    $data['override_reason'] ?? '';

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

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

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

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

        order_number,
        payment_method,
        subtotal,
        tax,
        discount,
        total,
        stripe_payment_intent,
        status,
        override_reason

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

    $stmt->execute([

        $orderNumber,
        $amount,
        $amount,
        $data['payment_intent'],
        $overrideReason

    ]);

    $receiptText =
"Executive Protection Institute

Invoice:
".$orderNumber."

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

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

Customer Email:
".$email."

Customer Phone:
".$phone."

Items Purchased:
";

    if(is_array($cart)){

        foreach($cart as $item){

            $receiptText .=
            "- ".
            $item['name'].
            " - $".
            number_format(
                (float)$item['price'],
                2
            ).
            "\n";
        }
    }

    if(!empty($email)){

        send_receipt_email(

            $email,

            'Receipt '.$orderNumber,

            $receiptText

        );
    }

    echo json_encode([

        'success' => true,

        'invoice' => $orderNumber

    ]);

} catch(Exception $e){

    http_response_code(500);

    echo json_encode([

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

    ]);
}
