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

$id = $_GET['id'] ?? '';
$page = $_GET['Page'] ?? '';
$keys = urlencode($_GET['Keys'] ?? '');

$hrefstr = "?keys=$keys&Page=$page";

// Validate and fetch customer data
if (!empty($id) && is_numeric($id)) {
    // Fetch customer basic information
    $sql = "SELECT c.* FROM customer c WHERE c.cs_belong = ? AND c.id = ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ii", $_SESSION['employee_id'], $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        $customer = [
            'cs_company' => textUncode($row['cs_company']),
            'cs_address' => textUncode($row['cs_address']),
            'cs_code' => textUncode($row['cs_code']),
            'cs_deal' => textUncode($row['cs_deal']),
            'cs_addtime' => $row['cs_addtime'],
            'cs_belongclient' => $row['cs_belongclient'],
            'cs_updatetime' => $row['cs_updatetime'],
            'cs_from' => $row['cs_from'],
            'cs_country' => $row['cs_country'],
            'cs_type' => $row['cs_type'],
            'cs_note' => htmlUnCode($row['cs_note']),
            'cs_claimFrom' => $row['cs_claimFrom'],
            'allowedit' => $row['allowedit']
        ];
        
        // Fetch all contact records for this customer
        $contactSql = "SELECT cc.* FROM customer_contact cc WHERE cc.customer_id = ?";
        $contactStmt = $conn->prepare($contactSql);
        $contactStmt->bind_param("i", $id);
        $contactStmt->execute();
        $contactResult = $contactStmt->get_result();
        
        $contacts = [];
        while ($contactRow = $contactResult->fetch_assoc()) {
            $contact = [
                'id' => $contactRow['id'],
                'contact_name' => textUncode($contactRow['contact_name']),
                'created_at' => $contactRow['created_at'],
                'updated_at' => $contactRow['updated_at']
            ];
            
            // Process each contact method type (up to 3 entries each)
            $methodTypes = ['tel', 'email', 'whatsapp', 'wechat', 'linkedin', 'facebook', 'alibaba'];
            foreach ($methodTypes as $type) {
                for ($i = 1; $i <= 3; $i++) {
                    $fieldBase = $type . '_' . $i;
                    $contact[$fieldBase] = textUncode($contactRow[$fieldBase]);
                    if ($type == 'tel' || $type == 'whatsapp') {
                        $contact[$fieldBase . '_format'] = textUncode($contactRow[$fieldBase . '_format']);
                    }
                    $contact[$fieldBase . '_bu'] = textUncode($contactRow[$fieldBase . '_bu']);
                }
            }
            
            $contacts[] = $contact;
        }
    } else {
        echo "<script>alert('客户不存在或你没权限查看!');history.back();</script>";
        exit;
    }
} else {
    echo "<script>alert('客户不存在!');history.back();</script>";
    header("Location: $hrefstr");
    exit;
}
?>
<!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="system/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:'simple',
            hoverExecDelay:-1
        });
        
        // 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 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="">
                    <div class="contact-method-row">
                        <span style="width:80px;display:inline-block;font-weight:bold;" class="method-select">联系人姓名</span>
                        <input type="text" name="contact[${contactIndex}][contact_name]" class="txt1 method-input" style="width:60%;" placeholder="联系人姓名"/>
                    </div>
                    <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);
        });
        
        // 客户关系相关JS代码
        // 显示添加关系弹窗
        $('#add-relationship-btn').click(function() {
            $('#relationship-modal-title').text('添加客户关系');
            $('#relationship_id').val('');
            $('#related_customer_id').val('');
            $('#related_customer_search').val('').show();
            $('#related_customer_selected').hide();
            $('#relationship_type').val('');
            $('input[name="relationship_status"][value="1"]').prop('checked', true);
            $('#relationship_description').val('');
            
            $('<div class="modal-backdrop"></div>').appendTo('body');
            $('#relationship-modal').show();
        });
        
        // 关闭弹窗
        $('#cancel-relationship-btn').click(function() {
            $('#relationship-modal').hide();
            $('.modal-backdrop').remove();
        });
        
        // 编辑关系
        $(document).on('click', '.edit-relationship-btn', function() {
            var relationshipId = $(this).data('id');
            
            // AJAX获取关系详情
            $.ajax({
                url: 'get_relationship.php',
                type: 'GET',
                data: {id: relationshipId},
                dataType: 'json',
                success: function(data) {
                    if (data && data.success) {
                        var relationship = data.relationship;
                        $('#relationship_id').val(relationship.id);
                        
                        // 确定关联的客户(不是当前客户的那一方)
                        var currentCustomerId = $('#current_customer_id').val();
                        var relatedCustomerId = relationship.source_customer_id == currentCustomerId 
                                            ? relationship.target_customer_id 
                                            : relationship.source_customer_id;
                        var relatedCustomerName = relationship.source_customer_id == currentCustomerId 
                                            ? relationship.target_company 
                                            : relationship.source_company;
                        var relatedCustomerCode = relationship.source_customer_id == currentCustomerId 
                                            ? relationship.target_code 
                                            : relationship.source_code;
                        
                        var displayText = relatedCustomerName;
                        if (relatedCustomerCode) {
                            displayText = relatedCustomerCode + ' - ' + relatedCustomerName;
                        }
                        
                        $('#related_customer_id').val(relatedCustomerId);
                        $('#related_customer_search').hide();
                        $('#related_customer_selected')
                            .text(displayText)
                            .append('<span class="customer-clear-btn" title="清除选择">X</span>')
                            .show()
                            .attr('title', displayText);
                        
                        $('#relationship_type').val(relationship.relationship_type);
                        $('input[name="relationship_status"][value="' + relationship.relationship_status + '"]').prop('checked', true);
                        $('#relationship_description').val(relationship.description);
                        
                        $('#relationship-modal-title').text('编辑客户关系');
                        $('<div class="modal-backdrop"></div>').appendTo('body');
                        $('#relationship-modal').show();
                    } else {
                        alert('获取关系信息失败');
                    }
                },
                error: function() {
                    alert('获取关系信息失败,请稍后重试');
                }
            });
        });
        
        // 删除关系
        $(document).on('click', '.delete-relationship-btn', function() {
            if (confirm('确定要删除此客户关系吗?')) {
                var relationshipId = $(this).data('id');
                
                $.ajax({
                    url: 'delete_relationship.php',
                    type: 'POST',
                    data: {id: relationshipId},
                    dataType: 'json',
                    success: function(data) {
                        if (data && data.success) {
                            alert('删除成功');
                            location.reload();
                        } else {
                            alert(data.message || '删除失败');
                        }
                    },
                    error: function() {
                        alert('操作失败,请稍后重试');
                    }
                });
            }
        });
        
        // 保存关系
        $('#save-relationship-btn').click(function() {
            var relationshipId = $('#relationship_id').val();
            var currentCustomerId = $('#current_customer_id').val();
            var relatedCustomerId = $('#related_customer_id').val();
            var relationshipType = $('#relationship_type').val();
            var relationshipStatus = $('input[name="relationship_status"]:checked').val();
            var description = $('#relationship_description').val();
            
            // 验证
            if (!relatedCustomerId) {
                alert('请选择关联客户');
                return;
            }
            
            if (!relationshipType) {
                alert('请选择关系类型');
                return;
            }
            
            var data = {
                id: relationshipId,
                source_customer_id: currentCustomerId,
                target_customer_id: relatedCustomerId,
                relationship_type: relationshipType,
                relationship_status: relationshipStatus,
                description: description
            };
            
            $.ajax({
                url: 'save_relationship.php',
                type: 'POST',
                data: data,
                dataType: 'json',
                success: function(response) {
                    if (response && response.success) {
                        alert('保存成功');
                        $('#relationship-modal').hide();
                        $('.modal-backdrop').remove();
                        location.reload();
                    } else {
                        alert(response.message || '保存失败');
                    }
                },
                error: function() {
                    alert('操作失败,请稍后重试');
                }
            });
        });
        
        // 客户搜索功能
        var customerSearchTimeout = null;
        var customerIsComposing = false;
        
        // 监听输入法组合事件
        $(document).on('compositionstart', '#related_customer_search', function() {
            customerIsComposing = true;
        });

        $(document).on('compositionend', '#related_customer_search', function() {
            customerIsComposing = false;
            $(this).trigger('input'); // 手动触发一次input事件
        });
        
        // 客户搜索输入
        $(document).on('input', '#related_customer_search', function() {
            // 如果是输入法正在组合中文,不处理
            if (customerIsComposing) return;
            
            var searchTerm = $(this).val().trim();
            var customerDropdown = $('#related_customer_dropdown');
            var currentCustomerId = $('#current_customer_id').val();
            
            // 清除之前的超时
            clearTimeout(customerSearchTimeout);
            
            // 隐藏之前的结果
            customerDropdown.hide();
            
            // 清除之前的选择
            $('#related_customer_id').val('');
            $('#related_customer_selected').hide();
            
            // 如果搜索词少于1个字符,不执行搜索
            if (searchTerm.length < 1) {
                return;
            }
            
            // 设置一个300毫秒的超时,以减少请求数量
            customerSearchTimeout = setTimeout(function() {
                $.ajax({
                    url: 'get_customer_search.php',
                    type: 'GET',
                    data: {
                        search: searchTerm,
                        exclude_id: currentCustomerId // 排除当前客户
                    },
                    dataType: 'json',
                    success: function(data) {
                        customerDropdown.empty();
                        
                        if (data && data.customers && data.customers.length > 0) {
                            $.each(data.customers, function(i, customer) {
                                var displayText = customer.cs_company;
                                if (customer.cs_code) {
                                    displayText = customer.cs_code + ' - ' + displayText;
                                }
                                
                                var item = $('<div class="customer-item"></div>')
                                    .attr('data-id', customer.id)
                                    .attr('data-display', displayText)
                                    .text(displayText);
                                
                                customerDropdown.append(item);
                            });
                            customerDropdown.show();
                        }
                    },
                    error: function() {
                        console.log('搜索客户失败,请重试');
                    }
                });
            }, 300);
        });
        
        // 点击选择客户
        $(document).on('click', '.customer-item', function() {
            var customerId = $(this).data('id');
            var displayText = $(this).data('display');
            
            // 设置选中的客户ID和显示
            $('#related_customer_id').val(customerId);
            $('#related_customer_search').hide();
            $('#related_customer_selected')
                .text(displayText)
                .append('<span class="customer-clear-btn" title="清除选择">X</span>')
                .show()
                .attr('title', displayText);
            
            // 隐藏下拉菜单
            $('#related_customer_dropdown').hide();
        });
        
        // 点击X按钮清除选择的客户
        $(document).on('click', '.customer-clear-btn', function(e) {
            e.stopPropagation();
            
            // 显示搜索框,隐藏已选信息
            $('#related_customer_search').val('').show();
            $('#related_customer_selected').hide();
            
            // 清空客户ID
            $('#related_customer_id').val('');
        });
        
        // 点击其他地方隐藏下拉列表
        $(document).on('click', function(e) {
            if (!$(e.target).closest('.customer-search-container').length) {
                $('.customer-dropdown').hide();
            }
        });
    });

    // 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);
    }

    // Look for the updateMethodPlaceholder function and replace it with this modified version
    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 = "邮箱格式必须正确,如: example@domain.com";
                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("这是哪个国家的客户?");
            $("#cs_country").focus();
            return false;
        }
        
        if (clientFrom == "0") {
            alert("请填写客户来源!");
            $("#cs_from").focus();
            return false;
        }
        
        // Validate that at least one business type is selected
        if (!$('input[name="cs_type[]"]:checked').length) {
            alert("请至少选择一种业务类型!");
            return false;
        }
        
        // Get source text to check if it's from Alibaba platforms
        var clientFromText = $("#cs_from option:selected").text();
        var isAlibabaSource = clientFromText.indexOf("1688") >= 0 || 
                             clientFromText.indexOf("阿里") >= 0 || 
                             clientFromText.indexOf("alibaba") >= 0;

        
        // Validate that at least one contact has at least one contact method
        var hasContactMethod = false;
        var hasAlibabaContact = false;
        var allContactsValid = true;
        var phoneRegex = /^\+\d{1,4}\s\d{5,}$/; // Regex to validate phone format: +[country code] [number]
        var emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; // Regex to validate email format
        
        $('.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 there's an Alibaba contact method
                    if (methodType === 'alibaba') {
                        hasAlibabaContact = true;
                    }
                }
                
                // Check if method type is selected but value is empty
                if (methodType && !methodValue) {
                    alert("联系方式类型已选择但值为空");
                    allContactsValid = false;
                    return false;
                }
                
                // Validate phone number format for tel and whatsapp
                if ((methodType === 'tel' || methodType === 'whatsapp') && methodValue) {
                    if (!phoneRegex.test(methodValue)) {
                        alert("电话格式不正确,请使用以下格式:区号+号码,如 +86 15012345678");
                        $(this).find('input.method-input').focus();
                        allContactsValid = false;
                        return false;
                    }
                }
                
                // Validate email format
                if (methodType === 'email' && methodValue) {
                    if (!emailRegex.test(methodValue)) {
                        alert("邮箱格式不正确,请输入有效的邮箱地址");
                        $(this).find('input.method-input').focus();
                        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;
        }
        
        // If source is from Alibaba platforms, must have Alibaba contact method
        if (isAlibabaSource && !hasAlibabaContact) {
            alert("客户来源为1688或阿里国际站时,必须添加至少一个阿里巴巴联系方式!");
            return false;
        }
        
        // Set tag values
        $("input#mytag").val($(".taglist").html());
        
        // Convert the dynamic contact methods to the standard format expected by the server
        $('.contact-form').each(function(contactIndex) {
            var methodsData = {};
            
            $(this).find('.contact-method-row').each(function() {
                var type = $(this).find('select.method-select').val();
                var value = $(this).find('input.method-input').val();
                
                if (type && value) {
                    methodsData[type] = value;
                }
            });
            
            // Create hidden inputs for each method
            for (var type in methodsData) {
                $('<input>').attr({
                    type: 'hidden',
                    name: 'contact[' + contactIndex + '][' + type + ']',
                    value: methodsData[type]
                }).appendTo(this);
            }
        });
        
        return true;
    }

    // Modified submission function
    function submitCustomerForm() {
        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: 0px 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;
        }
        
        /* 客户关系样式 */
        .relationships-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 10px;
        }
        .relationships-table th, .relationships-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        .relationships-table th {
            background-color: #f2f2f2;
        }
        .btn-add-relationship {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 6px 12px;
            margin-bottom: 10px;
            cursor: pointer;
        }
        .edit-relationship-btn, .delete-relationship-btn {
            margin-right: 5px;
            cursor: pointer;
            padding: 3px 8px;
            border: none;
        }
        .edit-relationship-btn {
            background-color: #2196F3;
            color: white;
        }
        .delete-relationship-btn {
            background-color: #f44336;
            color: white;
        }
        #relationship-modal {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: white;
            padding: 20px;
            border: 1px solid #ddd;
            box-shadow: 0 0 10px rgba(0,0,0,0.3);
            z-index: 1000;
            width: 600px;
            max-width: 90%;
        }
        /* 弹窗内表格样式修复 */
        #relationship-modal table.table1 {
            width: 100%;
            border-collapse: collapse;
            table-layout: fixed;
        }
        #relationship-modal table.table1 th {
            width: 120px;
            text-align: right;
            padding-right: 10px;
            vertical-align: middle;
            white-space: nowrap;
        }
        #relationship-modal table.table1 td {
            padding: 6px 8px;
        }
        #relationship-modal .txt1 {
            width: 90%;
        }
        #relationship-modal select.txt1 {
            max-width: 300px;
        }
        .modal-backdrop {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            z-index: 999;
        }
        .modal-actions {
            text-align: right;
            margin-top: 15px;
        }
        .modal-actions button {
            padding: 5px 15px;
            margin-left: 10px;
            cursor: pointer;
        }
        /* 弹窗按钮样式 */
        .modal-actions .btn1 {
            border: 1px solid #ccc;
            background: #f5f5f5;
            border-radius: 3px;
            color: #333;
            font-size: 12px;
            height: 26px;
            padding: 0 15px;
            transition: all 0.3s;
        }
        .modal-actions .btn1:hover {
            background: #e6e6e6;
            border-color: #adadad;
        }
        #save-relationship-btn {
            background-color: #428bca;
            color: white;
            border-color: #357ebd;
        }
        #save-relationship-btn:hover {
            background-color: #3071a9;
            border-color: #285e8e;
        }
        .customer-search-container {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
            position: relative;
            width: 80%;
        }
        .customer-dropdown {
            display: none;
            position: absolute;
            background: white;
            border: 1px solid #ccc;
            max-height: 200px;
            overflow-y: auto;
            width: 100%;
            z-index: 1000;
            box-shadow: 0 3px 8px rgba(0,0,0,0.25);
            border-radius: 0 0 4px 4px;
            top: 100%;
            left: 0;
        }
        .customer-item {
            padding: 10px 12px;
            cursor: pointer;
            border-bottom: 1px solid #eee;
            transition: background-color 0.2s;
        }
        .customer-item:hover {
            background-color: #f0f0f0;
        }
        .selected-customer-info {
            font-weight: bold;
            padding: 8px 10px;
            border: 1px solid #ddd;
            background-color: #f9f9f9;
            display: none;
            width: 100%;
            box-sizing: border-box;
            word-break: break-all;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: normal;
            min-height: 38px;
            position: relative;
            padding-right: 25px;
        }
        .customer-clear-btn {
            position: absolute;
            right: 5px;
            top: 50%;
            transform: translateY(-50%);
            color: #e74c3c;
            font-weight: bold;
            cursor: pointer;
            width: 16px;
            height: 16px;
            text-align: center;
            line-height: 16px;
            background: #f5f5f5;
            border-radius: 50%;
        }
        .customer-clear-btn:hover {
            background: #e74c3c;
            color: white;
        }
    </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="<?= htmlspecialcharsFix($customer['cs_code']) ?>" 
                            <?= !empty($customer['cs_claimFrom']) ? 'readonly' : '' ?> class="txt1" />
                        <input type="hidden" name="id" value="<?= $id ?>" />
                        <input type="hidden" name="cs_addtime" value="<?= $customer['cs_addtime'] ?>" />
                        <input type="hidden" name="Permissions" value="<?= $customer['allowedit'] ?>" />
                    </td>
                </tr>
                <tr>
                    <th width="8%">公司名称</th>
                    <td><input type="text" id="cs_company" name="cs_company" value="<?= htmlspecialcharsFix($customer['cs_company']) ?>" class="txt1" /></td>
                </tr>
                <!-- 客户关系管理部分 -->
                <tr>
                    <th width="8%" valign="top">客户关系</th>
                    <td>
                        <div id="relationships-container">
                            <?php
                            // 获取当前客户的所有关系
                            $relationshipSql = "SELECT cr.*, 
                                                c1.cs_company as source_company, c1.cs_code as source_code,
                                                c2.cs_company as target_company, c2.cs_code as target_code
                                                FROM customer_relationship cr
                                                LEFT JOIN customer c1 ON cr.source_customer_id = c1.id
                                                LEFT JOIN customer c2 ON cr.target_customer_id = c2.id
                                                WHERE cr.source_customer_id = ? OR cr.target_customer_id = ?";
                            $relationshipStmt = $conn->prepare($relationshipSql);
                            $relationshipStmt->bind_param("ii", $id, $id);
                            $relationshipStmt->execute();
                            $relationshipResult = $relationshipStmt->get_result();
                            
                            $hasRelationships = false;
                            if ($relationshipResult->num_rows > 0) {
                                $hasRelationships = true;
                                echo '<table width="100%" border="0" cellpadding="3" cellspacing="1" class="relationships-table">';
                                echo '<tr><th>关系类型</th><th>相关客户</th><th>关系状态</th><th>关系描述</th><th>操作</th></tr>';
                                
                                while ($relationship = $relationshipResult->fetch_assoc()) {
                                    $relationType = '';
                                    switch ($relationship['relationship_type']) {
                                        case 1: $relationType = '母公司-子公司'; break;
                                        case 2: $relationType = '供应商-客户'; break;
                                        case 3: $relationType = '合作伙伴'; break;
                                        case 4: $relationType = '竞争对手'; break;
                                        case 5: $relationType = '推荐人'; break;
                                        case 6: $relationType = '其他'; break;
                                    }
                                    
                                    $relationStatus = $relationship['relationship_status'] == 1 ? '启用' : '停用';
                                    
                                    // 确定关联的客户(不是当前客户的那一方)
                                    $relatedCustomerId = $relationship['source_customer_id'] == $id 
                                                        ? $relationship['target_customer_id'] 
                                                        : $relationship['source_customer_id'];
                                    $relatedCustomerName = $relationship['source_customer_id'] == $id 
                                                        ? textUncode($relationship['target_company']) 
                                                        : textUncode($relationship['source_company']);
                                    $relatedCustomerCode = $relationship['source_customer_id'] == $id 
                                                        ? textUncode($relationship['target_code']) 
                                                        : textUncode($relationship['source_code']);
                                    
                                    $displayText = $relatedCustomerName;
                                    if ($relatedCustomerCode) {
                                        $displayText = $relatedCustomerCode . ' - ' . $relatedCustomerName;
                                    }
                                    
                                    echo '<tr>';
                                    echo '<td>' . $relationType . '</td>';
                                    echo '<td>' . htmlspecialchars($displayText) . '</td>';
                                    echo '<td>' . $relationStatus . '</td>';
                                    echo '<td>' . htmlspecialchars(textUncode($relationship['description'])) . '</td>';
                                    echo '<td>';
                                    echo '<button type="button" class="edit-relationship-btn" data-id="' . $relationship['id'] . '">编辑</button>';
                                    echo '<button type="button" class="delete-relationship-btn" data-id="' . $relationship['id'] . '">删除</button>';
                                    echo '</td>';
                                    echo '</tr>';
                                }
                                
                                echo '</table>';
                            } else {
                                echo '<p>暂无关联客户关系。</p>';
                            }
                            ?>
                            <button type="button" id="add-relationship-btn" class="btn-add-relationship">添加客户关系</button>
                        </div>
                        
                        <!-- 添加/编辑关系的弹出框 -->
                        <div id="relationship-modal" style="display: none;">
                            <h3 id="relationship-modal-title" style="margin-top: 0; margin-bottom: 15px;">添加客户关系</h3>
                            <input type="hidden" id="relationship_id" value="">
                            <input type="hidden" id="current_customer_id" value="<?= $id ?>">
                            
                            <table width="100%" border="0" cellpadding="3" cellspacing="1" class="table1 relationship-modal-table">
                                <tr>
                                    <th width="120">关联客户</th>
                                    <td>
                                        <div class="customer-search-container" style="width: 90%; position: relative;">
                                            <input type="text" id="related_customer_search" class="customer-search txt1" placeholder="输入客户编码或名称搜索..." value="" style="width: 100%; box-sizing: border-box;" />
                                            <div id="related_customer_selected" class="selected-customer-info"></div>
                                            <div id="related_customer_dropdown" class="customer-dropdown"></div>
                                        </div>
                                        <input type="hidden" id="related_customer_id" value="" />
                                    </td>
                                </tr>
                                <tr>
                                    <th>关系类型</th>
                                    <td>
                                        <select id="relationship_type" class="txt1" style="width: auto; min-width: 200px;">
                                            <option value="">请选择关系类型</option>
                                            <option value="1">母公司-子公司</option>
                                            <option value="2">供应商-客户</option>
                                            <option value="3">合作伙伴</option>
                                            <option value="4">竞争对手</option>
                                            <option value="5">推荐人</option>
                                            <option value="6">其他</option>
                                        </select>
                                    </td>
                                </tr>
                                <tr>
                                    <th>关系状态</th>
                                    <td>
                                        <label style="margin-right: 15px;">
                                            <input type="radio" name="relationship_status" value="1" checked>
                                            启用
                                        </label>
                                        <label>
                                            <input type="radio" name="relationship_status" value="0">
                                            停用
                                        </label>
                                    </td>
                                </tr>
                                <tr>
                                    <th>关系描述</th>
                                    <td>
                                        <textarea id="relationship_description" class="txt1" style="width: 90%; height: 100px; resize: vertical;"></textarea>
                                    </td>
                                </tr>
                            </table>
                            
                            <div class="modal-actions">
                                <button type="button" id="save-relationship-btn" class="btn1">保存</button>
                                <button type="button" id="cancel-relationship-btn" class="btn1">取消</button>
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th width="8%">地区/国家</th>
                    <td>
                        <div class="layui-input-inline">
                            <div class="layui-form-select ySearchSelect y1">
                                <div class="layui-input">
                                    <?php
                                    $stmt = $conn->prepare("SELECT id, countryCode, countryName FROM country WHERE id = ?");
                                    $stmt->bind_param("i", $customer['cs_country']);
                                    $stmt->execute();
                                    $countryResult = $stmt->get_result();
                                    if ($countryRow = $countryResult->fetch_assoc()) {
                                        $countryId = $countryRow['id'];
                                        echo htmlspecialcharsFix($countryRow['countryName']);
                                    } else {
                                        echo "请选择";
                                    }
                                    ?>
                                </div>
                                <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>
                                <input name="cs_country" id="cs_country" value="<?= $countryId ?? '' ?>" type="hidden">
                            </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()) {
                                $selected = ($customer['cs_from'] == $row['id']) ? ' selected="selected"' : '';
                                echo "<option value=\"{$row['id']}\"$selected>{$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">
                            <?php if (!empty($contacts)): ?>
                                <?php foreach ($contacts as $index => $contact): ?>
                                <div class="contact-form" id="contact-form-<?= $index ?>">
                                    <div class="contact-header">
                                        <button type="button" class="remove-contact-btn" data-index="<?= $index ?>">删除</button>
                                        <h3>联系人 #<?= $index + 1 ?></h3>
                                    </div>
                                    <input type="hidden" name="contact[<?= $index ?>][id]" value="<?= $contact['id'] ?>">
                                    <div class="contact-method-row">
                                        <span style="width:80px;display:inline-block;font-weight:bold;" class="method-select">联系人姓名</span>
                                        <input type="text" name="contact[<?= $index ?>][contact_name]" value="<?= htmlspecialcharsFix($contact['contact_name']) ?>" class="txt1 method-input" style="width:60%;" placeholder="联系人姓名"/>
                                    </div>
                                    <div class="contact-methods-container" id="contact-methods-<?= $index ?>">
                                        <?php
                                        $methodTypes = [
                                            'tel' => '电话',
                                            'wechat' => '微信',
                                            'whatsapp' => 'WhatsApp',
                                            'email' => '邮箱',
                                            'linkedin' => '领英',
                                            'facebook' => 'Facebook',
                                            'alibaba' => '阿里巴巴'
                                        ];
                                        
                                        foreach ($methodTypes as $type => $label) {
                                            for ($i = 1; $i <= 3; $i++) {
                                                $fieldName = $type . '_' . $i;
                                                if (!empty($contact[$fieldName])) {
                                                    echo '<div class="contact-method-row">';
                                                    echo '<select class="method-select" name="contact[' . $index . '][' . $fieldName . ']" onchange="updateMethodSelectAndPlaceholder(this)">';
                                                    echo '<option value="">请选择联系方式</option>';
                                                    
                                                    foreach ($methodTypes as $optionType => $optionLabel) {
                                                        $selected = ($optionType === $type) ? 'selected' : '';
                                                        echo '<option value="' . $optionType . '" ' . $selected . '>' . $optionLabel . '</option>';
                                                    }
                                                    
                                                    echo '</select>';
                                                    echo '<input type="text" class="txt1 method-input" style="width:60%;" name="contact[' . $index . '][' . $fieldName . ']" value="' . htmlspecialcharsFix($contact[$fieldName]) . '">';
                                                    
                                                    if ($type === 'tel' || $type === 'whatsapp') {
                                                        echo '<input type="hidden" class="format-input" name="contact[' . $index . '][' . $fieldName . '_format]" value="' . htmlspecialcharsFix($contact[$fieldName . '_format']) . '">';
                                                    }
                                                    
                                                    echo '<input type="hidden" class="backup-input" name="contact[' . $index . '][' . $fieldName . '_bu]" value="' . htmlspecialcharsFix($contact[$fieldName . '_bu']) . '">';
                                                    echo '<button type="button" class="remove-method-btn">删除</button>';
                                                    echo '</div>';
                                                }
                                            }
                                        }
                                        ?>
                                    </div>
                                    <button type="button" class="add-method-btn" data-contact-index="<?= $index ?>">添加联系方式</button>
                                </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="contact-form" id="contact-form-0"">
                                    <div class="contact-header">
                                        <button type="button" class="remove-contact-btn" data-index="0">删除</button>
                                        <h3>联系人 #1</h3>
                                    </div>
                                    <input type="hidden" name="contact[0][id]" value="">
                                    <div class="contact-method-row">
                                        <span style="width:80px;display:inline-block;font-weight:bold;" class="method-select">联系人姓名</span>
                                        <input type="text" name="contact[0][contact_name]" class="txt1 method-input" style="width:60%;" placeholder="联系人姓名"/>
                                    </div>
                                    <div class="contact-methods-container" id="contact-methods-0">
                                        <!-- Contact methods will be added here -->
                                    </div>
                                    <button type="button" class="add-method-btn" data-contact-index="0">添加联系方式</button>
                                </div>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th width="8%">地址</th>
                    <td><input type="text" id="cs_address" name="cs_address" value="<?= htmlspecialcharsFix($customer['cs_address']) ?>" class="txt1" /></td>
                </tr>
                <tr>
                    <th>业务类型</th>
                    <td>
                        <?php
                        // 获取当前客户的业务类型
                        $selected_types = [];
                        $type_result = $conn->query("SELECT business_type_id FROM customer_business_type WHERE customer_id = " . intval($id));
                        while ($type_row = $type_result->fetch_assoc()) {
                            $selected_types[] = $type_row['business_type_id'];
                        }
                        
                        $result = $conn->query("SELECT id, businessType FROM clienttype");
                        while ($row = $result->fetch_assoc()) {
                            $checked = in_array($row['id'], $selected_types) ? ' checked="checked"' : '';
                            echo "<input type=\"checkbox\" name=\"cs_type[]\" value=\"{$row['id']}\" id=\"fortype{$row['id']}\"$checked>
                                  <label for=\"fortype{$row['id']}\">{$row['businessType']}</label>";
                        }
                        ?>
                    </td>
                </tr>
                <tr>
                    <th>跟进阶段</th>
                    <td>
                        <?php
                        $dealOptions = [
                            ['id' => '0', 'label' => '无响应'],
                            ['id' => '1', 'label' => '背景调查'],
                            ['id' => '2', 'label' => '明确需求'],
                            ['id' => '3', 'label' => '已成交']
                        ];
                        
                        foreach ($dealOptions as $option) {
                            $checked = ($customer['cs_deal'] == $option['id']) ? ' checked="checked"' : '';
                            $disabled = ($customer['cs_deal'] == '3' && $option['id'] != '3') ? ' disabled="disabled"' : '';
                            echo "<input type=\"radio\" id=\"fordeal{$option['id']}\" class=\"cs_deal\" name=\"cs_deal\" 
                                  value=\"{$option['id']}\"$checked$disabled><label for=\"fordeal{$option['id']}\">{$option['label']}</label>";
                        }
                        ?>
                    </td>
                </tr>
                <tr>
                    <th>其他</th>
                    <td>
                        <input type="checkbox" id="belongClient" class="cs_belongClient" name="cs_belongClient" 
                            value="1"<?= $customer['cs_belongclient'] == 1 ? ' checked="checked"' : '' ?>>
                        <label for="belongClient">客户的客户</label>
                    </td>
                </tr>
                <tr>
                    <th>自定义标签</th>
                    <td>
                        <div class="taglist">
                            <?php
                            $stmt = $conn->prepare("SELECT id, tagName FROM tagtable WHERE customerId = ?");
                            $stmt->bind_param("i", $id);
                            $stmt->execute();
                            $result = $stmt->get_result();
                            while ($row = $result->fetch_assoc()) {
                                echo "<span>" . htmlspecialcharsFix($row['tagName']) . "</span>";
                            }
                            ?>
                        </div>
                        <div class="commontag">
                            <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
                            $stmt = $conn->prepare("SELECT DISTINCT tagName FROM tagtable WHERE employeeId = ?");
                            $stmt->bind_param("i", $_SESSION['employee_id']);
                            $stmt->execute();
                            $result = $stmt->get_result();
                            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添加">
                        <input type="hidden" id="mytag" name="mytag" value="">
                    </td>
                </tr>
                <tr>
                    <th width="8%">备注</th>
                    <td><textarea name="cs_note" class="txt2"><?= htmlspecialcharsFix($customer['cs_note']) ?></textarea></td>
                </tr>
            </tbody>
        </table>
        
        <div class="form-actions">
            <input type="button" name="save" id="save" value="确定" class="btn1" onclick="submitCustomerForm();">
            <input type="button" value="返回" class="btn1" onClick="location.href='customers.php<?= $hrefstr ?>'" />
        </div>
    </form>
</div>
</body>
</html>