<?php

declare(strict_types=1);

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

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

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

if (
    empty($data['customer_email']) ||
    empty($data['customer_phone']) ||
    empty($data['cart'])
) {

    http_response_code(400);

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

    exit;
}

$customerEmail = trim($data['customer_email']);
$customerPhone = trim($data['customer_phone']);
$cart = $data['cart'];

$subtotal = 0;
$receiptLines = [];

foreach ($cart as $item) {

    $lineTotal =
        (float)$item['price'] *
        (int)$item['quantity'];

    $subtotal += $lineTotal;

    $receiptLines[] =
        $item['name'] .
        ' x' . $item['quantity'] .
        ' - $' . number_format($lineTotal, 2);

    $stmt = $pdo->prepare("
        UPDATE products
        SET quantity = quantity - ?
        WHERE id = ?
    ");

    $stmt->execute([
        $item['quantity'],
        $item['id']
    ]);
}

$tax = round($subtotal * 0.00, 2);

$total = $subtotal + $tax;

$invoiceNumber =
    'cashpurchase-' .
    time() .
    '-' .
    random_int(1000, 9999);

$receiptText =
"Executive Protection Institute

Invoice: " . $invoiceNumber . "

Date: " . date('Y-m-d H:i:s') . "

--------------------------------

" .
implode("\n", $receiptLines) . "

--------------------------------

Subtotal: $" . number_format($subtotal, 2) . "
Tax: $" . number_format($tax, 2) . "
Total: $" . number_format($total, 2) . "

Customer Email:
" . $customerEmail . "

Customer Phone:
" . $customerPhone;

$stmt = $pdo->prepare("
INSERT INTO cash_receipts(
invoice_number,
customer_email,
customer_phone,
subtotal,
tax,
total,
receipt_text
)
VALUES(?,?,?,?,?,?,?)
");

$stmt->execute([
    $invoiceNumber,
    $customerEmail,
    $customerPhone,
    $subtotal,
    $tax,
    $total,
    $receiptText
]);

$receiptId = $pdo->lastInsertId();

$orderNumber = $invoiceNumber;

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

$stmt->execute([
    $orderNumber,
    $subtotal,
    $tax,
    $total
]);

$orderId = $pdo->lastInsertId();

foreach ($cart as $item) {

    $lineTotal =
        (float)$item['price'] *
        (int)$item['quantity'];

    $stmt = $pdo->prepare("
    INSERT INTO order_items(
    order_id,
    product_id,
    quantity,
    price,
    total
    )
    VALUES(?,?,?,?,?)
    ");

    $stmt->execute([
        $orderId,
        $item['id'],
        $item['quantity'],
        $item['price'],
        $lineTotal
    ]);
}

send_receipt_email(
    $customerEmail,
    'Your Receipt - ' . $invoiceNumber,
    $receiptText
);

echo json_encode([
    'success' => true,
    'receipt_id' => $receiptId,
    'invoice_number' => $invoiceNumber
]);
