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

$cid = $_GET['cid'] ?? '';
if (empty($cid) || !is_numeric($cid)) {
    $cid = 0;
}

// Check claim limit for today
$sqlstr = "SELECT COUNT(id) as claimcount FROM customer WHERE cs_belong = " . $_SESSION['employee_id'] . 
          " AND cs_claimdate > '" . date('Y-m-d') . "'";

$result = $conn->query($sqlstr);
$row = $result->fetch_assoc();
$reachedLimit = ($row['claimcount'] > 10);

// Get employee code
$result = $conn->query("SELECT em_code FROM employee WHERE id = " . $_SESSION['employee_id']);
$row = $result->fetch_assoc();
$em_code = $row['em_code'];

if ($reachedLimit) {
    echo "-1";
} else {
    // Get customer info and update
    $sql = "SELECT employee.id as originalId, cs_code, em_user, cs_belong, cs_updatetime, cs_claimdate, 
            cs_claimFrom, cs_chain, is_silent 
            FROM customer 
            LEFT JOIN employee ON customer.cs_belong = employee.id 
            WHERE customer.id = " . $conn->real_escape_string($cid);
    
    $result = $conn->query($sql);
    
    if ($row = $result->fetch_assoc()) {
        // 检查是否在认领自己的客户
        if ($row['cs_belong'] == $_SESSION['employee_id']) {
            echo "-2"; // 返回错误代码 -2 表示不能认领自己的客户
            exit;
        }
        
        $oldCode = $row['cs_code'];
        $originalEmp = $row['em_user'];
        $originalId= $row['cs_belong'];
        $newCode = str_replace("-", "/0" . substr($em_code, 1) . "-", $oldCode);
        
        // Update chain and check circulation
        $newChain = $row['cs_chain'] . "," . $_SESSION['employee_id'];
        $circulation = substr_count($newChain, ',');
        $is_silent = ($circulation > 3) ? 1 : 0;
        
        // Update customer
        $updateSql = "UPDATE customer SET 
            cs_belong = " . $_SESSION['employee_id'] . ",
            cs_claimdate = NOW(),
            cs_code = '" . $conn->real_escape_string($newCode) . "',
            cs_updatetime = NOW(),
            cs_claimFrom = " . $row['originalId'] . ",
            cs_chain = '" . $conn->real_escape_string($newChain) . "',
            is_silent = " . $is_silent . "
            WHERE id = " . $cid;
            
        $conn->query($updateSql);
        
        // Insert claim record
        $insertSql = "INSERT INTO claimrecord (oldCode, originalEmp,original_employee_id, newEmp,new_employee_id, cs_id, claimTime, isread) 
                     VALUES (
                         '" . $conn->real_escape_string($oldCode) . "',
                         '" . $conn->real_escape_string($originalEmp) . "',
                         '" . $conn->real_escape_string($originalId) . "',
                         '" . $conn->real_escape_string($_SESSION['employee_name']) . "',
                         '" . $conn->real_escape_string($_SESSION['employee_id']) . "',
                         " . $cid . ",
                         NOW(),
                         0
                     )";
        $conn->query($insertSql);
        
        // Delete tags
        $conn->query("DELETE FROM tagtable WHERE customerId = " . $cid);
        
        // 发送消息给原业务员
        if ($originalId > 0) {
            // 获取客户名称
            $customerSql = "SELECT cs_code FROM customer WHERE id = " . $cid;
            $customerResult = $conn->query($customerSql);
            $customerRow = $customerResult->fetch_assoc();
            $customerName = $customerRow ? $customerRow['cs_code'] : '客户';
            
            // 构建消息内容
            $messageTitle = "客户被认领通知";
            $messageContent = "您的客户 {$customerName}(原编码:{$oldCode})已被 {$_SESSION['employee_name']} 认领。\n";
            $messageContent=textDecode($messageContent);
            $messageContent .= "认领时间:" . date('Y-m-d H:i:s') . "\n";
            $messageContent .= "新客户编号:{$newCode}\n";
            
            // 发送消息
            sendMessage(
                $messageTitle,
                $messageContent,
                2,  // 客户相关
                0,  // 个人消息
                $originalId,  // 原业务员ID
                1   // 重要
            );
        }
        
        echo "1";
    }
}
?>