<?php
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='creditpurchase-'.time().'-'.random_int(1000,9999);
$amount=(float)$data['amount'];
$stmt=$pdo->prepare("INSERT INTO orders(order_number,payment_method,subtotal,tax,discount,total,stripe_payment_intent,status) VALUES(?,'credit',?,0,0,?,?,'paid')");
$stmt->execute([$orderNumber,$amount,$amount,$data['payment_intent']]);
$orderId=(int)$pdo->lastInsertId();
if(isset($data['cart']) && is_array($data['cart'])){foreach($data['cart'] as $item){$i=$pdo->prepare("INSERT INTO order_items(order_id,product_name,quantity,price) VALUES(?,?,1,?)");$i->execute([$orderId,$item['name'],$item['price']]);}}
$r=$pdo->prepare("INSERT INTO cash_receipts(order_number,customer_email,customer_phone,total_amount,payment_method,status) VALUES(?,?,?,?, 'credit','paid')");
$r->execute([$orderNumber,$data['email'],$data['phone'],$amount]);
if(!empty($data['email'])){send_receipt_email($data['email'],'Receipt '.$orderNumber,'Thank you for your purchase. Invoice: '.$orderNumber);} echo json_encode(['success'=>true,'order_number'=>$orderNumber]); ?>