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

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

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    echo json_encode(['success' => false, 'message' => '参数错误']);
    exit;
}

$id = intval($_GET['id']);

// 获取关系详情
$sql = "SELECT cr.*, 
        c1.cs_company as source_company, c1.cs_code as source_code,
        c2.cs_company as target_company, c2.cs_code as target_code
        FROM customer_relationship cr
        LEFT JOIN customer c1 ON cr.source_customer_id = c1.id
        LEFT JOIN customer c2 ON cr.target_customer_id = c2.id
        WHERE cr.id = $id";

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

if ($row = mysqli_fetch_assoc($result)) {
    // 检查权限:如果不是管理员,只能查看自己能操作的客户
    $isAdmin = checkIfAdmin();
    if (!$isAdmin) {
        // 检查当前用户是否是源客户或目标客户的负责人
        $sourceId = $row['source_customer_id'];
        $targetId = $row['target_customer_id'];
        $employeeId = $_SESSION['employee_id'];
        
        $customerSql = "SELECT id FROM customer WHERE (id = $sourceId OR id = $targetId) AND cs_belong = $employeeId";
        $customerResult = mysqli_query($conn, $customerSql);
        
        if (mysqli_num_rows($customerResult) == 0) {
            echo json_encode(['success' => false, 'message' => '您没有权限查看此客户关系']);
            exit;
        }
    }
    
    // 准备返回数据
    $row['source_company'] = textUncode($row['source_company']);
    $row['source_code'] = textUncode($row['source_code']);
    $row['target_company'] = textUncode($row['target_company']);
    $row['target_code'] = textUncode($row['target_code']);
    $row['description'] = textUncode($row['description']);
    
    echo json_encode(['success' => true, 'relationship' => $row]);
} else {
    echo json_encode(['success' => false, 'message' => '未找到客户关系']);
}
?>