<?php
require_once 'conn.php';
checkLogin();

$isedit = false;
$id = $_POST['id'] ?? '';
if (!empty($id) && is_numeric($id)) {
    $isedit = true;
    
    // 检查是否为管理员,非管理员只能编辑自己的订单
    $isAdmin = checkIfAdmin();
    if (!$isAdmin) {
        // 验证订单所有权
        $checkOwnershipQuery = "SELECT id FROM orders WHERE id = $id AND employee_id = " . $_SESSION['employee_id'];
        $ownershipResult = mysqli_query($conn, $checkOwnershipQuery);
        
        if (mysqli_num_rows($ownershipResult) === 0) {
            echo "<script>alert('您没有权限编辑此订单!');history.back();</script>";
            exit;
        }
    }
}

// 获取表单数据 - 订单基本信息
$order_code = mysqli_real_escape_string($conn, htmlspecialchars($_POST['order_code'], ENT_QUOTES, 'UTF-8'));
$customer_id = (int)$_POST['customer_id'];
$contact_id = !empty($_POST['contact_id']) ? (int)$_POST['contact_id'] : "NULL";
$employee_id = $_SESSION['employee_id'];
$order_date = mysqli_real_escape_string($conn, $_POST['order_date']);

// 设置已删除字段的默认值
$delivery_date = "NULL";
$actual_delivery_date = "NULL";
$order_status = 1; // 默认为"待确认"
$payment_status = 0; // 默认为"未付款"
$currency = "CNY"; // 默认为人民币
$notes = mysqli_real_escape_string($conn, htmlspecialchars($_POST['notes'], ENT_QUOTES, 'UTF-8'));
$internal_notes = ""; // 默认为空

// 获取订单项信息
$items = $_POST['items'] ?? [];

// 计算订单总额
$subtotal = 0;
$discount_amount = !empty($_POST['discount_amount']) ? (float)$_POST['discount_amount'] : 0;

foreach ($items as $item) {
    $quantity = (int)$item['quantity'];
    $total_price = (float)$item['total_price']; // 直接使用用户输入的总价
    $subtotal += $total_price;
}

$total_amount = $subtotal - $discount_amount;

// 验证必填字段
if (empty($order_code)) {
    echo "<script>alert('销售订单号不能为空');history.back();</script>";
    exit;
}

if ($customer_id <= 0) {
    echo "<script>alert('请选择客户');history.back();</script>";
    exit;
}

if (empty($items)) {
    echo "<script>alert('订单必须包含至少一个产品');history.back();</script>";
    exit;
}

$customer_country=0;
// 检查客户国家和产品销售限制
$customer_query = "SELECT cs_country FROM customer WHERE id = $customer_id LIMIT 1";
$customer_result = mysqli_query($conn, $customer_query);

if ($customer_result && mysqli_num_rows($customer_result) > 0) {
    $customer_data = mysqli_fetch_assoc($customer_result);
    $customer_country = $customer_data['cs_country'];
    
    if (!empty($customer_country)) {
        $restricted_products = [];
        
        foreach ($items as $item) {
            if (empty($item['product_id'])) continue;
            
            $product_id = (int)$item['product_id'];
            
            // 获取产品详情,包括nosale字段
            $product_query = "SELECT ProductName, nosale FROM products WHERE id = $product_id LIMIT 1";
            $product_result = mysqli_query($conn, $product_query);
            
            if ($product_result && mysqli_num_rows($product_result) > 0) {
                $product_data = mysqli_fetch_assoc($product_result);
                $nosale_countries = $product_data['nosale'];
                
                // 检查客户所在国家是否在销售限制列表中
                if (!empty($nosale_countries)) {
                    $restricted_countries = explode(',', $nosale_countries);
                    if (in_array($customer_country, $restricted_countries)) {
                        $restricted_products[] = $product_data['ProductName'];
                    }
                }
            }
        }
        
        // 如果有限制销售的产品,显示错误并返回
        if (!empty($restricted_products)) {
            $restricted_product_names = implode('、', $restricted_products);
            echo "<script>alert('以下产品不能销售给所选客户所在的国家/地区: {$restricted_product_names}');history.back();</script>";
            exit;
        }
    }
}

// 处理保存
if ($isedit) {

    // 更新订单基本信息
    $sql = "UPDATE orders SET 
            order_code = '$order_code', 
            customer_id = $customer_id, 
            contact_id = $contact_id, 
            employee_id = $employee_id, 
            order_date = '$order_date', 
            delivery_date = $delivery_date, 
            actual_delivery_date = $actual_delivery_date, 
            order_status = $order_status, 
            payment_status = $payment_status, 
            currency = '$currency', 
            subtotal = $subtotal, 
            discount_amount = $discount_amount, 
            total_amount = $total_amount, 
            notes = '$notes', 
            internal_notes = '$internal_notes', 
            updated_at = NOW() 
            WHERE id = $id";

    mysqli_query($conn, $sql);

    // 删除旧的订单项
    $sql = "DELETE FROM order_items WHERE order_id = $id";
    mysqli_query($conn, $sql);

    // 添加新的订单项
    foreach ($items as $item) {
        if (empty($item['product_id'])) continue; // 跳过没有选择产品的行

        $product_id = (int)$item['product_id'];
        $quantity = (int)$item['quantity'];
        $unit = mysqli_real_escape_string($conn, htmlspecialchars($item['unit'], ENT_QUOTES, 'UTF-8'));
        $total_price = (float)$item['total_price'];
        // 如果数量大于0,计算单价,否则单价为0
        $unit_price = ($quantity > 0) ? ($total_price / $quantity) : 0;
        $item_notes = mysqli_real_escape_string($conn, htmlspecialchars($item['notes'] ?? '', ENT_QUOTES, 'UTF-8'));

        $sql = "INSERT INTO order_items (
                order_id, product_id, specification_id, quantity, unit, unit_price, 
                total_price, notes, 
                created_at, updated_at
            ) VALUES (
                $id, $product_id, 0, $quantity, '$unit', $unit_price, 
                $total_price, '$item_notes', 
                NOW(), NOW()
            )";

        mysqli_query($conn, $sql);
    }

    $message = "订单更新成功!";
} else {

    // 创建新订单
    $sql = "INSERT INTO orders (
            order_code, customer_id, contact_id, employee_id, 
            order_date, delivery_date, actual_delivery_date, 
            order_status, payment_status, currency, 
            subtotal, discount_amount, total_amount, 
            notes, internal_notes, created_at, updated_at
        ) VALUES (
            '$order_code', $customer_id, $contact_id, $employee_id, 
            '$order_date', $delivery_date, $actual_delivery_date, 
            $order_status, $payment_status, '$currency', 
            $subtotal, $discount_amount, $total_amount, 
            '$notes', '$internal_notes', NOW(), NOW()
        )";

    mysqli_query($conn, $sql);
    $order_id = mysqli_insert_id($conn);

    // 添加订单项
    foreach ($items as $item) {
        if (empty($item['product_id'])) continue; // 跳过没有选择产品的行

        $product_id = (int)$item['product_id'];
        $quantity = (int)$item['quantity'];
        $unit = mysqli_real_escape_string($conn, htmlspecialchars($item['unit'], ENT_QUOTES, 'UTF-8'));
        $total_price = (float)$item['total_price'];
        // 如果数量大于0,计算单价,否则单价为0
        $unit_price = ($quantity > 0) ? ($total_price / $quantity) : 0;
        $item_notes = mysqli_real_escape_string($conn, htmlspecialchars($item['notes'] ?? '', ENT_QUOTES, 'UTF-8'));

        $sql = "INSERT INTO order_items (
                order_id, product_id, specification_id, quantity, unit, unit_price, 
                total_price, notes, 
                created_at, updated_at
            ) VALUES (
                $order_id, $product_id, 0, $quantity, '$unit', $unit_price, 
                $total_price, '$item_notes', 
                NOW(), NOW()
            )";

        mysqli_query($conn, $sql);
    }

    $message = "订单创建成功!";
}

// 重定向回订单列表页面
$page = $_GET['Page'] ?? '';
$keys = urlencode($_GET['Keys'] ?? '');
echo "<script>alert('$message');location.href='order.php?keys=$keys&Page=$page';</script>";
exit;
?>