<?php
require_once 'conn.php';
checkLogin();
?>
<!DOCTYPE html>
<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 src="js/jquery-1.7.2.min.js"></script>
    <script src="js/js.js"></script>
    <script src="js/xheditor-1.1.9/xheditor-1.1.9-zh-cn.min.js"></script>
    <script src="js/Hz2Py-szm-min.js"></script>
    <script src="js/ySearchSelect.js"></script>
    <script>
    $(document).ready(function(){
        $('.txt2').xheditor({
            tools:'full',
            hoverExecDelay:-1,
            urlBase:'system',
            upLinkUrl:"upload.php",
            upLinkExt:"zip,rar,txt,pdf",
            upImgUrl:"upload.php",
            upImgExt:"jpg,jpeg,gif,png",
            upFlashUrl:"upload.php",
            upFlashExt:"swf",
            upMediaUrl:"upload.php",
            upMediaExt:"wmv,avi,wma,mp3,mid"
        });
        
        // Add contact form
        $('.add-contact-btn').click(function() {
            var contactsContainer = $('#contacts-container');
            var contactIndex = contactsContainer.children('.contact-form').length;
            var contactForm = `
                <div class="contact-form" id="contact-form-${contactIndex}">
                    <div class="contact-header">
                        <button type="button" class="remove-contact-btn" data-index="${contactIndex}">删除</button>
                        <h3>联系人 #${contactIndex + 1}</h3>
                    </div>
                    <input type="hidden" name="contact[${contactIndex}][id]" value="">
                    <table width="100%" border="0" cellpadding="3" cellspacing="1" class="contact-table">
                        <tr>
                            <th width="8%">联系人</th>
                            <td><input type="text" name="contact[${contactIndex}][contact_name]" class="txt1" placeholder="联系人姓名"/></td>
                        </tr>
                    </table>
                    <div class="contact-methods-container" id="contact-methods-${contactIndex}">
                        <!-- Contact methods will be added here -->
                    </div>
                    <button type="button" class="add-method-btn" data-contact-index="${contactIndex}">添加联系方式</button>
                </div>
            `;
            contactsContainer.append(contactForm);
        });
        
        // Add contact method
        $(document).on('click', '.add-method-btn', function() {
            var contactIndex = $(this).data('contact-index');
            var methodsContainer = $('#contact-methods-' + contactIndex);
            
            // Count existing methods by type
            var methodCounts = {};
            methodsContainer.find('select.method-select').each(function() {
                var type = $(this).val();
                if (type) {
                    methodCounts[type] = (methodCounts[type] || 0) + 1;
                }
            });
            
            var methodRow = `
                <div class="contact-method-row">
                    <select class="method-select" onchange="updateMethodSelectAndPlaceholder(this)">
                        <option value="">请选择联系方式</option>
                        <option value="tel" ${(methodCounts.tel || 0) >= 3 ? 'disabled' : ''}>电话</option>
                        <option value="wechat" ${(methodCounts.wechat || 0) >= 3 ? 'disabled' : ''}>微信</option>
                        <option value="whatsapp" ${(methodCounts.whatsapp || 0) >= 3 ? 'disabled' : ''}>WhatsApp</option>
                        <option value="email" ${(methodCounts.email || 0) >= 3 ? 'disabled' : ''}>邮箱</option>
                        <option value="linkedin" ${(methodCounts.linkedin || 0) >= 3 ? 'disabled' : ''}>领英</option>
                        <option value="facebook" ${(methodCounts.facebook || 0) >= 3 ? 'disabled' : ''}>Facebook</option>
                        <option value="alibaba" ${(methodCounts.alibaba || 0) >= 3 ? 'disabled' : ''}>阿里巴巴</option>
                    </select>
                    <input type="text" class="txt1 method-input" style="width:60%;" placeholder="请选择联系方式类型">
                    <button type="button" class="remove-method-btn">删除</button>
                </div>
            `;
            
            methodsContainer.append(methodRow);
            updateMethodFields(methodsContainer.find('.contact-method-row:last-child'));
        });
        
        // Remove contact method
        $(document).on('click', '.remove-method-btn', function() {
            var methodRow = $(this).closest('.contact-method-row');
            var contactIndex = methodRow.closest('.contact-form').attr('id').split('-')[2];
            var type = methodRow.find('select.method-select').val();
            methodRow.remove();
            
            // Update available options in other selects
            updateAvailableMethodTypes(contactIndex);
        });

        // Remove contact
        $(document).on('click', '.remove-contact-btn', function() {
            var contactForm = $(this).closest('.contact-form');
            contactForm.remove();
            
            // Renumber remaining contacts
            $('#contacts-container .contact-form').each(function(index) {
                $(this).find('h3').text('联系人 #' + (index + 1));
            });
        });

        // Add initial contact form if none exists
        if ($('#contacts-container').children().length === 0) {
            $('.add-contact-btn').click();
        }
    });

    // Update method fields based on selection
    function updateMethodFields(methodRow) {
        var select = methodRow.find('select.method-select');
        var input = methodRow.find('input.method-input');
        var contactForm = methodRow.closest('.contact-form');
        var contactIndex = contactForm.attr('id').split('-')[2];
        var type = select.val();
        
        if (!type) return;
        
        // Count existing methods of this type
        var count = 1;
        contactForm.find('select.method-select').each(function() {
            if ($(this).val() === type && $(this)[0] !== select[0]) {
                count++;
            }
        });
        
        // Update field names
        select.attr('name', `contact[${contactIndex}][${type}_${count}]`);
        input.attr('name', `contact[${contactIndex}][${type}_${count}]`);
        
        // Add format field for tel and whatsapp
        if (type === 'tel' || type === 'whatsapp') {
            if (!methodRow.find('.format-input').length) {
                input.after(`<input type="hidden" class="format-input" name="contact[${contactIndex}][${type}_${count}_format]">`);
            }
        }
        
        // Add backup field
        if (!methodRow.find('.backup-input').length) {
            methodRow.append(`<input type="hidden" class="backup-input" name="contact[${contactIndex}][${type}_${count}_bu]">`);
        }
    }

    // Update available method types for a contact
    function updateAvailableMethodTypes(contactIndex) {
        var methodsContainer = $('#contact-methods-' + contactIndex);
        
        // Count methods by type
        var methodCounts = {};
        methodsContainer.find('select.method-select').each(function() {
            var type = $(this).val();
            if (type) {
                methodCounts[type] = (methodCounts[type] || 0) + 1;
            }
        });
        
        // Update all selects in this contact
        methodsContainer.find('select.method-select').each(function() {
            var currentValue = $(this).val();
            
            $(this).find('option').each(function() {
                var optionValue = $(this).val();
                if (optionValue && optionValue !== currentValue) {
                    $(this).prop('disabled', (methodCounts[optionValue] || 0) >= 3);
                }
            });
        });
    }

    // Update placeholder and handle method fields
    function updateMethodSelectAndPlaceholder(selectElement) {
        var methodRow = $(selectElement).closest('.contact-method-row');
        updateMethodPlaceholder(selectElement);
        updateMethodFields(methodRow);
        
        var contactIndex = methodRow.closest('.contact-form').attr('id').split('-')[2];
        updateAvailableMethodTypes(contactIndex);
    }

    // Update method placeholder based on selected type
    function updateMethodPlaceholder(selectElement) {
        var placeholder = "";
        var value = $(selectElement).val();
        
        switch(value) {
            case "tel":
                placeholder = "电话格式:区号+号码 如:+86 15012345678";
                break;
            case "wechat":
                placeholder = "微信";
                break;
            case "whatsapp":
                placeholder = "Whatsapp 格式:区号+号码 如:+86 15012345678";
                break;
            case "email":
                placeholder = "邮件";
                break;
            case "linkedin":
                placeholder = "领英链接";
                break;
            case "facebook":
                placeholder = "Facebook";
                break;
            case "alibaba":
                placeholder = "阿里巴巴";
                break;
            default:
                placeholder = "请选择联系方式类型";
        }
        
        $(selectElement).next('.method-input').attr('placeholder', placeholder);
    }

    // Custom validation function for multiple contacts form with contact methods
    function validateMultipleContactsForm() {
        var clientCode = $("#cs_code").val();
        var clientCompany = $("#cs_company").val();
        var clientFrom = $("#cs_from").val();
        var clientCountry = $("#cs_country").val();
        
        // Validate basic customer info
        if (clientCode == "" || clientCode == null) {
            alert("客户代码不能为空!");
            $("#cs_code").focus();
            return false;
        }
        
        if (clientCountry == 0 || !clientCountry) {
            alert("这是哪个国家的客户?");
            return false;
        }
        
        if (clientFrom == "0") {
            alert("请填写客户来源!");
            return false;
        }
        
        // Validate that at least one contact has at least one contact method
        var hasContactMethod = false;
        var allContactsValid = true;
        
        $('.contact-form').each(function(contactIndex) {
            var $form = $(this);
            var contactName = $form.find('input[name*="[contact_name]"]').val();
            var hasMethodInThisContact = false;
            
            // Check if this contact has methods
            $form.find('.contact-method-row').each(function() {
                var methodType = $(this).find('select.method-select').val();
                var methodValue = $(this).find('input.method-input').val();
                
                if (methodValue) {
                    hasMethodInThisContact = true;
                    hasContactMethod = true;
                }
                
                // Check if method type is selected but value is empty
                if (methodType && !methodValue) {
                    alert("联系方式类型已选择但值为空");
                    allContactsValid = false;
                    return false;
                }
            });
            
            // If contact has a name but no methods, or has methods but no name
            if ((contactName && !hasMethodInThisContact) || (!contactName && hasMethodInThisContact)) {
                alert("联系人 #" + (contactIndex + 1) + " 缺少联系人姓名或联系方式");
                allContactsValid = false;
                return false;
            }
            
            // If contact has neither name nor methods, it's an empty contact
            if (!contactName && !hasMethodInThisContact) {
                alert("联系人 #" + (contactIndex + 1) + " 是空的,请填写信息或删除此联系人");
                allContactsValid = false;
                return false;
            }
        });
        
        if (!allContactsValid) {
            return false;
        }
        
        if (!hasContactMethod) {
            alert("至少需要添加一个联系人,且联系人至少需要一种联系方式!");
            return false;
        }
        
        // Set tag values
        $("input#mytag").val($(".taglist").html());
        
        return true;
    }

    // Modified submission function
    function subform() {
        if (validateMultipleContactsForm()) {
            $("#form1").submit();
        }
    }
    </script>
    <style>
        body {
            margin: 0;
            padding: 20px;
            background: #fff;
        }
        #man_zone {
            margin-left: 0;
        }
        .contact-form {
            margin-bottom: 10px;
            /*border: 1px solid #ddd;*/
            padding: 8px;
            background-color: #FFFFFF;
        }
        .contact-header {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            gap: 10px;
        }
        .contact-header h3 {
            margin: 0;
            order: 2;
            flex-grow: 1;
        }
        .remove-contact-btn {
            background-color: #f44336;
            color: white;
            border: none;
            padding: 4px 8px;
            cursor: pointer;
            order: 1;
        }
        .add-contact-btn {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 6px 12px;
            margin-bottom: 10px;
            cursor: pointer;
        }
        .contact-methods-container {
            margin-top: 8px;
        }
        .contact-method-row {
            margin-bottom: 6px;
            padding: 6px;
            border: 1px solid #eee;
           /*background-color: #f5f5f5;*/
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .add-method-btn {
            background-color: #2196F3;
            color: white;
            border: none;
            padding: 4px 8px;
            margin-top: 4px;
            cursor: pointer;
        }
        .remove-method-btn {
            background-color: #f44336;
            color: white;
            border: none;
            padding: 2px 4px;
            cursor: pointer;
        }
        .method-select {
            margin-right: 8px;
            padding: 3px;
        }
        .contact-table {
            margin-bottom: 6px;
        }
        .contact-table td, .contact-table th {
            padding: 4px 6px;
        }
    </style>
</head>
<body class="clear">
<?php // require_once 'panel.php'; ?>
<div id="man_zone">
    <form name="form1" id="form1" method="post" action="customerSave.php<?= $hrefstr ?? '' ?>">
        <table width="100%" border="0" cellpadding="3" cellspacing="1" class="table1">
            <tbody>
                <tr>
                    <th width="8%">客户编号</th>
                    <td>
                        <input type="text" id="cs_code" name="cs_code" value="" class="txt1" />
                        <input type="hidden" name="cs_addtime" value="<?= date('Y-m-d H:i:s') ?>" />
                    </td>
                </tr>
                <tr>
                    <th width="8%">公司名称</th>
                    <td><input type="text" id="cs_company" name="cs_company" value="" class="txt1" /></td>
                </tr>
                <tr>
                    <th width="8%">地区</th>
                    <td>
                        <div class="layui-input-inline">
                            <div class="layui-form-select ySearchSelect y1">
                                <div class="layui-input">请选择客户区域</div>
                                <input name="cs_country" id="cs_country" type="hidden">
                                <i class="layui-edge"></i>
                                <ul>
                                    <?php
                                    $result = $conn->query("SELECT id, countryCode, countryName FROM country");
                                    while ($row = $result->fetch_assoc()) {
                                        echo "<li class=\"on\" data-c=\"{$row['id']}\">(+{$row['countryCode']}){$row['countryName']}</li>";
                                    }
                                    ?>
                                    <p>无匹配项</p>
                                </ul>
                            </div>
                        </div>
                        <script>
                            $(function () {
                                $(".y1").ySearchSelect();  
                            })
                        </script>
                    </td>
                </tr>
                <tr>
                    <th width="8%">来源</th>
                    <td>
                        <select id="cs_from" name="cs_from">
                            <option value="0">请选择来源</option>
                            <?php
                            $result = $conn->query("SELECT id, ch_name FROM qudao");
                            while ($row = $result->fetch_assoc()) {
                                echo "<option value=\"{$row['id']}\">{$row['ch_name']}</option>";
                            }
                            ?>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th width="8%" valign="top">联系人信息</th>
                    <td>
                        <button type="button" class="add-contact-btn">添加联系人</button>
                        
                        <div id="contacts-container">
                            <!-- Contact forms will be added here -->
                        </div>
                    </td>
                </tr>
                <tr>
                    <th>地址</th>
                    <td><input type="text" id="cs_address" name="cs_address" value="" class="txt1" /></td>
                </tr>
                <tr>
                    <th>业务类型</th>
                    <td>
                        <?php
                        $result = $conn->query("SELECT id, businessType FROM clienttype");
                        while ($row = $result->fetch_assoc()) {
                            echo "<input type=\"radio\" name=\"cs_type\" value=\"{$row['id']}\" id=\"fortype{$row['id']}\">
                                  <label for=\"fortype{$row['id']}\">{$row['businessType']}</label>";
                        }
                        ?>
                    </td>
                </tr>
                <tr>
                    <th>跟进阶段</th>
                    <td>
                        <input type="radio" id="fordeal1" class="cs_deal" name="cs_deal" value="0"><label for="fordeal1">无响应</label>
                        <input type="radio" id="fordeal2" class="cs_deal" name="cs_deal" value="1" checked="checked"><label for="fordeal2">背景调查</label>
                        <input type="radio" id="fordeal3" class="cs_deal" name="cs_deal" value="2"><label for="fordeal3">明确需求</label>
                        <input type="radio" id="fordeal4" class="cs_deal" name="cs_deal" value="3"><label for="fordeal4">已成交</label>
                    </td>
                </tr>
                <tr>
                    <th>其他</th>
                    <td>
                        <input type="checkbox" id="belongClient" class="cs_belongClient" name="cs_belongClient" value="1">
                        <label for="belongClient">客户的客户</label>
                    </td>
                </tr>
                <tr>
                    <th>自定义标签</th>
                    <td>
                        <div class="taglist"></div>
                        <input type="hidden" id="mytag" name="mytag" value="">
                        <div class="commontag clear">
                            <i class="tag">美特柏品牌客户</i>,
                            <i class="tag">OEM定制客户</i>,
                            <i class="tag">小型B端客户</i>,
                            <i class="tag">C端客户</i>,
                            <i class="tag">贸易公司</i>,
                            <i class="tag">档口客户</i>
                            <?php
                            // 将bind_param改为SQL拼接
                            $employee_id = intval($_SESSION['employee_id']);
                            $sql = "SELECT DISTINCT tagName FROM tagtable WHERE employeeId = ".$employee_id;
                            $result = $conn->query($sql);
                            
                            while ($row = $result->fetch_assoc()) {
                                echo "<i class=\"tag\">" . htmlspecialcharsFix(textUncode($row['tagName'])) . "</i>,";
                            }
                            ?>
                        </div>
                        <input type="text" id="tapinput" class="txt-short" placeholder="添加新标签,按Enter添加">
                    </td>
                </tr>
                <tr>
                    <th width="8%">备注</th>
                    <td><textarea name="cs_note" class="txt2" placeholder=""></textarea></td>
                </tr>
                <tr>
                    <th></th>
                    <td>
                        <input type="button" name="save" id="save" value="确定" class="btn1" onclick="subform();" />
                        <input type="button" value="返回" class="btn1" onClick="location.href='customers.php'" />
                    </td>
                </tr>
            </tbody>
        </table>
    </form>
</div>
</body>
</html>