<?php
header('Content-Type: application/json');
require_once 'config.php';

$order_id = $_POST['order_id'] ?? '';
$customer_id = $_POST['customer_id'] ?? '';
$total = $_POST['total'] ?? '';
$items = $_POST['items'] ?? ''; // e.g. "Jollof Rice x2, Egusi Soup x1"
$delivered_at = date('Y-m-d H:i:s');

if (!$order_id || !$customer_id || !$total) {
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit;
}

// Insert into receipts table
$stmt = $conn->prepare("INSERT INTO receipts (order_id, customer_id, total_amount, items, delivered_at) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("isdss", $order_id, $customer_id, $total, $items, $delivered_at);
$success = $stmt->execute();
$stmt->close();

// Optionally update order status
if ($success) {
    $stmt2 = $conn->prepare("UPDATE orders SET status = 'Delivered' WHERE id = ?");
    $stmt2->bind_param("i", $order_id);
    $stmt2->execute();
    $stmt2->close();
}

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