<?php

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

// Ensure native database errors are handled safely by JSON response blocks instead of breaking Flutter's parser
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once '../config/database.php';

$db = getDB();

// Decode incoming raw payload body stream 
$data = json_decode(file_get_contents("php://input"), true);

if (!$data) {
    echo json_encode([
        "success" => false,
        "message" => "Invalid JSON"
    ]);
    exit;
}

// Sanitize client input variables before running database operations
$full_name = $db->real_escape_string($data['full_name'] ?? '');
$phone     = $db->real_escape_string($data['phone'] ?? '');
$address   = $db->real_escape_string($data['address'] ?? '');
$subtotal  = floatval($data['subtotal'] ?? 0);
$delivery  = floatval($data['delivery'] ?? 0);
$total     = floatval($data['total'] ?? 0);
$items     = $data['items'] ?? [];

if (empty($full_name) || empty($phone) || empty($address)) {
    echo json_encode([
        "success" => false,
        "message" => "Missing Fields"
    ]);
    exit;
}

// Generate sequential timestamp-backed invoice tracker number
$order_number = "ORD" . time();

// 1. Insert master customer metadata row record into 'orders' table
$insertOrder = $db->query("INSERT INTO orders(
    order_number,
    full_name,
    phone,
    address,
    subtotal,
    delivery_charge,
    total,
    payment_method,
    status
) VALUES(
    '$order_number',
    '$full_name',
    '$phone',
    '$address',
    '$subtotal',
    '$delivery',
    '$total',
    'Cash On Delivery',
    'Pending'
)");

if (!$insertOrder) {
    echo json_encode([
        "success" => false,
        "message" => $db->error
    ]);
    exit;
}

$order_id = $db->insert_id;

// 2. Loop through purchased items list to insert order records and update stock
foreach ($items as $item) {
    $product_id   = intval($item['product']['id'] ?? 0);
    $product_name = $db->real_escape_string($item['product']['name_bn'] ?? '');
    
    $product_image = '';
    if (isset($item['product']['image'])) {
        $product_image = $db->real_escape_string($item['product']['image']);
    }

    $quantity  = intval($item['quantity'] ?? 1);
    $price     = floatval($item['product']['price'] ?? 0);
    
    $variation = '';
    if (isset($item['variation'])) {
        $variation = $db->real_escape_string($item['variation']);
    }

    // Insert item details into historical cross-reference table 'order_items'
    $db->query("INSERT INTO order_items(
        order_id,
        product_id,
        product_name,
        product_image,
        quantity,
        price,
        variation
    ) VALUES(
        '$order_id',
        '$product_id',
        '$product_name',
        '$product_image',
        '$quantity',
        '$price',
        '$variation'
    )");

    // 3. Update 'products' table stock and increment total sales counters safely
    if ($product_id > 0) {
        $db->query("UPDATE products 
                    SET stock = GREATEST(0, stock - $quantity),
                        total_sales = total_sales + $quantity 
                    WHERE id = $product_id");
    }
}

// Return unified clean success signal directly to Flutter app
echo json_encode([
    "success"      => true,
    "message"      => "Order Placed Successfully",
    "order_number" => $order_number
]);