<?php
session_start();
$userid = $_SESSION['user_id']; // salesman ID from session
include "config.php"; // DB connection

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

$customer_id = $data['customer_id'];
$cart        = $data['cart'];
$note        = $data['order_note'] ?? '';
$order_id    = $data['order_id'] ?? null;
$salesman_id = $userid;

// Calculate total amount
$total_amount = 0;
foreach ($cart as $item) {
    $total_amount += $item['price'] * $item['quantity'];
}

try {
    // Start transaction
    $con->begin_transaction();

    if ($order_id) {
        // 🔹 Restore stock from old order items
        $stmt = $con->prepare("SELECT product_id, quantity FROM order_items WHERE order_id = ?");
        $stmt->bind_param("i", $order_id);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $restore = $con->prepare("UPDATE tbl_stock_items SET stock = stock + ? WHERE id = ?");
            $restore->bind_param("ii", $row['quantity'], $row['product_id']);
            $restore->execute();
            $restore->close();
        }
        $stmt->close();

        // 🔹 Delete old order items
        $stmt = $con->prepare("DELETE FROM order_items WHERE order_id = ?");
        $stmt->bind_param("i", $order_id);
        $stmt->execute();
        $stmt->close();

        // 🔹 Update existing order
        $stmt = $con->prepare("UPDATE orders 
                               SET customer_id = ?, salesman_id = ?, total_amount = ?, note = ? 
                               WHERE id = ?");
        $stmt->bind_param("iidsi", $customer_id, $salesman_id, $total_amount, $note, $order_id);
        $stmt->execute();
        $stmt->close();

    } else {
        // 🔹 Create new order
        $stmt = $con->prepare("INSERT INTO orders (customer_id, salesman_id, total_amount, note) 
                               VALUES (?, ?, ?, ?)");
        $stmt->bind_param("iids", $customer_id, $salesman_id, $total_amount, $note);
        $stmt->execute();
        $order_id = $stmt->insert_id;
        $stmt->close();
    }

    // 🔹 Insert new items into order_items with SAME order_id
    foreach ($cart as $item) {
        $total = $item['price'] * $item['quantity'];

        $stmt = $con->prepare("INSERT INTO order_items 
            (order_id, product_id, product_name, price, quantity, total, remarks) 
            VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param(
            "iisdiss",
            $order_id,
            $item['id'],
            $item['name'],
            $item['price'],
            $item['quantity'],
            $total,
            $item['remarks']
        );
        $stmt->execute();
        $stmt->close();

        // 🔹 Decrease stock (negative allowed)
        $stmt = $con->prepare("UPDATE tbl_stock_items SET stock = stock - ? WHERE id = ?");
        $stmt->bind_param("ii", $item['quantity'], $item['id']);
        $stmt->execute();
        $stmt->close();
    }

    // Commit transaction
    $con->commit();

    echo json_encode(["success" => true, "order_id" => $order_id]);

} catch (Exception $e) {
    // Rollback if error occurs
    $con->rollback();
    echo json_encode(["success" => false, "message" => $e->getMessage()]);
}
