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

// 获取操作类型
$act = $_GET['act'] ?? '';

// 获取表单数据
$id = isset($_POST['id']) ? intval($_POST['id']) : (isset($_GET['id']) ? intval($_GET['id']) : 0);
$source_customer_id = isset($_POST['source_customer_id']) ? intval($_POST['source_customer_id']) : 0;
$target_customer_id = isset($_POST['target_customer_id']) ? intval($_POST['target_customer_id']) : 0;
$relationship_type = isset($_POST['relationship_type']) ? intval($_POST['relationship_type']) : 0;
$relationship_status = isset($_POST['relationship_status']) ? intval($_POST['relationship_status']) : 1;
$description = isset($_POST['description']) ? textEncode($_POST['description']) : '';

// 当前员工ID
$employee_id = $_SESSION['employee_id'];
$isAdmin = checkIfAdmin();

// 删除操作
if ($act == 'delete' && $id > 0) {
    // 验证关系记录是否存在
    $checkQuery = "SELECT * FROM customer_relationship WHERE id = $id";
    $result = $conn->query($checkQuery);
    
    if ($result->num_rows == 0) {
        echo "<script>alert('未找到指定的客户关系记录!'); window.location.href='relationships.php';</script>";
        exit;
    }
    
    // 检查权限:如果不是管理员,只能删除自己创建的关系
    $row = $result->fetch_assoc();
    if (!$isAdmin && $row['employee_id'] != $_SESSION['employee_id']) {
        echo "<script>alert('您没有权限删除此客户关系记录!'); window.location.href='relationships.php';</script>";
        exit;
    }
    
    // 记录删除操作到日志
    $source_company_query = "SELECT cs_company FROM customer WHERE id = ".$row['source_customer_id'];
    $target_company_query = "SELECT cs_company FROM customer WHERE id = ".$row['target_customer_id'];
    
    $source_result = $conn->query($source_company_query);
    $source_company = '';
    if ($source_row = $source_result->fetch_assoc()) {
        $source_company = textDecode($source_row['cs_company']);
    }
    
    $target_result = $conn->query($target_company_query);
    $target_company = '';
    if ($target_row = $target_result->fetch_assoc()) {
        $target_company = textDecode($target_row['cs_company']);
    }
    
    $log_message = $_SESSION['employee_name'] . " 删除了客户关系记录:" . 
                   $source_company . " 和 " . $target_company . " 之间的关系";
    
    logAction($log_message);
    
    // 执行删除操作
    $deleteQuery = "DELETE FROM customer_relationship WHERE id = $id";
    $conn->query($deleteQuery);
    
    echo "<script>alert('客户关系记录已成功删除!'); window.location.href='relationships.php';</script>";
    exit;
}

// 表单数据验证
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // 验证源客户和目标客户
    if ($source_customer_id <= 0 || $target_customer_id <= 0) {
        echo "<script>alert('请选择有效的源客户和目标客户!'); history.back();</script>";
        exit;
    }
    
    if ($source_customer_id == $target_customer_id) {
        echo "<script>alert('源客户和目标客户不能是同一个客户!'); history.back();</script>";
        exit;
    }
    
    // 验证关系类型
    if ($relationship_type <= 0 || $relationship_type > 6) {
        echo "<script>alert('请选择有效的关系类型!'); history.back();</script>";
        exit;
    }
    
    // 检查相同的关系是否已存在
    $checkDuplicateQuery = "SELECT * FROM customer_relationship 
                           WHERE source_customer_id = $source_customer_id 
                           AND target_customer_id = $target_customer_id 
                           AND relationship_type = $relationship_type";
    
    if ($id > 0) {
        $checkDuplicateQuery .= " AND id != $id";
    }
    
    $result = $conn->query($checkDuplicateQuery);
    
    if ($result->num_rows > 0) {
        echo "<script>alert('相同的客户关系记录已存在!'); history.back();</script>";
        exit;
    }
    
    // 如果是编辑操作,检查权限
    if ($id > 0) {
        $checkPermissionQuery = "SELECT * FROM customer_relationship WHERE id = $id";
        $permResult = $conn->query($checkPermissionQuery);
        
        if ($permResult->num_rows > 0) {
            $permRow = $permResult->fetch_assoc();
            if (!$isAdmin && $permRow['employee_id'] != $_SESSION['employee_id']) {
                echo "<script>alert('您没有权限编辑此客户关系记录!'); window.location.href='relationships.php';</script>";
                exit;
            }
        }
    }
    
    // 根据是否有ID决定是更新还是新增
    if ($id > 0) {
        // 更新操作
        $updateQuery = "UPDATE customer_relationship SET 
                        source_customer_id = $source_customer_id,
                        target_customer_id = $target_customer_id,
                        relationship_type = $relationship_type,
                        relationship_status = $relationship_status,
                        description = '$description',
                        updated_by = $employee_id,
                        updated_at = NOW()
                        WHERE id = $id";
        
        if ($conn->query($updateQuery)) {
            // 获取源客户和目标客户名称
            $source_company_query = "SELECT cs_company FROM customer WHERE id = $source_customer_id";
            $target_company_query = "SELECT cs_company FROM customer WHERE id = $target_customer_id";
            
            $source_result = $conn->query($source_company_query);
            $source_company = '';
            if ($source_row = $source_result->fetch_assoc()) {
                $source_company = textDecode($source_row['cs_company']);
            }
            
            $target_result = $conn->query($target_company_query);
            $target_company = '';
            if ($target_row = $target_result->fetch_assoc()) {
                $target_company = textDecode($target_row['cs_company']);
            }
            
            // 记录日志
            $log_message = $_SESSION['employee_name'] . " 更新了客户关系记录:" . 
                          $source_company . " 和 " . $target_company . " 之间的关系";
            
            logAction($log_message);
            
            echo "<script>alert('客户关系记录已成功更新!'); window.location.href='relationships.php';</script>";
        } else {
            echo "<script>alert('更新客户关系记录失败:" . $conn->error . "'); history.back();</script>";
        }
    } else {
        // 新增操作
        $insertQuery = "INSERT INTO customer_relationship 
                        (source_customer_id, target_customer_id, relationship_type, relationship_status, 
                         description, employee_id, updated_by, created_at, updated_at)
                        VALUES ($source_customer_id, $target_customer_id, $relationship_type, $relationship_status, 
                         '$description', $employee_id, $employee_id, NOW(), NOW())";
        
        if ($conn->query($insertQuery)) {
            // 获取源客户和目标客户名称
            $source_company_query = "SELECT cs_company FROM customer WHERE id = $source_customer_id";
            $target_company_query = "SELECT cs_company FROM customer WHERE id = $target_customer_id";
            
            $source_result = $conn->query($source_company_query);
            $source_company = '';
            if ($source_row = $source_result->fetch_assoc()) {
                $source_company = textDecode($source_row['cs_company']);
            }
            
            $target_result = $conn->query($target_company_query);
            $target_company = '';
            if ($target_row = $target_result->fetch_assoc()) {
                $target_company = textDecode($target_row['cs_company']);
            }
            
            // 记录日志
            $log_message = $_SESSION['employee_name'] . " 新增了客户关系记录:" . 
                          $source_company . " 和 " . $target_company . " 之间的关系";
            
            logAction($log_message);
            
            echo "<script>alert('客户关系记录已成功添加!'); window.location.href='relationships.php';</script>";
        } else {
            echo "<script>alert('添加客户关系记录失败:" . $conn->error . "'); history.back();</script>";
        }
    }
} else {
    echo "<script>alert('无效的请求!'); window.location.href='relationships.php';</script>";
}
?>