<?php
/**
 * 채팅 로그 API
 * 채팅 로그 저장, 불러오기 및 오프라인 채팅 업로드 기능을 처리합니다.
 */

// 크로스 도메인 요청 허용
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json; charset=UTF-8");

// OPTIONS 요청 처리 (CORS 프리플라이트)
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// 요청 메소드 확인
$method = $_SERVER['REQUEST_METHOD'];

// 요청 경로 파싱 (URL에서 'action' 파라미터 사용)
$action = isset($_GET['action']) ? $_GET['action'] : '';

// action이 비어있으면 URL 경로에서 추출 시도
if (empty($action)) {
    $requestUri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
    if (strpos($requestUri, '/saveChatLog') !== false) {
        $action = 'saveChatLog';
    } elseif (strpos($requestUri, '/loadChatLog') !== false) {
        $action = 'loadChatLog';
    } elseif (strpos($requestUri, '/uploadOfflineChats') !== false) {
        $action = 'uploadOfflineChats';
    }
}

// 기본 응답 설정
$response = [
    'success' => false,
    'message' => '알 수 없는 요청입니다.'
];

// 액션에 따른 처리
switch ($action) {
    case 'saveChatLog':
        if ($method === 'POST') {
            $response = saveChatLog();
        } else {
            $response['message'] = 'POST 요청이 필요합니다.';
        }
        break;
        
    case 'loadChatLog':
        if ($method === 'GET') {
            loadChatLog();
            exit; // 직접 응답을 생성하므로 추가 처리 방지
        } else {
            $response['message'] = 'GET 요청이 필요합니다.';
        }
        break;
        
    case 'uploadOfflineChats':
        if ($method === 'POST') {
            $response = uploadOfflineChats();
        } else {
            $response['message'] = 'POST 요청이 필요합니다.';
        }
        break;
        
    default:
        $response['message'] = '지원하지 않는 액션입니다.';
        break;
}

// JSON 응답 전송
echo json_encode($response);

/**
 * 채팅 로그를 파일에 저장
 * 
 * @return array 응답 배열
 */
function saveChatLog() {
    // POST 데이터 받기
    $postData = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($postData['logData']) || !isset($postData['logPath'])) {
        return [
            'success' => false,
            'message' => '필수 데이터가 누락되었습니다.'
        ];
    }
    
    $logData = $postData['logData'];
    $logPath = validateAndSanitizePath($postData['logPath']);
    
    if ($logPath === false) {
        return [
            'success' => false,
            'message' => '유효하지 않은 로그 경로입니다.'
        ];
    }
    
    // 디렉토리 확인 및 생성
    $logDir = dirname($logPath);
    if (!is_dir($logDir)) {
        if (!mkdir($logDir, 0755, true)) {
            return [
                'success' => false,
                'message' => '로그 디렉토리를 생성할 수 없습니다.'
            ];
        }
    }
    
    // 파일에 로그 추가
    if (file_put_contents($logPath, $logData, FILE_APPEND | LOCK_EX) === false) {
        return [
            'success' => false,
            'message' => '로그 파일에 쓰기 실패했습니다.'
        ];
    }
    
    return [
        'success' => true,
        'message' => '채팅 로그가 저장되었습니다.'
    ];
}

/**
 * 채팅 로그 파일 불러오기
 */
function loadChatLog() {
    // GET 파라미터 검증
    if (!isset($_GET['logPath'])) {
        header('Content-Type: text/plain; charset=UTF-8');
        echo "로그 경로가 지정되지 않았습니다.";
        return;
    }
    
    $logPath = validateAndSanitizePath($_GET['logPath']);
    
    if ($logPath === false) {
        header('Content-Type: text/plain; charset=UTF-8');
        echo "유효하지 않은 로그 경로입니다.";
        return;
    }
    
    // 디렉토리 확인 및 생성 (로그 파일 불러오기 전에도 디렉토리 확인)
    $logDir = dirname($logPath);
    if (!is_dir($logDir)) {
        // 디렉토리가 없으면 생성 시도
        if (mkdir($logDir, 0755, true)) {
            // 새 파일 생성 (빈 파일)
            file_put_contents($logPath, '');
        }
    }
    
    // 파일 존재 확인
    if (!file_exists($logPath)) {
        header('Content-Type: text/plain; charset=UTF-8');
        echo ""; // 파일이 없으면 빈 문자열 반환
        return;
    }
    
    // 파일 내용 읽기
    $content = file_get_contents($logPath);
    
    if ($content === false) {
        header('Content-Type: text/plain; charset=UTF-8');
        echo "로그 파일을 읽을 수 없습니다.";
        return;
    }
    
    // 텍스트 형식으로 응답
    header('Content-Type: text/plain; charset=UTF-8');
    echo $content;
}

/**
 * 오프라인에서 저장된 채팅 로그를 업로드
 * 
 * @return array 응답 배열
 */
function uploadOfflineChats() {
    // POST 데이터 받기
    $postData = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($postData['logData']) || !isset($postData['logPath'])) {
        return [
            'success' => false,
            'message' => '필수 데이터가 누락되었습니다.'
        ];
    }
    
    $logData = $postData['logData'];
    $logPath = validateAndSanitizePath($postData['logPath']);
    
    if ($logPath === false) {
        return [
            'success' => false,
            'message' => '유효하지 않은 로그 경로입니다.'
        ];
    }
    
    // 디렉토리 확인 및 생성
    $logDir = dirname($logPath);
    if (!is_dir($logDir)) {
        if (!mkdir($logDir, 0755, true)) {
            return [
                'success' => false,
                'message' => '로그 디렉토리를 생성할 수 없습니다.'
            ];
        }
    }
    
    // 파일에 로그 추가
    if (file_put_contents($logPath, $logData, FILE_APPEND | LOCK_EX) === false) {
        return [
            'success' => false,
            'message' => '로그 파일에 쓰기 실패했습니다.'
        ];
    }
    
    return [
        'success' => true,
        'message' => '오프라인 채팅 로그가 업로드되었습니다.'
    ];
}

/**
 * 로그 파일 경로 검증 및 정제
 * 
 * @param string $path 검증할 경로
 * @return string|false 정제된 경로 또는 오류시 false
 */
function validateAndSanitizePath($path) {
    // 상대 경로인 경우 절대 경로로 변환
    if (!realpath($path)) {
        // 상위 디렉토리 이동 방지
        if (strpos($path, '..') !== false) {
            return false;
        }
        
        // js/chatLog/ 디렉토리 내에 있는지 확인
        if (strpos($path, 'js/chatLog/') !== 0 && strpos($path, '/js/chatLog/') !== 0) {
            // 지정된 디렉토리 안에 있도록 강제
            $path = 'js/chatLog/' . basename($path);
        }
        
        // 현재 스크립트 실행 디렉토리 기준으로 경로 생성
        $basePath = dirname(dirname(dirname(__FILE__))); // 현재 파일(chatLogApi.php)의 상위 3단계 디렉토리
        $path = $basePath . '/' . ltrim($path, '/');
    }
    
    return $path;
} 