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

// 检查当前用户是否为组长
$isLeader = false;
$userInfoQuery = "SELECT em_role, em_permission_role_id FROM employee WHERE id = " . $_SESSION['employee_id'];
$userResult = $conn->query($userInfoQuery);
if ($userResult && $userRow = $userResult->fetch_assoc()) {
    // 只有 em_permission_role_id=2 表示该用户是组长
    $isLeader = ($userRow['em_permission_role_id'] == 2);
}

// 如果不是组长,直接跳转到客户列表页面
if (!$isLeader) {
    header('Location: customers.php');
    exit;
}

// 获取URL参数
$tagName = $_GET['tagName'] ?? '';
$employeeId = $_GET['employeeId'] ?? $_SESSION['employee_id'];

if (empty($employeeId) || !is_numeric($employeeId)) {
    $employeeId = $_SESSION['employee_id'];
}

// 如果不是组长,只能查看自己的数据
if (!$isLeader) {
    $employeeId = $_SESSION['employee_id'];
} else if ($employeeId != $_SESSION['employee_id']) {
    // 如果是组长查看组员数据,确认该员工确实是自己的组员
    $checkSubordinate = "SELECT id FROM employee WHERE id = $employeeId AND em_role = " . $_SESSION['employee_id'];
    $checkResult = $conn->query($checkSubordinate);
    if (!$checkResult || $checkResult->num_rows == 0) {
        // 不是自己的组员,只能查看自己的数据
        $employeeId = $_SESSION['employee_id'];
    }
}

if (empty($tagName)) {
    header('Location: customers.php');
    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="system/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 class="clear">
<?php // require_once 'panel.php'; ?>
<div id="man_zone">
    <div class="fastSelect clear">
        <h1>标签:<?= htmlspecialcharsFix($tagName) ?></h1>
        <?php if ($isLeader): ?>
        <p>查看员工: <?php 
            $empQuery = "SELECT em_user FROM employee WHERE id = $employeeId";
            $empResult = $conn->query($empQuery);
            if ($empResult && $empRow = $empResult->fetch_assoc()) {
                echo htmlspecialcharsFix($empRow['em_user']);
            } else {
                echo "未知";
            }
        ?></p>
        <?php endif; ?>
    </div>

    <div width="100%" border="0" cellpadding="3" cellspacing="1" class="table2">
        <div class="theader">
            <div class="col2">序号</div>
            <div class="col3">客户编号</div>
            <div class="col4">渠道来源</div>
            <div class="col5">区域</div>
            <div class="col6">客户类型</div>
            <div class="col7">跟进阶段</div>
            <div class="col8">录入时间</div>
            <div class="col10">操作</div>
        </div>

        <?php
        // 优化SQL查询:如果是组长,可以根据所选组员查看,否则只看自己的
        $sqlStr = "SELECT c.id, c.cs_code, c.cs_from, c.cs_country, c.cs_type, c.cs_deal, c.cs_addtime, c.cs_note, c.cs_belong
                  FROM customer c
                  WHERE c.cs_belong = $employeeId 
                  AND c.id IN (SELECT customerId FROM tagtable WHERE tagName='" . $conn->real_escape_string($tagName) . "')";

        $result = $conn->query($sqlStr);
        $tempNum = 0;

        if ($result && $result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $tempNum++;
                
                // 获取联系人信息
                $contactSql = "SELECT * FROM customer_contact WHERE customer_id = " . $row['id'];
                $contactResult = $conn->query($contactSql);
                $contactData = $contactResult->num_rows > 0 ? $contactResult->fetch_assoc() : null;
        ?>
                <div class="tline">
                    <div class="col2"><?= $tempNum ?></div>
                    <div class="col3 slidepanel"><?= htmlspecialcharsFix($row['cs_code']) ?></div>
                    <div class="col4">
                        <?php
                        $qudaoResult = $conn->query("SELECT ch_name FROM qudao WHERE id=" . (int)$row['cs_from']);
                        echo ($qudaoRow = $qudaoResult->fetch_assoc()) ? htmlspecialcharsFix($qudaoRow['ch_name']) : '未填写';
                        ?>
                    </div>
                    <div class="col5">
                        <?php
                        $countryResult = $conn->query("SELECT countryName FROM country WHERE id=" . (int)$row['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="col7">
                        <?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="col8"><?= $row['cs_addtime'] ?></div>
                    <div class="col10"><a href="customerEdit.php?id=<?= $row['id'] ?>" class="ico_edit ico">修改</a></div>
                </div>
                <div class="notepanel clear">
                    <div class="noteItem">联系方式</div>
                    <div class="lx">
                        <?php 
                        // 展示联系人信息
                        if ($contactData) {
                            $contactFields = [
                                'tel' => ['电话', false],
                                'email' => ['邮箱', true],
                                'whatsapp' => ['WhatsApp', false],
                                'wechat' => ['微信', false],
                                'linkedin' => ['领英', false],
                                'facebook' => ['Facebook', false],
                                'alibaba' => ['阿里巴巴', false]
                            ];
                            
                            foreach ($contactFields as $fieldBase => $config) {
                                $fieldName = $config[0];
                                $isEmail = $config[1];
                                
                                echo "<div class=\"$fieldBase\">";
                                for ($i = 1; $i <= 3; $i++) {
                                    $field = $fieldBase . '_' . $i;
                                    if (!empty($contactData[$field])) {
                                        if ($isEmail) {
                                            echo "<div><a href=\"mailto:" . htmlspecialcharsFix($contactData[$field]) . "\">" . 
                                                 htmlspecialcharsFix($contactData[$field]) . "</a></div>";
                                        } else {
                                            echo "<div>" . htmlspecialcharsFix($contactData[$field]) . "</div>";
                                        }
                                    }
                                }
                                echo "</div>";
                            }
                        }
                        ?>
                    </div>
                    <div class="noteItem2">备注</div>
                    <div class="notecontent"><?= htmlUnCode($row['cs_note']) ?></div>
                </div>
        <?php
            }
        }
        ?>
    </div>
</div>
</body>
</html>