<?php
// Function to log case saves with full metadata
function logCaseSave($userId, $username, $email, $grade, $score, $status, $errorType = null, $errorMsg = null, $insertId = null, $caseName = null) {
    $timestamp = date('Y-m-d H:i:s');
    $userIP = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
    if (strpos($userIP, ',') !== false) {
        $userIP = trim(explode(',', $userIP)[0]);
    }
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
    
    // Create logs directory structure if it doesn't exist
    $logsDir = ROOT_PATH . '/logs';
    $saveLogsDir = $logsDir . '/save_logs';
    
    if (!is_dir($logsDir)) {
        mkdir($logsDir, 0755, true);
    }
    if (!is_dir($saveLogsDir)) {
        mkdir($saveLogsDir, 0755, true);
    }
    
    // Generate weekly log filename: saves_log_2025_W44.txt
    $year = date('Y');
    $week = date('W');
    $logFileName = "saves_log_{$year}_W{$week}.txt";
    $logFilePath = $saveLogsDir . '/' . $logFileName;
    
    $logEntry = "\n" . str_repeat("=", 80) . "\n";
    $logEntry .= "TIMESTAMP: " . $timestamp . "\n";
    $logEntry .= "STATUS: " . $status . "\n";
    $logEntry .= "USER_ID: " . $userId . "\n";
    $logEntry .= "USERNAME: " . $username . "\n";
    $logEntry .= "EMAIL: " . $email . "\n";
    $logEntry .= "CASE_GRADE: " . $grade . "\n";
    $logEntry .= "CASE_SCORE: " . $score . "\n";
    $logEntry .= "IP_ADDRESS: " . $userIP . "\n";
    $logEntry .= "USER_AGENT: " . $userAgent . "\n";
    
    if ($caseName) {
        $logEntry .= "CASE_NAME: " . $caseName . "\n";
    }
    
    if ($status === 'SUCCESS' && $insertId) {
        $logEntry .= "INSERT_ID: " . $insertId . "\n";
        $logEntry .= "DATABASE_RECORD: Successfully inserted into wp_groupusers_data\n";
    }
    
    if ($errorType) {
        $logEntry .= "ERROR_TYPE: " . $errorType . "\n";
    }
    if ($errorMsg) {
        $logEntry .= "ERROR_MESSAGE: " . $errorMsg . "\n";
    }
    
    $logEntry .= str_repeat("=", 80) . "\n";
    
    error_log($logEntry, 3, $logFilePath);
}
?>
