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

header('Content-Type: application/json');

// 验证必要的字段
if (
    !isset($_POST['source_customer_id']) || !is_numeric($_POST['source_customer_id']) ||
    !isset($_POST['target_customer_id']) || !is_numeric($_POST['target_customer_id']) ||
    !isset($_POST['relationship_type']) || !is_numeric($_POST['relationship_type'])
) {
    echo json_encode(['success' => false, 'message' => '参数错误']);
    exit;
}

$sourceId = intval($_POST['source_customer_id']);
$targetId = intval($_POST['target_customer_id']);
$relationType = intval($_POST['relationship_type']);
$relationStatus = isset($_POST['relationship_status']) ? intval($_POST['relationship_status']) : 1;
$description = isset($_POST['description']) ? mysqli_real_escape_string($conn, $_POST['description']) : '';
$id = isset($_POST['id']) && !empty($_POST['id']) ? intval($_POST['id']) : null;
$employeeId = $_SESSION['employee_id'];

$isAdmin = checkIfAdmin();

// 验证权限
if (!$isAdmin) {
    // 检查当前用户是否是源客户的负责人
    $customerSql = "SELECT id FROM customer WHERE id = $sourceId AND cs_belong = $employeeId";
    $customerResult = mysqli_query($conn, $customerSql);
    
    if (mysqli_num_rows($customerResult) == 0) {
        echo json_encode(['success' => false, 'message' => '您没有权限操作此客户关系']);
        exit;
    }
    
    // 如果是编辑,还需要验证是否有权限修改
    if ($id) {
        $checkSql = "SELECT source_customer_id FROM customer_relationship WHERE id = $id";
        $checkResult = mysqli_query($conn, $checkSql);
        
        if ($checkRow = mysqli_fetch_assoc($checkResult)) {
            $existingSourceId = $checkRow['source_customer_id'];
            
            // 检查现有关系的源客户是否是当前用户负责的
            if ($existingSourceId != $sourceId) {
                $sourceCheckSql = "SELECT id FROM customer WHERE id = $existingSourceId AND cs_belong = $employeeId";
                $sourceResult = mysqli_query($conn, $sourceCheckSql);
                
                if (mysqli_num_rows($sourceResult) == 0) {
                    echo json_encode(['success' => false, 'message' => '您没有权限修改此客户关系']);
                    exit;
                }
            }
        }
    }
}

// 检查源客户和目标客户是否相同
if ($sourceId == $targetId) {
    echo json_encode(['success' => false, 'message' => '源客户和目标客户不能是同一个']);
    exit;
}

// 检查是否已存在相同的关系
$checkDuplicateSql = "SELECT id FROM customer_relationship WHERE 
                      ((source_customer_id = $sourceId AND target_customer_id = $targetId) OR 
                       (source_customer_id = $targetId AND target_customer_id = $sourceId))";

// 如果是编辑模式,需要排除当前记录
if ($id) {
    $checkDuplicateSql .= " AND id != $id";
}

$duplicateResult = mysqli_query($conn, $checkDuplicateSql);

if (mysqli_num_rows($duplicateResult) > 0) {
    echo json_encode(['success' => false, 'message' => '已存在相同的客户关系']);
    exit;
}

// 创建或更新关系
if ($id) {
    // 更新现有关系
    $sql = "UPDATE customer_relationship SET 
            source_customer_id = $sourceId,
            target_customer_id = $targetId,
            relationship_type = $relationType,
            relationship_status = $relationStatus,
            description = '$description',
            updated_at = NOW()
            WHERE id = $id";
} else {
    // 创建新关系
    $sql = "INSERT INTO customer_relationship 
            (source_customer_id, target_customer_id, relationship_type, relationship_status, description, employee_id, created_at, updated_at) 
            VALUES ($sourceId, $targetId, $relationType, $relationStatus, '$description', $employeeId, NOW(), NOW())";
}

$result = mysqli_query($conn, $sql);

if ($result) {
    $relationId = $id ?: mysqli_insert_id($conn);
    echo json_encode(['success' => true, 'id' => $relationId, 'message' => '保存成功']);
} else {
    echo json_encode(['success' => false, 'message' => '保存失败: ' . mysqli_error($conn)]);
}
?>