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

$act = $_GET['act'] ?? '';

if ($act == "postchk") {
    $keys = urlencode($_GET['Keys'] ?? '');
    $page = $_GET['Page'] ?? '';
    $chkact = $_POST['chkact'] ?? '';

    if (!empty($_POST['chkbox'])) {
        $sqlStr = "";
        $count = count($_POST['chkbox']);
        $ids = implode(',', array_map('intval', $_POST['chkbox']));

        foreach ($_POST['chkbox'] as $id) {
            $sqlStr .= ($sqlStr ? " OR id=" : " WHERE id=") . (int)$id;
        }

        switch ($chkact) {
            case "0":
            case "1":
            case "2":
                $sqlStr = "UPDATE customer SET cs_deal=" . $chkact . $sqlStr;

                // 记录操作日志
                $dealStatus = "";
                switch($chkact) {
                    case "0": $dealStatus = "无响应"; break;
                    case "1": $dealStatus = "背景调查"; break;
                    case "2": $dealStatus = "明确需求"; break;
                }
                $action = "{$_SESSION['employee_name']} 将{$count}个客户({$ids})状态修改为【{$dealStatus}】";
                logAction($action);
                break;
            default:
                // 员工转让操作
                $employeeId = str_replace("t", "", $chkact);

                // 检查是否有客户已经属于目标业务员
                $checkSql = "SELECT GROUP_CONCAT(id) as existing_ids FROM customer 
                             WHERE cs_belong = $employeeId AND id IN ($ids)";
                $checkResult = $conn->query($checkSql);
                $existingIds = "";

                if ($checkResult && $checkRow = $checkResult->fetch_assoc()) {
                    $existingIds = $checkRow['existing_ids'];
                }

                if (!empty($existingIds)) {
                    // 有客户已经属于该业务员,显示错误信息
                    $stmt = $conn->prepare("SELECT em_user FROM employee WHERE id = ?");
                    $stmt->bind_param("i", $employeeId);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    $employeeName = '未知业务员';
                    if ($row = $result->fetch_assoc()) {
                        $employeeName = $row['em_user'];
                    }
                    $stmt->close();

                    echo "<script>alert('无法转移,客户ID:{$existingIds} 已经属于业务员【{$employeeName}】!');history.back();</script>";
                    exit;
                }

                $sqlStr = "UPDATE customer SET cs_belong=" . $employeeId . $sqlStr;

                // 获取员工名称
                $stmt = $conn->prepare("SELECT em_code, em_user FROM employee WHERE id = ?");
                $stmt->bind_param("i", $employeeId);
                $stmt->execute();
                $result = $stmt->get_result();
                $employeeName = '未知业务员';
                if ($row = $result->fetch_assoc()) {
                    $employeeName = $row['em_user'];
                }
                $stmt->close();

                // 记录操作日志
                $action = "{$_SESSION['employee_name']} 批量转移{$count}个客户({$ids})给业务员【{$employeeName}】";
                logAction($action);
        }

        $conn->query($sqlStr);
        header("Location: ?Keys=" . $keys . "&Page=" . $page);
        exit;
    }
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>管理区域</title>
    <link rel="stylesheet" href="css/common.css" type="text/css" />
    <link rel="stylesheet" href="css/alert.css" type="text/css" />
    <script src="js/jquery-1.7.2.min.js"></script>
    <script src="js/js.js"></script>
    <style>
        body {
            margin: 0;
            padding: 20px;
            background: #fff;
        }
        #man_zone {
            margin-left: 0;

        }
    </style>
</head>
<body >
<?php // require_once 'panel.php'; ?>
<div id="man_zone">
<?php


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

$filterCountry = $_GET['fliterCountry'] ?? '';
$filterQudao = $_GET['fliterQudao'] ?? '';
$filterDeal = $_GET['fliterDeal'] ?? '';
$filterBusiness = $_GET['fliterBusiness'] ?? '';
$filterContact = $_GET['fliterContact'] ?? '';

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

if (!empty($filterCountry)) {
    $filterStr .= " AND c.cs_country=" . (int)$filterCountry;
    $urlStr .= "&fliterCountry=" . $filterCountry;
}

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

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

if (!empty($filterBusiness)) {
    $filterStr .= " AND c.cs_type=" . (int)$filterBusiness;
    $urlStr .= "&fliterBusiness=" . $filterBusiness;
}

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

$keys = urlencode($keys);
$hrefstr = "?keys=" . $keys;
?>
<form id="form1" method="post" action="?act=postchk&Keys=<?= $keys ?>&Page=<?= $page ?>" onSubmit="return false">
    <div class="fastSelect clear">
        <H1>当月新增客户</H1>
        <div class="selectItem">
            <label>区域</label>
            <select name="fliterCountry" class="filterSearch">
                <option value="">请选择国家地区</option>
                <?php
                $result = $conn->query("SELECT id, countryName FROM country ORDER BY CONVERT(countryName USING gbk) COLLATE gbk_chinese_ci ASC");
                while ($row = $result->fetch_assoc()) {
                    $selected = ($filterCountry == $row['id']) ? ' selected="selected"' : '';
                    echo "<option value=\"{$row['id']}\"{$selected}>{$row['countryName']}</option>";
                }
                ?>
            </select>
        </div>
        <div class="selectItem">
            <label>来源渠道</label>
            <select name="fliterQudao" class="filterSearch">
                <option value="">请选择渠道</option>
                <?php
                $result = $conn->query("SELECT id, ch_name FROM qudao");
                while ($row = $result->fetch_assoc()) {
                    $selected = ($filterQudao == $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="0"<?= ($filterDeal == "0") ? ' selected="selected"' : '' ?>>无响应</option>
                <option value="1"<?= ($filterDeal == "1") ? ' selected="selected"' : '' ?>>背景调查</option>
                <option value="2"<?= ($filterDeal == "2") ? ' selected="selected"' : '' ?>>明确需求</option>
                <option value="3"<?= ($filterDeal == "3") ? ' selected="selected"' : '' ?>>已成交</option>
            </select>
        </div>
        <div class="selectItem">
            <label>客户类型</label>
            <select name="fliterBusiness" class="filterSearch">
                <option value="">请选择</option>
                <?php
                $result = $conn->query("SELECT id, businessType FROM clienttype");
                while ($row = $result->fetch_assoc()) {
                    $selected = ($filterBusiness == $row['id']) ? ' selected="selected"' : '';
                    echo "<option value=\"{$row['id']}\"{$selected}>{$row['businessType']}</option>";
                }
                ?>
            </select>
        </div>
        <div class="selectItem">
            <label>联系方式</label>
            <select name="fliterContact" class="filterSearch">
                <option value="">请选择</option>
                <option value="1"<?= ($filterContact == "1") ? ' selected="selected"' : '' ?>>电话</option>
                <option value="2"<?= ($filterContact == "2") ? ' selected="selected"' : '' ?>>微信</option>
                <option value="3"<?= ($filterContact == "3") ? ' selected="selected"' : '' ?>>WhatsApp</option>
                <option value="4"<?= ($filterContact == "4") ? ' selected="selected"' : '' ?>>邮箱</option>
                <option value="5"<?= ($filterContact == "5") ? ' selected="selected"' : '' ?>>领英</option>
                <option value="6"<?= ($filterContact == "6") ? ' selected="selected"' : '' ?>>Facebook</option>
                <option value="7"<?= ($filterContact == "7") ? ' selected="selected"' : '' ?>>阿里巴巴</option>
            </select>
        </div>
        <div class="inputSearch">
            <input type="text" id="keys" class="inputTxt" 
                placeholder="请输入搜索关键词"
                value="<?= empty($keyscode) ? '' : $keyscode ?>" 
                onKeyDown="if(event.keyCode==13){location.href='?Keys='+encodeURIComponent(document.getElementById('keys').value)}" />
            <input type="button" id="searchgo" class="searchgo" value="go" 
                onClick="location.href='?Keys='+encodeURIComponent(document.getElementById('keys').value)" />
        </div>
    </div>

    <div  class="table2 em<?= $_SESSION['employee_id'] ?>">
        <div class="theader">
            <div class="col1"><input type="checkbox" name="chkall" id="chkall" onClick="chkboxall(this,'chkbox')" /></div>
            <div class="col2">序号</div>
            <div class="col3">客户编号</div>
            <div class="col4">渠道来源</div>
            <div class="col5">区域</div>
            <div class="col6">客户类型</div>
            <div class="col6">是否成交</div>
            <div class="colmark">颜色标记</div>
            <div class="col6">录入时间</div>
            <div class="col9">操作</div>
        </div>

<?php
$employee_id = intval($_SESSION['employee_id']);
$searchPattern = mysqli_real_escape_string($conn, $keyscode);

$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, c.cs_type, c.cs_belongclient, c.allowedit, c.colorTag
        FROM customer c 
        WHERE c.cs_belong=" . $employee_id . " 
        AND MONTH(c.cs_addtime) = MONTH(CURRENT_DATE()) 
        AND YEAR(c.cs_addtime) = YEAR(CURRENT_DATE())";

if(!empty($searchPattern)) {
    $sql .= " AND (c.cs_code LIKE '%$searchPattern%' 
            OR c.id IN (SELECT customer_id FROM customer_contact WHERE 
                contact_name LIKE '%$searchPattern%' OR
                tel_1 LIKE '%$searchPattern%' OR
                tel_2 LIKE '%$searchPattern%' OR
                tel_3 LIKE '%$searchPattern%' OR
                email_1 LIKE '%$searchPattern%' OR
                email_2 LIKE '%$searchPattern%' OR
                email_3 LIKE '%$searchPattern%' OR
                wechat_1 LIKE '%$searchPattern%' OR
                wechat_2 LIKE '%$searchPattern%' OR
                wechat_3 LIKE '%$searchPattern%' OR
                whatsapp_1_format LIKE '%$searchPattern%' OR
                whatsapp_2_format LIKE '%$searchPattern%' OR
                whatsapp_3_format LIKE '%$searchPattern%' OR
                linkedin_1 LIKE '%$searchPattern%' OR
                linkedin_2 LIKE '%$searchPattern%' OR
                linkedin_3 LIKE '%$searchPattern%' OR
                facebook_1 LIKE '%$searchPattern%' OR
                facebook_2 LIKE '%$searchPattern%' OR
                facebook_3 LIKE '%$searchPattern%' OR
                alibaba_1 LIKE '%$searchPattern%' OR
                alibaba_2 LIKE '%$searchPattern%' OR
                alibaba_3 LIKE '%$searchPattern%')
            OR c.id IN (SELECT customerId FROM tagtable WHERE tagName LIKE '%$searchPattern%'))";
}

$sql .= " $filterStr ORDER BY c.colorTag DESC, c.id DESC";

// Pagination logic
$result = mysqli_query($conn, $sql);
$totalRecords = mysqli_num_rows($result);
$totalPages = max(1, ceil($totalRecords / 20));
$page = max(1, min((int)$page, $totalPages));
$offset = max(0, ($page - 1) * 20);

// Add pagination to query
$sql .= " LIMIT $offset, 20";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    $tempNum = $offset;
    while ($row = mysqli_fetch_assoc($result)) {
        $tempNum++;
?>
        <div class="tline color<?= $row['colorTag'] ?>">
            <div class="col1" align="center"><input type="checkbox" name="chkbox[]" value="<?= $row['id'] ?>" /></div>
            <div class="col2"><?= $tempNum ?></div>
            <div class="col3 slidepanel"><?= htmlspecialcharsFix($row['cs_code']) ?></div>
            <div class="col4">
                <?php
                $cs_from = intval($row['cs_from']);
                $qudaoResult = $conn->query("SELECT ch_name FROM qudao WHERE id=" . $cs_from);
                echo ($qudaoRow = $qudaoResult->fetch_assoc()) ? htmlspecialcharsFix($qudaoRow['ch_name']) : '未填写';
                ?>
            </div>
            <div class="col5">
                <?php
                $cs_country = intval($row['cs_country']);
                $countryResult = $conn->query("SELECT countryName FROM country WHERE id=" . $cs_country);
                echo ($countryRow = $countryResult->fetch_assoc()) ? htmlspecialcharsFix($countryRow['countryName']) : '未填写';
                ?>
            </div>
            <div class="col6">
                <?php
                // 使用JOIN查询一次性获取所有业务类型
                $businessTypes = $conn->query("
                            SELECT ct.businessType 
                            FROM customer_business_type cbt
                            JOIN clienttype ct ON cbt.business_type_id = ct.id
                            WHERE cbt.customer_id = " . (int)$row['id']);

                if ($businessTypes->num_rows > 0) {
                    $types = [];
                    while ($type = $businessTypes->fetch_assoc()) {
                        $types[] = $type['businessType'];
                    }
                    // 显示所有业务类型,用顿号分隔
                    echo implode('、', $types);
                } else {
                    echo '未填写';
                }
                ?>
            </div>
            <div class="col6">
                <?php
                if ($row['cs_deal'] == 3) {
                    echo "<span style='color:red;'>成交</span>";
                } elseif ($row['cs_deal'] == 2) {
                    echo "明确需求";
                } elseif ($row['cs_deal'] == 1) {
                    echo "背景调查";
                } else {
                    echo "无响应";
                }
                ?>
            </div>
            <div class="colmark colormark">
                <ul class="colorlist" data-id="<?= $row['id'] ?>">
                    <li value="1" class="color1"></li>
                    <li value="2" class="color2"></li>
                    <li value="3" class="color3"></li>
                    <li value="4" class="color4"></li>
                    <li value="0" class="color0"></li>
                </ul>
            </div>
            <div class="col6"><?= $row['cs_addtime'] ?></div>
            <div class="col9">
                <a href="customerEdit.php?Keys=<?= $keys ?>&Page=<?= $page ?>&act=edit&id=<?= $row['id'] ?>" 
                   class="ico_edit ico">修改</a>
            </div>
        </div>
        <div class="notepanel clear">
            <div class="noteItem">联系方式</div>
            <div class="lx">
                <?php
                // Fetch all contacts for this customer
                $contact_sql = "SELECT * FROM customer_contact WHERE customer_id = " . $row['id'];
                $contact_result = mysqli_query($conn, $contact_sql);
                while ($contact = mysqli_fetch_assoc($contact_result)) {
                ?>
                <div class="contact-block">
                    <?php if(!empty($contact['contact_name'])): ?>
                        <div class="contact-name"><?= htmlspecialcharsFix($contact['contact_name']) ?></div>
                    <?php endif; ?>
                    <div class="tel">
                        <?php if(!empty($contact['tel_1'])): ?>
                            <div><?= htmlspecialcharsFix($contact['tel_1']) ?></div>
                        <?php endif; ?>
                        <?php if(!empty($contact['tel_2'])): ?>
                            <div><?= htmlspecialcharsFix($contact['tel_2']) ?></div>
                        <?php endif; ?>
                        <?php if(!empty($contact['tel_3'])): ?>
                            <div><?= htmlspecialcharsFix($contact['tel_3']) ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="mail">
                        <?php if(!empty($contact['email_1'])): ?>
                            <div><a href="mailto:<?= htmlspecialcharsFix($contact['email_1']) ?>"><?= htmlspecialcharsFix($contact['email_1']) ?></a></div>
                        <?php endif; ?>
                        <?php if(!empty($contact['email_2'])): ?>
                            <div><a href="mailto:<?= htmlspecialcharsFix($contact['email_2']) ?>"><?= htmlspecialcharsFix($contact['email_2']) ?></a></div>
                        <?php endif; ?>
                        <?php if(!empty($contact['email_3'])): ?>
                            <div><a href="mailto:<?= htmlspecialcharsFix($contact['email_3']) ?>"><?= htmlspecialcharsFix($contact['email_3']) ?></a></div>
                        <?php endif; ?>
                    </div>
                    <div class="whatsapp">
                        <?php if(!empty($contact['whatsapp_1'])): ?>
                            <div><?= htmlspecialcharsFix($contact['whatsapp_1']) ?></div>
                        <?php endif; ?>
                        <?php if(!empty($contact['whatsapp_2'])): ?>
                            <div><?= htmlspecialcharsFix($contact['whatsapp_2']) ?></div>
                        <?php endif; ?>
                        <?php if(!empty($contact['whatsapp_3'])): ?>
                            <div><?= htmlspecialcharsFix($contact['whatsapp_3']) ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="wechat">
                        <?php if(!empty($contact['wechat_1'])): ?>
                            <div><?= htmlspecialcharsFix($contact['wechat_1']) ?></div>
                        <?php endif; ?>
                        <?php if(!empty($contact['wechat_2'])): ?>
                            <div><?= htmlspecialcharsFix($contact['wechat_2']) ?></div>
                        <?php endif; ?>
                        <?php if(!empty($contact['wechat_3'])): ?>
                            <div><?= htmlspecialcharsFix($contact['wechat_3']) ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="linkedin">
                        <?php if(!empty($contact['linkedin_1'])): ?>
                            <div><?= htmlspecialcharsFix($contact['linkedin_1']) ?></div>
                        <?php endif; ?>
                        <?php if(!empty($contact['linkedin_2'])): ?>
                            <div><?= htmlspecialcharsFix($contact['linkedin_2']) ?></div>
                        <?php endif; ?>
                        <?php if(!empty($contact['linkedin_3'])): ?>
                            <div><?= htmlspecialcharsFix($contact['linkedin_3']) ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="facebook">
                        <?php if(!empty($contact['facebook_1'])): ?>
                            <div><?= htmlspecialcharsFix($contact['facebook_1']) ?></div>
                        <?php endif; ?>
                        <?php if(!empty($contact['facebook_2'])): ?>
                            <div><?= htmlspecialcharsFix($contact['facebook_2']) ?></div>
                        <?php endif; ?>
                        <?php if(!empty($contact['facebook_3'])): ?>
                            <div><?= htmlspecialcharsFix($contact['facebook_3']) ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="alibaba">
                        <?php if(!empty($contact['alibaba_1'])): ?>
                            <div><?= htmlspecialcharsFix($contact['alibaba_1']) ?></div>
                        <?php endif; ?>
                        <?php if(!empty($contact['alibaba_2'])): ?>
                            <div><?= htmlspecialcharsFix($contact['alibaba_2']) ?></div>
                        <?php endif; ?>
                        <?php if(!empty($contact['alibaba_3'])): ?>
                            <div><?= htmlspecialcharsFix($contact['alibaba_3']) ?></div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php } ?>
            </div>
            <div class="noteItem2">备注</div>
            <div class="notecontent"><?= htmlUnCode($row['cs_note']) ?></div>
        </div>
<?php
    }
} else {
    if (empty($keys)) {
?>
        <tr>
            <div align="center" colspan="9">Sorry,当前暂无信息</div>
        </tr>
<?php
    } else {
?>
        <tr>
            <div align="center" colspan="9">
                <a href="?">Sorry,没有找到"<?= htmlspecialcharsFix($keyscode) ?>"相关的信息,点击返回</a>
            </div>
        </tr>
<?php
    }
}
?>
        <div colspan="9">
            <div class="showpagebox">
<?php
if (isset($totalPages) && $totalPages > 1) {
    $pageName = "?Keys=" . $keys . $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>";
    }
}
?>
            </div>
            <?php require_once 'postchkbox.php'; ?>
        </div>
    </div>
</form>
</div>
</body>
</html>