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

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

// Initialize variables
$product_name = '';
$product_img = '';
$unit = '';
$moq = '';
$category_id = isset($_GET['category_id']) ? intval($_GET['category_id']) : 0;
$note = '';
$tips = '';
$keys = isset($_GET['Keys']) ? urlencode($_GET['Keys']) : '';
$page = isset($_GET['Page']) ? $_GET['Page'] : 1;
$rebate = 0; // 默认不启用返点

// Get the return URL
$href_str = "products.php?keys=" . $keys . "&Page=" . $page;
if ($category_id) {
    $href_str .= "&category_id=" . $category_id;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>添加产品</title>
<link rel="stylesheet" href="css/common.css" type="text/css" />
<script language="javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/js.js"></script>
<script type="text/javascript" src="js/SearchArea.js"></script>
<script type="text/javascript" src="xheditor-1.1.9/xheditor-1.1.9-zh-cn.min.js"></script>
<style>
    /* Styles for specification section */
    .specifications {
        margin-bottom: 10px;
        width: 100%;
    }
    .specitem {
        margin-bottom: 8px;
        padding: 8px 10px;
        /*background-color: #f9f9f9;*/
        border: 1px solid #e0e0e0;
        border-radius: 4px;
        clear: both;
        overflow: hidden;
    }
    .addspecitem, .delspecitem {
        display: inline-block;
        width: 20px;
        height: 20px;
        text-align: center;
        line-height: 18px;
        border-radius: 50%;
        font-weight: bold;
        cursor: pointer;
        margin-left: 10px;
    }
    .addspecitem {
        background-color: #5cb85c;
        color: white;
    }
    .delspecitem {
        background-color: #d9534f;
        color: white;
    }
    .spec-input {
        width: 160px;
        padding: 4px;
        margin-right: 10px;
        border: 1px solid #ccc;
        border-radius: 3px;
    }
    .spec-small-input {
        width: 80px;
        padding: 4px;
        margin-right: 10px;
        border: 1px solid #ccc;
        border-radius: 3px;
    }
    .spec-label {
        display: inline-block;
        margin-right: 5px;
        font-weight: normal;
    }
    .required {
        color: red;
        margin-left: 2px;
    }
</style>
</head>

<body>
<div id="man_zone">
    <form name="form1" method="post" action="save_product.php">
        <table width="100%" border="0" cellpadding="3" cellspacing="1" class="table1">
            <tbody>
                <tr>
                    <th width="8%">产品名称</th>
                    <td><input type="text" id="ProductName" name="ProductName" value="<?php echo $product_name; ?>" class="txt1" />
                    <input type="hidden" name="id" value="" />
                    <input type="hidden" name="keys" value="<?php echo $keys; ?>" />
                    <input type="hidden" name="page" value="<?php echo $page; ?>" />
                    <input type="hidden" name="category_id" value="<?php echo $category_id; ?>" />
                    </td>
                </tr>
                <tr>
                    <th width="8%">产品分类</th>
                    <td>
                        <select name="category_id" id="category_id" class="select1">
                            <option value="0">-- 请选择分类 --</option>
                            <?php
                            // Build category tree
                            $category_data = buildCategoryTree($conn);
                            $cat_tree = $category_data['tree'];
                            
                            // Output options
                            outputCategoryOptions($cat_tree, $category_id);
                            ?>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th width="8%">产品图片</th>
                    <td><input type="text" id="ProductImg" name="ProductImg" placeholder="186x*186px" value="<?php echo $product_img; ?>" class="txt1" style="width:390px;float:left;" />
                    <iframe src="uploadfile.php" frameborder="0" scrolling="no" style="width:400px;height:22px;float:left;margin-left:10px;"></iframe></td>
                </tr>
                <tr>
                    <th width="8%">计价单位</th>
                    <td><input type="text" id="unit" name="unit" value="<?php echo $unit; ?>" class="txt1"/></td>
                </tr>
<!--                <tr>-->
<!--                    <th width="8%">起订数量</th>-->
<!--                    <td><input type="text" id="moq" name="moq" value="--><?php //echo $moq; ?><!--" class="txt1"/></td>-->
<!--                </tr>-->
                <tr>
                    <th width="8%">启用返点</th>
                    <td>
                        <label><input type="radio" name="rebate" value="1" <?php echo $rebate == 1 ? 'checked' : ''; ?> /> 启用</label>
                        <label style="margin-left: 20px;"><input type="radio" name="rebate" value="0" <?php echo $rebate == 0 ? 'checked' : ''; ?> /> 不启用</label>
                    </td>
                </tr>
                <tr id="rebate_settings">
                    <th width="8%">返点设置</th>
                    <td>
                        <div class="specifications">
                            <div class="specitem">
                                <span class="spec-label">最低采购数量<span class="required">*</span>:</span>
                                <input type="number" class="spec-small-input" name="min_quantity[]" value="1" required>
                                
                                <span class="spec-label">单件返点金额<span class="required">*</span>:</span>
                                <input type="text" class="spec-small-input" name="rebate_amount[]" placeholder="返点金额" value="0" required>
                                
                                <span class="addspecitem">+</span>
                                <span class="delspecitem">-</span>
                                
                                <!-- 隐藏字段,仍然提交但不显示 -->
                                <input type="hidden" name="rebate_id[]" value="0">
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th width="8%">不报价地区</th>
                    <td>
                        <ul class="areadd"></ul>
                        <input type="text" id="AreaSearch" class="fastsearch">
                        <div id="arealist" class="productlist"><ul></ul></div>
                    </td>
                </tr>
                <tr>
                    <th width="8%">不报价处理方式</th>
                    <td><input type="text" id="note" name="note" value="<?php echo $note; ?>" class="txt1"/></td>
                </tr>
                <tr>
                    <th width="8%">备注</th>
                    <td><input type="text" id="tips" name="tips" value="<?php echo $tips; ?>" class="txt1"/></td>
                </tr>
                <tr>
                    <th></th>
                    <td colspan="2">
                        <input type="submit" name="save" value="确定" class="btn1" />
                        <input type="reset" name="reset" value="重置" class="btn1" />
                        <input type="button" value="返回" class="btn1" onClick="location.href='<?php echo $href_str; ?>'" />
                    </td>
                </tr>
            </tbody>
        </table>
    </form>
</div>

<script>
    $(document).ready(function(){
        // Add rebate rule item
        $(document).on('click', '.addspecitem', function(){
            var newSpecItem = $(this).closest('.specitem').clone(true);
            newSpecItem.find('input[type="text"], input[type="hidden"]').val(''); // Clear values
            newSpecItem.find('input[name="min_quantity[]"]').val('1'); // Reset min quantity to 1
            newSpecItem.find('input[name="rebate_id[]"]').val('0'); // Set ID to 0 for new rebate rules
            $(this).closest('.specifications').append(newSpecItem);
        });
        
        // Remove rebate rule item
        $(document).on('click', '.delspecitem', function(){
            if($('.specitem').length > 1){
                $(this).closest('.specitem').remove();
            } else {
                alert('至少需要保留一个返点规则');
            }
        });
        
        // Update unit display when unit field changes
        $('#unit').on('change keyup', function(){
            $('.unit').text($(this).val());
        });
        
        // 验证最低采购数量不重复且返点金额符合规则
        $('form[name="form1"]').on('submit', function(e){
            // 检查是否有重复的最低采购数量
            var quantities = [];
            var hasError = false;
            
            // 收集并检查所有数量值
            $('input[name="min_quantity[]"]').each(function(){
                var quantity = parseInt($(this).val());
                if(quantities.includes(quantity)) {
                    alert('错误:存在重复的最低采购数量 ' + quantity + ',请修改!');
                    $(this).focus();
                    hasError = true;
                    return false; // 跳出循环
                }
                quantities.push(quantity);
            });
            
            if(hasError) {
                e.preventDefault();
                return false;
            }
            
            // 按最低采购数量排序规则
            var rules = [];
            $('.specitem').each(function(){
                var quantity = parseInt($(this).find('input[name="min_quantity[]"]').val());
                var amount = parseFloat($(this).find('input[name="rebate_amount[]"]').val());
                rules.push({
                    element: $(this),
                    quantity: quantity,
                    amount: amount
                });
            });
            
            // 按数量从小到大排序
            rules.sort(function(a, b){
                return a.quantity - b.quantity;
            });
            
            // 检查返点金额规则:数量越多,返点金额应大于等于数量小的
            for(var i = 1; i < rules.length; i++) {
                if(rules[i].amount < rules[i-1].amount) {
                    alert('错误:最低采购数量为 ' + rules[i].quantity + ' 的返点金额不能小于最低采购数量为 ' + rules[i-1].quantity + ' 的返点金额!');
                    rules[i].element.find('input[name="rebate_amount[]"]').focus();
                    hasError = true;
                    break;
                }
            }
            
            if(hasError) {
                e.preventDefault();
                return false;
            }
            
            return true;
        });
    });
</script>

</body>
</html>
<?php mysqli_close($conn); ?>