<?php
require_once('conn.php');
checkLogin("信息管理");

// 辅助函数
function numFormat($str) {
    // 移除所有非数字字符
    $formatted = preg_replace('/[^0-9]/', '', $str);
    return $formatted;
}

// Initialize variables
$urlStr = "";
$act = $_GET['act'] ?? '';
$output = '';

// Process all actions that might need headers
if ($act == "save") {
    $isEdit = false;
    $id = $_POST['id'] ?? '';
    if (!empty($id) && is_numeric($id)) {
        $isEdit = true;
    }

    // Main customer table fields
    $cs_code = textEncode($_POST['cs_code'] ?? '');
    $cs_company = textEncode($_POST['cs_company'] ?? '');
    $cs_belong = intval($_POST['cs_belong'] ?? 0);
    $cs_country = intval($_POST['cs_country'] ?? 0);
    $cs_from = intval($_POST['cs_from'] ?? 0);
    $cs_state = intval($_POST['cs_state'] ?? 0);
    $cs_deal = intval($_POST['cs_deal'] ?? 0);
    $no_content = htmlEncode($_POST['no_content'] ?? '');
    $cs_address = textEncode($_POST['cs_address'] ?? '');
    $allowedit = isset($_POST['allowedit']) ? 1 : 0;

    // Begin transaction for all database operations
    $conn->begin_transaction();
    
    try {
        if ($isEdit) {
            // Get existing chain info
            $sql = "SELECT cs_chain FROM customer WHERE id=$id";
            $result = $conn->query($sql);
            
            if ($row = $result->fetch_assoc()) {
                $cs_chain = $row['cs_chain'];
                $chain_array = explode(',', $cs_chain);
                $last_item = end($chain_array);
                
                if ($last_item != $cs_belong) {
                    $cs_chain .= ",$cs_belong";
                }
                
                // Update customer table
                $sql = "UPDATE customer SET 
                    cs_code='$cs_code',
                    cs_company='$cs_company',
                    cs_belong=$cs_belong,
                    cs_country=$cs_country,
                    cs_from=$cs_from,
                    cs_state=$cs_state,
                    cs_deal=$cs_deal,
                    cs_note='$no_content',
                    cs_address='$cs_address',
                    allowedit=$allowedit,
                    cs_chain='$cs_chain',
                    cs_updatetime=NOW()
                    WHERE id=$id";
                $conn->query($sql);

                // Delete existing contacts to replace with new ones
                $sql = "DELETE FROM customer_contact WHERE customer_id=$id";
                $conn->query($sql);
            } else {
                throw new Exception('不存在该客户');
            }
        } else {
            // Insert new customer
            $sql = "INSERT INTO customer (
                cs_code, cs_company, cs_belong, cs_country, cs_from,
                cs_state, cs_deal, cs_note, cs_address,
                allowedit, cs_chain, cs_addtime, cs_updatetime
            ) VALUES (
                '$cs_code', '$cs_company', $cs_belong, $cs_country, $cs_from,
                $cs_state, $cs_deal, '$no_content', '$cs_address',
                $allowedit, '$cs_belong', NOW(), NOW()
            )";
            
            $conn->query($sql);
            $id = $conn->insert_id;
        }

        // Process contacts array
        if (isset($_POST['contact']) && is_array($_POST['contact'])) {
            foreach ($_POST['contact'] as $contact) {
                if (empty($contact['contact_name'])) continue;

                $contact_name = textEncode($contact['contact_name']);
                
                // Initialize arrays for contact methods
                $methods = ['tel', 'email', 'whatsapp', 'wechat', 'linkedin', 'facebook', 'alibaba'];
                $fields = ['customer_id', 'contact_name'];
                $values = [$id, "'".$conn->real_escape_string($contact_name)."'"];

                // Process each contact method (up to 3 entries each)
                foreach ($methods as $method) {
                    for ($i = 1; $i <= 3; $i++) {
                        $field_base = $method . '_' . $i;
                        $value = $contact[$field_base] ?? '';
                        $escaped_value = $conn->real_escape_string(textEncode($value));
                        $fields[] = $field_base;
                        $values[] = "'$escaped_value'";

                        // Add format field for tel and whatsapp
                        if ($method == 'tel' || $method == 'whatsapp') {
                            $format_value = numFormat($value);
                            $fields[] = $field_base . '_format';
                            $values[] = "'".$conn->real_escape_string($format_value)."'";
                        }

                        // Add backup field
                        $bu_value = $contact[$field_base . '_bu'] ?? $value;
                        $escaped_bu_value = $conn->real_escape_string(textEncode($bu_value));
                        $fields[] = $field_base . '_bu';
                        $values[] = "'$escaped_bu_value'";
                    }
                }

                // Create and execute insert statement for contact
                $sql = "INSERT INTO customer_contact (" . implode(', ', $fields) . ", created_at, updated_at) 
                        VALUES (" . implode(', ', $values) . ", NOW(), NOW())";
                $conn->query($sql);
            }
        }

        // Commit transaction
        $conn->commit();
        
        // Redirect after successful save
        $page = $_GET['Page'] ?? '';
        $keys = urlencode($_GET['Keys'] ?? '');
        header("Location: ?keys=$keys&Page=$page$urlStr");
        exit;
        
    } catch (Exception $e) {
        // Rollback on failure
        $conn->rollback();
        $output = "<script>alert('保存失败: " . $e->getMessage() . "');history.back();</script>";
    }
}


// If we have output from processing, we'll show it instead of the normal page
if (!empty($output)) {
    echo $output;
    exit;
}


// 批量操作
if ($act == "postchk") {
    $keys = urlencode($_GET['Keys'] ?? '');
    $page = $_GET['Page'] ?? '';
    $chkact = $_POST['chkact'] ?? '';
    
    if (isset($_POST['chkbox']) && is_array($_POST['chkbox'])) {
        $ids = array_map('intval', $_POST['chkbox']);
        $idList = implode(',', $ids);
        
        if (!empty($idList)) {
            switch($chkact) {
                case "0":
                case "1":
                    $sql = "UPDATE customer SET cs_state=$chkact WHERE id IN ($idList)";
                    break;
                default:
                    // In delete case, let's use transactions to ensure both tables are updated
                    $conn->begin_transaction();
                    try {
                        // Delete from customer_contact first (due to foreign key constraint)
                        $sql = "DELETE FROM customer_contact WHERE customer_id IN ($idList)";
                        $conn->query($sql);
                        
                        // Then delete from customer table
                        $sql = "DELETE FROM customer WHERE id IN ($idList)";
                        $conn->query($sql);
                        
                        $conn->commit();
                    } catch (Exception $e) {
                        $conn->rollback();
                        echo "<script>alert('删除失败: " . $e->getMessage() . "');</script>";
                    }
            }
            if ($chkact == "0" || $chkact == "1") {
                $conn->query($sql);
            }
        }
    }
    
    header("Location: ?Keys=$keys&Page=$page");
    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 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="xheditor-1.1.9/xheditor-1.1.9-zh-cn.min.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"
    });

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

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

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);
}
</script>
<style>
    .contact-form {
        margin-bottom: 10px;
        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;
        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>
<div id="man_zone">
<?php

// 编辑操作
if ($act == "edit" || $act == "add") {
    $id = $_GET['id'] ?? '';
    $isEdit = false;
    
    // Initialize variables
    $cs_code = $cs_company = $cs_address = $cs_addtime = $cs_updatetime = $cs_note = '';
    $cs_belong = $cs_country = $cs_from = $cs_state = $cs_deal = $allowedit = $cs_type = $cs_belongclient = 0;
    $contacts = [];

    if (!empty($id) && is_numeric($id)) {
        $isEdit = true;
        
        // Join customer and customer_contact tables
        $sql = "SELECT c.*, cc.* FROM customer c 
                LEFT JOIN customer_contact cc ON c.id = cc.customer_id
                WHERE c.id = $id";
        $result = $conn->query($sql);
        
        if ($row = $result->fetch_assoc()) {
            // Basic customer info
            $cs_code = textUncode($row['cs_code']);
            $cs_company = textUncode($row['cs_company']);
            $cs_country = $row['cs_country'];
            $cs_from = $row['cs_from'];
            $cs_address = textUncode($row['cs_address']);
            $cs_addtime = $row['cs_addtime'];
            $cs_updatetime = $row['cs_updatetime'];
            $cs_belong = $row['cs_belong'];
            $cs_state = $row['cs_state'];
            $cs_deal = $row['cs_deal'];
            $cs_note = htmlUncode($row['cs_note']);
            $allowedit = $row['allowedit'];
            $cs_type = $row['cs_type'];
            $cs_belongclient = $row['cs_belongclient'];

            // Get all contacts for this customer
            $contactSql = "SELECT * FROM customer_contact WHERE customer_id = $id";
            $contactResult = $conn->query($contactSql);
            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;
            }
        }
    }

    $page = $_GET['Page'] ?? '';
    $keys = urlencode($_GET['Keys'] ?? '');
    $ord = urlencode($_GET['Ord'] ?? '');
    $hrefstr = "?keys=$keys&Page=$page&Ord=$ord";
    ?>
    <form name="form1" method="post" action="<?php echo $hrefstr; ?>&act=save">
    <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="<?php echo $cs_code; ?>" class="txt1" />
                    <input type="hidden" name="id" value="<?php echo $id; ?>" /></td>
            </tr>
            <tr>
                <th width="8%">公司名称</th>
                <td><input type="text" id="cs_company" name="cs_company" value="<?php echo $cs_company; ?>" class="txt1" /></td>
            </tr>
            <tr>
                <th width="8%">所属业务</th>
                <td>
                    <select name="cs_belong">
                        <option value="0">请选择</option>
                        <?php
                        $sql = "SELECT id,em_user FROM employee";
                        $result = $conn->query($sql);
                        while($row = $result->fetch_assoc()) {
                            $selected = ($row['id'] == $cs_belong) ? ' selected="selected"' : '';
                            echo "<option value=\"{$row['id']}\"$selected>{$row['em_user']}</option>";
                        }
                        ?>
                    </select>
                </td>
            </tr>
            <tr>
                <th width="8%">国家</th>
                <td>
                    <select name="cs_country">
                        <option value="0">请选择</option>
                        <?php
                        $sql = "SELECT id,countryCode,countryName FROM country";
                        $result = $conn->query($sql);
                        while($row = $result->fetch_assoc()) {
                            $selected = ($row['id'] == $cs_country) ? ' selected="selected"' : '';
                            echo "<option value=\"{$row['id']}\"$selected>{$row['countryName']}</option>";
                        }
                        ?>
                    </select>
                </td>
            </tr>
            <tr>
                <th width="8%">来源</th>
                <td>
                    <select name="cs_from">
                        <option value="0">请选择</option>
                        <?php
                        $sql = "SELECT id,ch_name FROM qudao";
                        $result = $conn->query($sql);
                        while($row = $result->fetch_assoc()) {
                            $selected = ($row['id'] == $cs_from) ? ' selected="selected"' : '';
                            echo "<option value=\"{$row['id']}\"$selected>{$row['ch_name']}</option>";
                        }
                        ?>
                    </select>
                </td>
            </tr>
            <tr>
                <th width="8%">录入时间</th>
                <td><?php echo $cs_addtime; ?></td>
            </tr>
            <tr>
                <th width="8%">更新时间</th>
                <td><?php echo $cs_updatetime; ?></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-<?php echo $index; ?>">
                                <div class="contact-header">
                                    <button type="button" class="remove-contact-btn" data-index="<?php echo $index; ?>">删除</button>
                                    <h3>联系人 #<?php echo $index + 1; ?></h3>
                                </div>
                                <input type="hidden" name="contact[<?php echo $index; ?>][id]" value="<?php echo $contact['id']; ?>">
                                <table width="100%" border="0" cellpadding="3" cellspacing="1" class="contact-table">
                                    <tr>
                                        <th width="8%">联系人</th>
                                        <td><input type="text" name="contact[<?php echo $index; ?>][contact_name]" value="<?php echo htmlspecialcharsFix($contact['contact_name']); ?>" class="txt1" placeholder="联系人姓名"/></td>
                                    </tr>
                                </table>
                                <div class="contact-methods-container" id="contact-methods-<?php echo $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 '</div>';
                                            }
                                        }
                                    }
                                    ?>
                                </div>
                                <button type="button" class="add-method-btn" data-contact-index="<?php echo $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="">
                                <table width="100%" border="0" cellpadding="3" cellspacing="1" class="contact-table">
                                    <tr>
                                        <th width="8%">联系人</th>
                                        <td><input type="text" name="contact[0][contact_name]" class="txt1" placeholder="联系人姓名"/></td>
                                    </tr>
                                </table>
                                <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="<?php echo $cs_address; ?>" class="txt1" /></td>
            </tr>
            <tr>
                <th width="8%">标签</th>
                <td>
                    <?php
                    if($isEdit) {
                        $sql = "SELECT id,tagName FROM tagtable WHERE customerId = " . (int)$id;
                        $result = $conn->query($sql);
                        while($row = $result->fetch_assoc()) {
                            echo htmlspecialcharsFix($row['tagName']) . ',';
                        }
                    }
                    ?>
                </td>
            </tr>
            <tr>
                <th width="8%">状态</th>
                <td>
                    <label><input type="radio" name="cs_state" value="1" <?php if($cs_state==1) echo 'checked="checked"'; ?> />有效</label> 
                    <label><input type="radio" name="cs_state" value="0" <?php if($cs_state!=1) echo 'checked="checked"'; ?> />不再跟进</label>
                </td>
            </tr>
            <tr>
                <th width="8%">是否误报</th>
                <td>
                    <label><input type="radio" name="allowedit" value="1" <?php if($allowedit==1) echo 'checked="checked"'; ?> />审核通过</label> 
                    <label><input type="radio" name="allowedit" value="0" <?php if($allowedit!=1) echo 'checked="checked"'; ?> />一般处理</label>
                </td>
            </tr>
            <tr>
                <th width="8%">是否成交</th>
                <td>
                    <label><input type="radio" name="cs_deal" value="3" <?php if($cs_deal==3) echo 'checked="checked"'; ?> />成交</label> 
                    <label><input type="radio" name="cs_deal" value="2" <?php if($cs_deal==2) echo 'checked="checked"'; ?> />明确需求</label>
                    <label><input type="radio" name="cs_deal" value="1" <?php if($cs_deal==1) echo 'checked="checked"'; ?> />背景调查</label>
                    <label><input type="radio" name="cs_deal" value="0" <?php if($cs_deal==0) echo 'checked="checked"'; ?> />无响应</label>
                </td>
            </tr>
            <tr>
                <th>内容</th>
                <td><textarea id="no_content" name="no_content" class="txt2"><?php echo $cs_note; ?></textarea></td>
            </tr>
            <tr>
                <th></th>
                <td>
                    <input type="submit" name="save" id="save" value="确定" class="btn1" /> 
                    <input type="reset" name="save" id="save" value="重置" class="btn1" /> 
                    <input type="button" value="返回" class="btn1" onClick="location.href='<?php echo $hrefstr; ?>'" />
                </td>
            </tr>
        </tbody>
    </table>
    </form>
    <?php
    exit;
}



// 主列表页面
$fliterQudao = $_GET['fliterQudao'] ?? '';
$fliterDeal = $_GET['fliterDeal'] ?? '';
$fliterTeam = $_GET['fliterTeam'] ?? '';
$fliterContact = $_GET['fliterContact'] ?? '';
$fliterEmployee = $_GET['fliterEmployee'] ?? '';

$filterStr = "";
$urlStr = "";

if (!empty($fliterQudao)) {
    $filterStr .= " AND c.cs_from=" . intval($fliterQudao);
    $urlStr .= "&fliterQudao=$fliterQudao";
}

if (!empty($fliterDeal)) {
    $filterStr .= " AND c.cs_deal=" . intval($fliterDeal);
    $urlStr .= "&fliterDeal=$fliterDeal";
}

if (!empty($fliterTeam)) {
    $teamId = intval($fliterTeam);
    $filterStr .= " AND (c.cs_belong=$teamId OR c.cs_belong IN (SELECT id FROM employee WHERE em_role=$teamId))";
    $urlStr .= "&fliterTeam=$fliterTeam";
}

if (!empty($fliterEmployee)) {
    $filterStr .= " AND c.cs_belong=" . intval($fliterEmployee);
    $urlStr .= "&fliterEmployee=$fliterEmployee";
}

if (!empty($fliterContact)) {
    switch($fliterContact) {
        case "1": $filterStr .= " AND (cc.tel_1 != '' OR cc.tel_2 != '' OR cc.tel_3 != '')"; break;
        case "2": $filterStr .= " AND (cc.wechat_1 != '' OR cc.wechat_2 != '' OR cc.wechat_3 != '')"; break;
        case "3": $filterStr .= " AND (cc.whatsapp_1 != '' OR cc.whatsapp_2 != '' OR cc.whatsapp_3 != '')"; break;
        case "4": $filterStr .= " AND (cc.email_1 != '' OR cc.email_2 != '' OR cc.email_3 != '')"; break;
        case "5": $filterStr .= " AND (cc.linkedin_1 != '' OR cc.linkedin_2 != '' OR cc.linkedin_3 != '')"; break;
        case "6": $filterStr .= " AND (cc.facebook_1 != '' OR cc.facebook_2 != '' OR cc.facebook_3 != '')"; break;
        default: $filterStr .= " AND (cc.alibaba_1 != '' OR cc.alibaba_2 != '' OR cc.alibaba_3 != '')";
    }
    $urlStr .= "&fliterContact=$fliterContact";
}

$keys = $_GET['Keys'] ?? '';
$keyscode = textEncode($keys);
$page = $_GET['Page'] ?? '';
$ord = $_GET['Ord'] ?? '';

$sql = "SELECT c.id, c.cs_code, c.cs_company, c.cs_country, c.cs_address, 
        c.cs_from, c.cs_deal, c.cs_addtime, c.cs_updatetime, c.cs_belong, c.cs_note, 
        c.cs_claimFrom, c.cs_chain, c.cs_dealdate,
        cc.contact_name as cs_name, 
        cc.tel_1 as cs_tel, cc.email_1 as cs_email, 
        cc.whatsapp_1 as cs_whatsapp, cc.wechat_1 as cs_wechat, 
        cc.linkedin_1 as cs_linkedin, cc.facebook_1 as cs_facebook, 
        cc.alibaba_1 as cs_alibaba
        FROM customer c 
        LEFT JOIN customer_contact cc ON c.id = cc.customer_id
        WHERE (c.cs_code LIKE '%".$conn->real_escape_string($keyscode)."%' 
        OR cc.contact_name LIKE '%".$conn->real_escape_string($keyscode)."%' 
        OR cc.tel_1 LIKE '%".$conn->real_escape_string($keyscode)."%'
        OR cc.tel_2 LIKE '%".$conn->real_escape_string($keyscode)."%'
        OR cc.tel_3 LIKE '%".$conn->real_escape_string($keyscode)."%'
        OR cc.wechat_1 LIKE '%".$conn->real_escape_string($keyscode)."%'
        OR cc.wechat_2 LIKE '%".$conn->real_escape_string($keyscode)."%'
        OR cc.wechat_3 LIKE '%".$conn->real_escape_string($keyscode)."%'
        OR cc.alibaba_1 LIKE '%".$conn->real_escape_string($keyscode)."%' 
        OR cc.alibaba_2 LIKE '%".$conn->real_escape_string($keyscode)."%'
        OR cc.alibaba_3 LIKE '%".$conn->real_escape_string($keyscode)."%'
        OR cc.whatsapp_1_format LIKE '%".$conn->real_escape_string($keyscode)."%'
        OR cc.whatsapp_2_format LIKE '%".$conn->real_escape_string($keyscode)."%'
        OR cc.whatsapp_3_format LIKE '%".$conn->real_escape_string($keyscode)."%'
        OR cc.email_1 LIKE '%".$conn->real_escape_string($keyscode)."%'
        OR cc.email_2 LIKE '%".$conn->real_escape_string($keyscode)."%'
        OR cc.email_3 LIKE '%".$conn->real_escape_string($keyscode)."%') 
        AND c.cs_state=1
        $filterStr 
        ORDER BY c.cs_updatetime DESC";

// Execute query to count total records
$countResult = $conn->query($sql);
if (!$countResult) {
    die("查询失败: " . $conn->error . "<br>SQL: " . $sql);
}
$totalRecords = $countResult->num_rows;
$countResult->close(); // 关闭第一个结果集

// Create pagination variables
$pageSize = 18;
$totalPages = ceil($totalRecords / $pageSize);
if ($totalPages < 1) $totalPages = 1; // 确保至少有一页,即使没有结果

if (empty($page)) $page = 1;
if ($page == 'end') $page = $totalPages;
if (!is_numeric($page) || $page < 1) $page = 1;
$page = (int)$page;
if ($page > $totalPages) $page = $totalPages;

// Apply pagination
$offset = ($page - 1) * $pageSize;
if ($offset < 0) $offset = 0; // 确保偏移量不为负数
$sql_paginated = $sql . " LIMIT $offset, $pageSize";  // 使用新变量,不修改原始SQL

// Execute the paginated query
$result = $conn->query($sql_paginated);
if (!$result) {
    die("分页查询失败: " . $conn->error . "<br>SQL: " . $sql_paginated);
}
$tempNum = $pageSize * ($page - 1);

?>

<form id="form1" method="post" action="?act=postchk&Keys=<?php echo $keys; ?>&Page=<?php echo $page; ?>" onSubmit="return false">
    <div class="fastSelect clear">
        <H1>搜索条件</H1>
        <div class="selectItem">        
        <label>来源渠道</label>
            <select name="fliterQudao" class="filterSearch">
                <option value="">请选择渠道</option>
                <?php 
                $sql_temp = "SELECT id,ch_name FROM qudao";
                $qudaoResult = $conn->query($sql_temp);
                while($row = $qudaoResult->fetch_assoc()) {
                    $selected = ($fliterQudao == $row['id']) ? ' selected="selected"' : '';
                    echo "<option value=\"{$row['id']}\"$selected>{$row['ch_name']}</option>";
                }
                ?>
            </select>    
        </div>
        <div class="selectItem">        
        <label>是否成交</label>
            <select name="fliterDeal" class="filterSearch">
                <option value="">请选择</option>
                <option value="3" <?php if($fliterDeal=="3") echo 'selected="selected"'; ?>>已成交</option>                    
                <option value="2" <?php if($fliterDeal=="2") echo 'selected="selected"'; ?>>明确需求</option>                    
                <option value="1" <?php if($fliterDeal=="1") echo 'selected="selected"'; ?>>背景调查</option>    
                <option value="0" <?php if($fliterDeal=="0") echo 'selected="selected"'; ?>>无响应</option>            
            </select>
        </div>
        <div class="selectItem">        
        <label>按组</label>
            <select name="fliterTeam" class="filterSearch">
                <option value="">请选择</option>
                <?php
                $sql_temp = "SELECT id,em_user FROM employee WHERE em_role=0";
                $teamResult = $conn->query($sql_temp);
                while($row = $teamResult->fetch_assoc()) {
                    $selected = ($fliterTeam == $row['id']) ? ' selected="selected"' : '';
                    echo "<option value=\"{$row['id']}\"$selected>{$row['em_user']}组</option>";
                }
                ?>            
            </select>
        </div>
        
        <div class="selectItem">        
        <label>业务</label>
            <select name="fliterEmployee" class="filterSearch">
                <option value="">请选择</option>
                <?php
                $sql_temp = "SELECT id,em_user FROM employee";
                $empResult = $conn->query($sql_temp);
                while($row = $empResult->fetch_assoc()) {
                    $selected = ($fliterEmployee == $row['id']) ? ' selected="selected"' : '';
                    echo "<option value=\"{$row['id']}\"$selected>{$row['em_user']}</option>";
                }
                ?>            
            </select>
        </div>
        
        <div class="selectItem">        
        <label>联系方式</label>
            <select name="fliterContact" class="filterSearch">
                <option value="">请选择</option>
                <option value="1" <?php if($fliterContact=="1") echo 'selected="selected"'; ?>>电话</option>        
                <option value="2" <?php if($fliterContact=="2") echo 'selected="selected"'; ?>>微信</option>    
                <option value="3" <?php if($fliterContact=="3") echo 'selected="selected"'; ?>>WhatsApp</option>        
                <option value="4" <?php if($fliterContact=="4") echo 'selected="selected"'; ?>>邮箱</option>            
                <option value="5" <?php if($fliterContact=="5") echo 'selected="selected"'; ?>>领英</option>        
                <option value="6" <?php if($fliterContact=="6") echo 'selected="selected"'; ?>>Facebook</option>            
                <option value="7" <?php if($fliterContact=="7") echo 'selected="selected"'; ?>>阿里巴巴</option>            
            </select>
        </div>
        <div class="inputSearch">
            <input type="text" id="keys" class="inputTxt" placeholder="请输入搜索关键词" value="<?php echo empty($keyscode) ? '' : $keyscode; ?>"
                    />
            <input type="button" id="searchgo" class="searchgo" value="go" 
                   onClick="location.href='?Keys='+encodeURIComponent(document.getElementById('keys').value)+'<?php echo $urlStr; ?>'" />
        </div>
    </div>
    
    <table width="100%" border="0" cellpadding="3" cellspacing="1" class="table1">
        <thead>
            <tr>
                <th width="4%"><input type="checkbox" name="chkall" id="chkall" onClick="chkboxall(this,'chkbox')" /></th>
                <th width="6%">序号</th>
                <th width="20%">客户编码</th>
                <th width="10%">联系人</th>
                <th width="10%">国家地区</th>    
                <th width="7.5%">来源</th>                        
                <th width="7.5%">是否成交</th>        
                <th width="10%">业务员</th>                    
                <th width="10%">操作</th>
            </tr>
        </thead>
        <tbody>
        <?php
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $tempNum++;
                ?>
                <tr onMouseOver="this.style.background='#F7FCFF'" onMouseOut="this.style.background='#FFFFFF'">
                    <td align="center"><input type="checkbox" name="chkbox[]" value="<?php echo $row['id'] ?? ''; ?>" /></td>
                    <td align="center"><?php echo $tempNum; ?></td>
                    <td align="center" class="code" data-id="<?php echo $row['id'] ?? ''; ?>">
                        <?php
                        echo $row['cs_code'] ?? ''; ?>
                        <?php if(($row['cs_claimFrom'] ?? 0) > 0): ?>
                            <img src="../images/yijiao.png" class="handover">
                        <?php endif; ?>
                    </td>
                    <td align="center"><?php echo htmlspecialcharsFix($row['cs_name'] ?? ''); ?></td>
                    <td align="center">
                        <?php
                        $countryId = intval($row['cs_country'] ?? 0);
                        $sql = "SELECT countryName FROM country WHERE id = $countryId";
                        $countryResult = $conn->query($sql);
                        if ($countryResult && $countryRow = $countryResult->fetch_assoc()) {
                            echo htmlspecialcharsFix($countryRow['countryName']);
                        } else {
                            echo "未选择";
                        }
                        ?>
                    </td>
                    <td align="center">
                        <?php
                        $fromId = intval($row['cs_from'] ?? 0);
                        $sql = "SELECT ch_name FROM qudao WHERE id = $fromId";
                        $fromResult = $conn->query($sql);
                        if ($fromResult && $fromRow = $fromResult->fetch_assoc()) {
                            echo htmlspecialcharsFix($fromRow['ch_name']);
                        } else {
                            echo "未选择";
                        }
                        ?>
                    </td>
                    <td align="center">
                        <?php 
                        if (($row['cs_deal'] ?? 0) == 3) {
                            echo "<span style='color:red;font-size:10px;'>" . htmlspecialcharsFix($row['cs_dealdate'] ?? '') . "成交</span>";
                        } elseif (($row['cs_deal'] ?? 0) == 2) {
                            echo "明确需求";
                        } elseif (($row['cs_deal'] ?? 0) == 1) {
                            echo "背景调查";
                        } else {
                            echo "无响应";
                        }
                        ?>
                    </td>
                    <td align="center">
                        <?php
                        $belongId = intval($row['cs_belong'] ?? 0);
                        $sql = "SELECT em_user FROM employee WHERE id = $belongId";
                        $empResult = $conn->query($sql);
                        if ($empResult && $empRow = $empResult->fetch_assoc()) {
                            echo htmlspecialcharsFix($empRow['em_user']);
                        } else {
                            echo "未选择";
                        }
                        ?>
                    </td>                
                    <td align="center">
                        <a href="?Keys=<?php echo urlencode($keys ?? ''); ?>&Page=<?php echo urlencode($page ?? '') . $urlStr; ?>&act=edit&id=<?php echo $row['id'] ?? ''; ?>" class="ico_edit ico">修改</a>
                    </td>
                </tr>
                <tr class="detail_panel code<?php echo $row['id'] ?? ''; ?>__panel">
                    <td colspan="2"></td>
                    <td colspan="7" class="cs_detail">                    
                        <ul>                
                            <li class="cs_detail_addtime">录入时间:<?php echo htmlspecialcharsFix($row['cs_addtime'] ?? ''); ?></li>
                            <li class="cs_detail_addtime">更新时间:<?php echo htmlspecialcharsFix($row['cs_updatetime'] ?? ''); ?></li>
                            <li class="cs_detail_addtime">
                                流转记录:
                                <?php                                
                                $chain = $row['cs_chain'] ?? '';
                                if(!empty($chain)) {
                                    $chain_array = explode(',', $chain);
                                    $chain_ids = array_filter(array_map('intval', $chain_array));
                                    
                                    if(!empty($chain_ids)) {
                                        $chain_ids_str = implode(',', $chain_ids);
                                        $sql = "SELECT em_user FROM employee WHERE id IN (" . $chain_ids_str . ")";
                                        $chainResult = $conn->query($sql);
                                        $chain_users = [];
                                        while($chainRow = $chainResult->fetch_assoc()) {
                                            $chain_users[] = htmlspecialcharsFix($chainRow['em_user']);
                                        }
                                        echo implode(' > ', $chain_users);
                                    }
                                }
                                ?>             
                            </li>
                            <?php if(!empty($row['cs_tel'] ?? '')): ?>
                                <li class="tel"><?php echo htmlspecialcharsFix($row['cs_tel']); ?></li>
                            <?php endif; ?>
                            <?php if(!empty($row['cs_email'] ?? '')): ?>
                                <li class="mail"><?php echo htmlspecialcharsFix($row['cs_email']); ?></li>
                            <?php endif; ?>
                            <?php if(!empty($row['cs_whatsapp'] ?? '')): ?>
                                <li class="whatsapp"><?php echo htmlspecialcharsFix($row['cs_whatsapp']); ?></li>
                            <?php endif; ?>
                            <?php if(!empty($row['cs_wechat'] ?? '')): ?>
                                <li class="wechat"><?php echo htmlspecialcharsFix($row['cs_wechat']); ?></li>
                            <?php endif; ?>
                            <?php if(!empty($row['cs_linkedin'] ?? '')): ?>
                                <li class="linkedin"><?php echo htmlspecialcharsFix($row['cs_linkedin']); ?></li>
                            <?php endif; ?>
                            <?php if(!empty($row['cs_facebook'] ?? '')): ?>
                                <li class="facebook"><?php echo htmlspecialcharsFix($row['cs_facebook']); ?></li>
                            <?php endif; ?>
                            <?php if(!empty($row['cs_alibaba'] ?? '')): ?>
                                <li class="alibaba"><?php echo htmlspecialcharsFix($row['cs_alibaba']); ?></li>
                            <?php endif; ?>
                            <?php if(!empty($row['cs_address'] ?? '')): ?>
                                <li class="address"><?php echo htmlspecialcharsFix($row['cs_address']); ?></li>
                            <?php endif; ?>
                        </ul>
                        <div class="cs_detail_note"><?php echo htmlspecialcharsFix($row['cs_note'] ?? ''); ?></div>
                    </td>                
                </tr>
                <?php
            }
        } else {
            // 没有搜索结果的情况
            if (!empty($keyscode)) {
                echo '<tr><td colspan="9" align="center">没有找到 "' . htmlspecialcharsFix($keyscode) . '" 相关的客户信息</td></tr>';
            } else {
                echo '<tr><td colspan="9" align="center">暂无客户信息</td></tr>';
            }
        }
        ?>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="9">
                    <div class="showpagebox">
                    <?php
                    if ($totalPages > 1) {
                        $pageName = "?Keys=$keys&Ord=$ord$urlStr&";
                        $pageLen = 3;
                        
                        if ($page > 1) {
                            echo "<a href=\"{$pageName}Page=1\">首页</a>";
                            echo "<a href=\"{$pageName}Page=" . ($page-1) . "\">上一页</a>";
                        }
                        
                        if ($pageLen * 2 + 1 >= $totalPages) {
                            $startPage = 1;
                            $endPage = $totalPages;
                        } else {
                            if ($page <= $pageLen + 1) {
                                $startPage = 1;
                                $endPage = $pageLen * 2 + 1;
                            } else {
                                $startPage = $page - $pageLen;
                                $endPage = $page + $pageLen;
                            }
                            if ($page + $pageLen > $totalPages) {
                                $startPage = $totalPages - $pageLen * 2;
                                $endPage = $totalPages;
                            }
                        }
                        
                        for ($i = $startPage; $i <= $endPage; $i++) {
                            if ($i == $page) {
                                echo "<a class=\"current\">$i</a>";
                            } else {
                                echo "<a href=\"{$pageName}Page=$i\">$i</a>";
                            }
                        }
                        
                        if ($page < $totalPages) {
                            if ($totalPages - $page > $pageLen) {
                                echo "<a href=\"{$pageName}Page=$totalPages\">...$totalPages</a>";
                            }
                            echo "<a href=\"{$pageName}Page=" . ($page+1) . "\">下一页</a>";
                            echo "<a href=\"{$pageName}Page=$totalPages\">尾页</a>";
                        }
                        
                        echo "<input type=\"text\" id=\"Pagego\" value=\"$page\" 
                              onFocus=\"if(this.value == '$page'){this.value='';}\" 
                              onBlur=\"if(this.value == ''){this.value='$page';}\" 
                              onKeyUp=\"this.value=this.value.replace(/\D/g,'')\" 
                              onKeyDown=\"if(event.keyCode==13){location.href='{$pageName}Page='+document.getElementById('Pagego').value}\" />";
                    }
                    ?>
                    </div>
                    <div class="postchkbox">
                        <select id="chkact" name="chkact">
                            <option value="1">显示</option>
                            <option value="0">隐藏</option>
                            <option value="-1">删除</option>
                        </select>
                        <input type="button" value="执行" onClick="postchk_new(1)" class="btn1" />
                        <input type="button" value="新增" onClick="location.href='?act=add'" class="btn1" />
                    </div>
                </td>
            </tr>
        </tfoot>
    </table>
</form>
</div>
</body>
</html>
<?php
$conn->close();
?>