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

// Check login status
checkLogin("信息管理");

// Initialize all variables to avoid undefined warnings
$id = isset($_POST['id']) ? $_POST['id'] : '';
$product_name = isset($_POST['ProductName']) ? htmlspecialcharsFix($_POST['ProductName']) : '';
$product_img = isset($_POST['ProductImg']) ? htmlspecialcharsFix($_POST['ProductImg']) : '';
$unit = isset($_POST['unit']) ? htmlspecialcharsFix($_POST['unit']) : '';
$moq = isset($_POST['moq']) ? htmlspecialcharsFix($_POST['moq']) : '';
$category_id = isset($_POST['category_id']) ? intval($_POST['category_id']) : 0;
$nosale = isset($_POST['nosale']) ? $_POST['nosale'] : array();
$note = isset($_POST['note']) ? htmlspecialcharsFix($_POST['note']) : '';
$tips = isset($_POST['tips']) ? htmlspecialcharsFix($_POST['tips']) : '';
$keys = isset($_POST['keys']) ? $_POST['keys'] : '';
$page = isset($_POST['page']) ? $_POST['page'] : 1;
$rebate = isset($_POST['rebate']) ? intval($_POST['rebate']) : 0; // 获取返点启用状态

// Initialize rebate rule variables
$min_quantity = isset($_POST['min_quantity']) ? $_POST['min_quantity'] : array();
$rebate_amount = isset($_POST['rebate_amount']) ? $_POST['rebate_amount'] : array();
$rebate_id = isset($_POST['rebate_id']) ? $_POST['rebate_id'] : array();

// Redirect URL
$redirect_url = "products.php?Keys=" . $keys . "&Page=" . $page;
if ($category_id) {
    $redirect_url .= "&category_id=" . $category_id;
}

// Determine if this is an edit or a new record
$is_edit = (!empty($id) && is_numeric($id));

// Process nosale array into comma-separated string
$nosale_str = '';
if (is_array($nosale) && !empty($nosale)) {
    $nosale_clean = array_map('intval', $nosale); // Ensure all values are integers
    $nosale_str = implode(',', $nosale_clean);
}

// Validate form data
if (empty($product_name)) {
    // You could add error handling here
    header("Location: " . $redirect_url);
    exit();
}

// Validate rebate rules - at least one rule is required with all fields filled
$has_valid_rebates = false;
if (is_array($min_quantity) && !empty($min_quantity)) {
    foreach ($min_quantity as $key => $quantity) {
        if (!empty($quantity) && isset($rebate_amount[$key]) && $rebate_amount[$key] !== '') {
            $has_valid_rebates = true;
            break;
        }
    }
}

if (!$has_valid_rebates) {
    // Redirect back with error message
    header("Location: " . $redirect_url . "&error=missing_rebates");
    exit();
}

// 验证最低采购数量不重复,且返点金额符合规则
$quantity_values = array();
$rebate_rules = array();

// 收集所有有效的规则
if (is_array($min_quantity) && !empty($min_quantity)) {
    foreach ($min_quantity as $key => $quantity) {
        if (!empty($quantity) && isset($rebate_amount[$key]) && $rebate_amount[$key] !== '') {
            $quantity_value = (int)$quantity;
            $rebate_value = (float)$rebate_amount[$key];
            
            // 检查重复的最低采购数量
            if (in_array($quantity_value, $quantity_values)) {
                // 存在重复数量,返回错误
                header("Location: " . $redirect_url . "&error=duplicate_quantity");
                exit();
            }
            
            $quantity_values[] = $quantity_value;
            $rebate_rules[] = array(
                'quantity' => $quantity_value,
                'amount' => $rebate_value
            );
        }
    }
}

// 按数量从小到大排序规则
usort($rebate_rules, function($a, $b) {
    return $a['quantity'] - $b['quantity'];
});

// 检查返点金额规则:数量越多,返点金额应大于等于数量小的
for ($i = 1; $i < count($rebate_rules); $i++) {
    if ($rebate_rules[$i]['amount'] < $rebate_rules[$i-1]['amount']) {
        // 返点金额不符合规则,返回错误
        header("Location: " . $redirect_url . "&error=invalid_rebate_amount");
        exit();
    }
}

if ($is_edit) {
    // Update existing product
    $sql = "UPDATE products SET 
            ProductName = '" . mysqli_real_escape_string($conn, $product_name) . "',
            ProductImg = '" . mysqli_real_escape_string($conn, $product_img) . "',
            Addtime = NOW(),
            moq = '" . mysqli_real_escape_string($conn, $moq) . "',
            unit = '" . mysqli_real_escape_string($conn, $unit) . "',
            nosale = '" . $nosale_str . "',
            note = '" . mysqli_real_escape_string($conn, $note) . "',
            tips = '" . mysqli_real_escape_string($conn, $tips) . "',
            rebate = " . $rebate . ",
            category_id = " . $category_id . "
            WHERE id = " . (int)$id;
    mysqli_query($conn, $sql);
    
    // 处理返点规则
    // Track which rebate rule IDs we're keeping in this update
    $kept_rebate_ids = array();
    
    // Process rebate rules
    if (is_array($min_quantity) && !empty($min_quantity)) {
        foreach ($min_quantity as $key => $quantity) {
            if (!empty($quantity) && isset($rebate_amount[$key]) && $rebate_amount[$key] !== '') {
                $quantity_value = isset($min_quantity[$key]) && is_numeric($min_quantity[$key]) ? (int)$min_quantity[$key] : 1;
                $rebate_value = isset($rebate_amount[$key]) && is_numeric($rebate_amount[$key]) ? (float)$rebate_amount[$key] : 0;
                $rebate_id_value = isset($rebate_id[$key]) && is_numeric($rebate_id[$key]) ? (int)$rebate_id[$key] : 0;
                
                if ($rebate_id_value > 0) {
                    // Update existing rebate rule
                    $sql = "UPDATE rebate_rules SET 
                            min_quantity = " . $quantity_value . ", 
                            rebate_amount = " . $rebate_value . "
                            WHERE id = " . $rebate_id_value . " AND product_id = " . (int)$id;
                    mysqli_query($conn, $sql);
                    
                    // Add to kept IDs list
                    $kept_rebate_ids[] = $rebate_id_value;
                } else {
                    // Insert new rebate rule
                    $sql = "INSERT INTO rebate_rules 
                            (product_id, min_quantity, rebate_amount, addtime) 
                            VALUES (
                                " . (int)$id . ", 
                                " . $quantity_value . ", 
                                " . $rebate_value . ", 
                                NOW()
                            )";
                    mysqli_query($conn, $sql);
                    
                    // Add newly inserted ID to kept list
                    $kept_rebate_ids[] = mysqli_insert_id($conn);
                }
            }
        }
    }
    
    // Delete rebate rules that were removed in the form
    if (!empty($kept_rebate_ids)) {
        $delete_sql = "DELETE FROM rebate_rules WHERE product_id = " . (int)$id;
        if (count($kept_rebate_ids) > 0) {
            $delete_sql .= " AND id NOT IN (" . implode(',', $kept_rebate_ids) . ")";
        }
        mysqli_query($conn, $delete_sql);
    } else {
        // If no rebate rules are kept, delete all rules for this product
        mysqli_query($conn, "DELETE FROM rebate_rules WHERE product_id = " . (int)$id);
    }
} else {
    // Insert new product
    $sql = "INSERT INTO products (ProductName, ProductImg, Addtime, moq, unit, nosale, note, tips, rebate, category_id) 
            VALUES (
                '" . mysqli_real_escape_string($conn, $product_name) . "',
                '" . mysqli_real_escape_string($conn, $product_img) . "',
                NOW(),
                '" . mysqli_real_escape_string($conn, $moq) . "',
                '" . mysqli_real_escape_string($conn, $unit) . "',
                '" . $nosale_str . "',
                '" . mysqli_real_escape_string($conn, $note) . "',
                '" . mysqli_real_escape_string($conn, $tips) . "',
                " . $rebate . ",
                " . $category_id . "
            )";
    mysqli_query($conn, $sql);
    $id = mysqli_insert_id($conn);
    
    // Add rebate rules for new product
    if (is_array($min_quantity) && !empty($min_quantity)) {
        foreach ($min_quantity as $key => $quantity) {
            if (!empty($quantity) && isset($rebate_amount[$key]) && $rebate_amount[$key] !== '') {
                $quantity_value = isset($min_quantity[$key]) && is_numeric($min_quantity[$key]) ? (int)$min_quantity[$key] : 1;
                $rebate_value = isset($rebate_amount[$key]) && is_numeric($rebate_amount[$key]) ? (float)$rebate_amount[$key] : 0;
                
                $sql = "INSERT INTO rebate_rules 
                        (product_id, min_quantity, rebate_amount, addtime) 
                        VALUES (
                            " . (int)$id . ", 
                            " . $quantity_value . ", 
                            " . $rebate_value . ", 
                            NOW()
                        )";
                mysqli_query($conn, $sql);
            }
        }
    }
}

// Redirect after save
mysqli_close($conn);
header("Location: " . $redirect_url);
exit();