<?php
require('../../vendor/autoload.php');
include_once('../../includes/db.php');
header('Content-Type: application/json');
ini_set('display_errors', 1);
error_reporting(E_ALL);

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

$user_id = $data['user_id'] ?? null;
$items = json_decode($data['cart_items'] ?? '[]', true);
$address = $data['address'] ?? '';
$location = $data['location'] ?? '';
$name = $data['name'] ?? '';
$phone = $data['phone'] ?? '';
$payment_type = $data['payment_type'] ?? 'COD';
$delivery_fee = floatval($data['delivery_fee'] ?? 0.0);

if (!$user_id || !is_array($items) || empty($items)) {
    echo json_encode(["status" => false, "message" => "Missing user ID or items"]);
    exit;
}

try {
    $subtotal = 0;

    foreach ($items as $item) {
        $product_id = $item['product_id'];
        $quantity = $item['quantity'];

        $product = fetchOne("SELECT price FROM products WHERE id = ?", [$product_id]);
        $price = $product['price'] ?? 0;
        $subtotal += $price * $quantity;
    }

    $total_price = $subtotal + $delivery_fee;

    // 🟢 Insert the order with status "placed"
    execute("INSERT INTO orders (user_id, address, location, name, phone, payment_type, delivery_fee, subtotal, total_price, status, created_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'placed', NOW())", [
        $user_id, $address, $location, $name, $phone, $payment_type, $delivery_fee, $subtotal, $total_price
    ]);

    global $conn;
    $order_id = $conn->insert_id;

    foreach ($items as $item) {
        $product_id = $item['product_id'];
        $quantity = $item['quantity'];
        $product = fetchOne("SELECT price FROM products WHERE id = ?", [$product_id]);
        $price = $product['price'] ?? 0;

        execute("INSERT INTO order_items (order_id, product_id, quantity, price)
                 VALUES (?, ?, ?, ?)", [$order_id, $product_id, $quantity, $price]);
    }

    echo json_encode(["status" => true, "message" => "Order placed successfully", "order_id" => $order_id]);
} catch (Exception $e) {
    echo json_encode(["status" => false, "message" => "Error: " . $e->getMessage()]);
}
?>
