<?php
session_start();
include 'includes/connect.php';

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

error_reporting(E_ALL);
ini_set('display_errors', 1);

/* ================= USER ================= */
$user_id = $_SESSION['user_id'] ?? $_SESSION['distributor_id'] ?? $_SESSION['id'] ?? 0;

if(!$user_id){
    echo json_encode(["success"=>false,"message"=>"Login required"]);
    exit;
}

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

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

/* ================= SHIPPING ================= */
$name     = mysqli_real_escape_string($conn, $data['name'] ?? '');
$mobile   = mysqli_real_escape_string($conn, $data['mobile'] ?? '');
$address  = mysqli_real_escape_string($conn, $data['address'] ?? '');
$city     = mysqli_real_escape_string($conn, $data['city'] ?? '');
$pincode  = mysqli_real_escape_string($conn, $data['pincode'] ?? '');
$village  = mysqli_real_escape_string($conn, $data['village'] ?? '');

/* ================= PAYMENT ================= */
$payment_method   = mysqli_real_escape_string($conn, $data['payment'] ?? '');
$discount         = floatval($data['discount'] ?? 0);
$payment_amount   = floatval($data['payment_amount'] ?? 0);
$payment_type     = mysqli_real_escape_string($conn, $data['payment_type'] ?? '');
$payment_mode     = mysqli_real_escape_string($conn, $data['payment_mode'] ?? '');
$delivered_trays  = intval($data['delivered_trays'] ?? 0);

/* ================= ITEMS ================= */
$items = $data['items'] ?? [];

if(empty($items)){
    echo json_encode(["success"=>false,"message"=>"Cart empty"]);
    exit;
}

/* ================= CALCULATION ================= */
$total_amount = 0;
$total_trays = 0;

foreach($items as $it){
    $price = floatval($it['price'] ?? 0);
    $qty   = intval($it['qty'] ?? 0);

    $total_amount += ($price * $qty);
    $total_trays += $qty;
}

$net_amount = $total_amount - $discount;
if($net_amount < 0) $net_amount = 0;

/* ================= INSERT ORDER ================= */
$order_sql = "
INSERT INTO orders (
user_id,
name,
mobile,
address,
city,
pincode,
village,
payment_method,
total_amount,
discount,
net_amount,
payment_amount,
payment_type,
payment_mode,
delivered_trays,
total_trays,
created_at
) VALUES (
'$user_id',
'$name',
'$mobile',
'$address',
'$city',
'$pincode',
'$village',
'$payment_method',
'$total_amount',
'$discount',
'$net_amount',
'$payment_amount',
'$payment_type',
'$payment_mode',
'$delivered_trays',
'$total_trays',
NOW()
)
";

if(!mysqli_query($conn, $order_sql)){
    echo json_encode([
        "success"=>false,
        "message"=>"Order insert failed",
        "error"=>mysqli_error($conn)
    ]);
    exit;
}

$order_id = mysqli_insert_id($conn);

/* ================= ITEMS + INVENTORY UPDATE ================= */
foreach($items as $it){

    $product_id = intval($it['id']);
    $price = floatval($it['price']);
    $qty = intval($it['qty']);
    $total = $price * $qty;

    $cart_q = mysqli_query($conn, "SELECT * FROM cart WHERE id='$product_id' AND user_id='$user_id'");
    $cart = mysqli_fetch_assoc($cart_q);

    $brand = mysqli_real_escape_string($conn, $cart['brand'] ?? '');
    $label_name = mysqli_real_escape_string($conn, $cart['label_name'] ?? '');
    $variety_id = intval($cart['variety_id'] ?? 0);

    /* batch_id from inventory system */
    $batch_id = intval($it['batch_id'] ?? 0);

    /* ================= ORDER ITEMS ================= */
    mysqli_query($conn, "
        INSERT INTO order_items (
            order_id,
            brand,
            variety_id,
            label_name,
            quantity,
            trays,
            price,
            total,
            batch_id
        ) VALUES (
            '$order_id',
            '$brand',
            '$variety_id',
            '$label_name',
            '$qty',
            '$qty',
            '$price',
            '$total',
            '$batch_id'
        )
    ");

    /* ================= INVENTORY UPDATE ================= */
    if($variety_id > 0 && $batch_id > 0){

        $stock_q = mysqli_query($conn, "
            SELECT tray_no, sold_trays 
            FROM inventory_management 
            WHERE variety_id='$variety_id' 
            AND batch_id='$batch_id'
        ");

        $stock = mysqli_fetch_assoc($stock_q);

        $current_tray = intval($stock['tray_no'] ?? 0);
        $sold = intval($stock['sold_trays'] ?? 0);

        $new_tray = $current_tray - $qty;
        if($new_tray < 0) $new_tray = 0;

        $new_sold = $sold + $qty;

        mysqli_query($conn, "
            UPDATE inventory_management 
            SET 
                tray_no='$new_tray',
                sold_trays='$new_sold'
            WHERE 
                variety_id='$variety_id' 
                AND batch_id='$batch_id'
        ");
    }

    /* ================= REMOVE CART ================= */
    mysqli_query($conn, "DELETE FROM cart WHERE id='$product_id' AND user_id='$user_id'");
}

/* ================= RESPONSE ================= */
echo json_encode([
    "success"=>true,
    "message"=>"Order placed successfully with inventory & sold tracking",
    "order_id"=>$order_id
]);
?>