<?php
/**
 * 채팅 로그 API
 * 채팅 로그 저장, 불러오기 및 관리 기능을 처리합니다.
 */

// 오류 로깅 활성화
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 크로스 도메인 요청 허용
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'];
$action = isset($_GET['action']) ? $_GET['action'] : '';

// 디버그 로그
$debugLogFile = __DIR__ . '/debug.log';
file_put_contents($debugLogFile, date('Y-m-d H:i:s') . " - 요청: {$method} {$action}\n", FILE_APPEND);

// 기본 응답 설정
$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;
        
    default:
        $response['message'] = '지원하지 않는 액션입니다: ' . $action;
        break;
}

// JSON 응답 전송
echo json_encode($response);

/**
 * 채팅 로그를 파일에 저장
 * 
 * @return array 응답 배열
 */
function saveChatLog() {
    global $debugLogFile;
    file_put_contents($debugLogFile, date('Y-m-d H:i:s') . " - saveChatLog 시작\n", FILE_APPEND);
    
    // POST 데이터 받기
    $postData = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($postData['logData']) || !isset($postData['logPath'])) {
        file_put_contents($debugLogFile, date('Y-m-d H:i:s') . " - 필수 데이터 누락\n", FILE_APPEND);
        return [
            'success' => false,
            'message' => '필수 데이터가 누락되었습니다.'
        ];
    }
    
    $logData = $postData['logData'];
    file_put_contents($debugLogFile, date('Y-m-d H:i:s') . " - 로그 데이터: " . substr($logData, 0, 50) . "...\n", FILE_APPEND);
    
    $requestedPath = $postData['logPath'];
    file_put_contents($debugLogFile, date('Y-m-d H:i:s') . " - 요청된 경로: {$requestedPath}\n", FILE_APPEND);
    
    // 항상 고정된 경로 사용 (보안 향상)
    $logPath = __DIR__ . '/chatLog.txt';
    file_put_contents($debugLogFile, date('Y-m-d H:i:s') . " - 실제 저장 경로: {$logPath}\n", FILE_APPEND);
    
    // 디렉토리 확인 및 생성
    $logDir = dirname($logPath);
    if (!is_dir($logDir)) {
        file_put_contents($debugLogFile, date('Y-m-d H:i:s') . " - 디렉토리 생성 시도: {$logDir}\n", FILE_APPEND);
        if (!mkdir($logDir, 0755, true)) {
            file_put_contents($debugLogFile, date('Y-m-d H:i:s') . " - 디렉토리 생성 실패\n", FILE_APPEND);
            return [
                'success' => false,
                'message' => '로그 디렉토리를 생성할 수 없습니다.'
            ];
        }
    }
    
    // 파일에 로그 추가
    $result = file_put_contents($logPath, $logData, FILE_APPEND | LOCK_EX);
    file_put_contents($debugLogFile, date('Y-m-d H:i:s') . " - 파일 쓰기 결과: " . ($result === false ? "실패" : "{$result} 바이트") . "\n", FILE_APPEND);
    
    if ($result === false) {
        return [
            'success' => false,
            'message' => '로그 파일에 쓰기 실패했습니다.'
        ];
    }
    
    return [
        'success' => true,
        'message' => '채팅 로그가 저장되었습니다.',
        'bytes' => $result
    ];
}

/**
 * 채팅 로그 파일 불러오기
 */
function loadChatLog() {
    global $debugLogFile;
    file_put_contents($debugLogFile, date('Y-m-d H:i:s') . " - loadChatLog 시작\n", FILE_APPEND);
    
    // 요청된 경로 로깅
    $requestedPath = isset($_GET['logPath']) ? $_GET['logPath'] : 'not specified';
    file_put_contents($debugLogFile, date('Y-m-d H:i:s') . " - 요청된 경로: {$requestedPath}\n", FILE_APPEND);
    
    // 항상 고정된 경로 사용 (보안 향상)
    $logPath = __DIR__ . '/chatLog.txt';
    file_put_contents($debugLogFile, date('Y-m-d H:i:s') . " - 실제 로드 경로: {$logPath}\n", FILE_APPEND);
    
    // 파일 존재 확인
    if (!file_exists($logPath)) {
        file_put_contents($debugLogFile, date('Y-m-d H:i:s') . " - 파일이 존재하지 않아 생성 시도\n", FILE_APPEND);
        // 파일이 없으면 빈 파일 생성
        if (file_put_contents($logPath, '') === false) {
            file_put_contents($debugLogFile, date('Y-m-d H:i:s') . " - 빈 파일 생성 실패\n", FILE_APPEND);
            header('Content-Type: text/plain; charset=UTF-8');
            echo "로그 파일을 생성할 수 없습니다.";
            return;
        }
        file_put_contents($debugLogFile, date('Y-m-d H:i:s') . " - 빈 파일 생성 성공\n", FILE_APPEND);
    }
    
    // 파일 내용 읽기
    file_put_contents($debugLogFile, date('Y-m-d H:i:s') . " - 파일 읽기 시도\n", FILE_APPEND);
    $content = file_get_contents($logPath);
    
    if ($content === false) {
        file_put_contents($debugLogFile, date('Y-m-d H:i:s') . " - 파일 읽기 실패\n", FILE_APPEND);
        header('Content-Type: text/plain; charset=UTF-8');
        echo "로그 파일을 읽을 수 없습니다.";
        return;
    }
    
    file_put_contents($debugLogFile, date('Y-m-d H:i:s') . " - 파일 읽기 성공: " . strlen($content) . " 바이트\n", FILE_APPEND);
    
    // 텍스트 형식으로 응답
    header('Content-Type: text/plain; charset=UTF-8');
    echo $content;
} 