<?php
include($_SERVER['DOCUMENT_ROOT'] . '/includes/include_all.inc.php');
include($_SERVER['DOCUMENT_ROOT'] . '/includes/save_logging.php');
include($_SERVER['DOCUMENT_ROOT'] . '/includes/debug_mode.php');

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

$userIP = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
$userId = $_SESSION['front_user_id'] ?? null;

// Only log detailed debugging if debug mode is enabled
if (isDebugModeEnabled()) {
    logMessage2("=== CASE SAVE ATTEMPT STARTED ===");
    logMessage2("User ID: " . ($userId ?? 'NOT SET'));
    logMessage2("IP Address: " . $userIP);
    logMessage2("User Agent: " . $userAgent);
    logMessage2("Request Method: " . $_SERVER['REQUEST_METHOD']);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    if (isDebugModeEnabled()) {
        logMessage2("ERROR: Invalid request method - " . $_SERVER['REQUEST_METHOD']);
    }
    $_SESSION['flash_message'] = ['type' => 'error', 'message' => 'Invalid request method.'];
    echo json_encode(["success" => false, "errorType" => "INVALID_METHOD", "message" => "Invalid request method."]);
    exit();
}

$inputData = file_get_contents("php://input");
if (isDebugModeEnabled()) {
    logMessage2("Raw POST data length: " . strlen($inputData) . " bytes");
}

$data = json_decode($inputData, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    $jsonError = json_last_error_msg();
    if (isDebugModeEnabled()) {
        logMessage2("ERROR: JSON decode failed - " . $jsonError);
    }
    $_SESSION['flash_message'] = ['type' => 'error', 'message' => 'Invalid data format.'];
    echo json_encode(["success" => false, "errorType" => "INVALID_JSON", "message" => "Invalid data format."]);
    exit();
}

if (empty($data)) {
    if (isDebugModeEnabled()) {
        logMessage2("ERROR: Empty data received");
    }
    $_SESSION['flash_message'] = ['type' => 'error', 'message' => 'No data provided.'];
    echo json_encode(["success" => false, "errorType" => "NO_DATA", "message" => "No data provided."]);
    exit();
}

if (!isset($_SESSION['front_user_id'])) {
    if (isDebugModeEnabled()) {
        logMessage2("ERROR: User session not found");
    }
    
    $caseGrade = isset($data['grade']) ? $data['grade'] : 'Unknown';
    $caseLog = isset($data['caseLog']) ? $data['caseLog'] : '';
    
    // Use client-provided score and time if available (for session expired cases)
    $caseScore = isset($data['clientCaseScore']) ? $data['clientCaseScore'] : '';
    if (empty($caseScore)) {
        preg_match('/(-?\d+\s*\/\s*\d+)/', $caseLog, $scoreMatches);
        $caseScore = isset($scoreMatches[0]) ? $scoreMatches[0] : '';
    }
    $caseTime = isset($data['clientCaseTime']) ? $data['clientCaseTime'] : '';
    
    // fetch the real user info from the hidden fields
    $clientUserId = isset($data['clientUserId']) ? $data['clientUserId'] : null;
    $clientFirstName = isset($data['clientUserFirstName']) ? $data['clientUserFirstName'] : '';
    $clientLastName = isset($data['clientUserLastName']) ? $data['clientUserLastName'] : '';
    $clientUserName = trim($clientFirstName . ' ' . $clientLastName);
    if (empty($clientUserName)) $clientUserName = 'Unknown';
    $clientUserEmail = isset($data['clientUserEmail']) ? $data['clientUserEmail'] : 'Unknown';
    
    $caseTime = isset($data['clientCaseTime']) ? $data['clientCaseTime'] : '';
    $caseName = isset($data['clientCaseName']) ? $data['clientCaseName'] : 'Unknown Case';
    $errorDetails = 'User session not found' . ($caseTime ? ' | Case time: ' . $caseTime : '');
    logCaseSaveDebug($clientUserId, $clientUserName, $clientUserEmail, $caseGrade, $caseScore, 'FAILED', 'SESSION_EXPIRED', $errorDetails, null, $caseName);
    $_SESSION['flash_message'] = ['type' => 'error', 'message' => 'Your session has expired. Please log in again and retry saving. If needed, open the case log, copy all text and save in a txt file or Word doc. Contact jill@website.com'];
    echo json_encode(["success" => false, "errorType" => "SESSION_EXPIRED", "message" => "User session expired."]);
    exit();
}

$username = 'Unknown';
$userEmail = 'Unknown';
try {
    $stmtUser = $pdo->prepare("SELECT user_login, user_email FROM wp_users WHERE ID = :user_id");
    $stmtUser->bindParam(':user_id', $userId, PDO::PARAM_INT);
    $stmtUser->execute();
    $userInfo = $stmtUser->fetch(PDO::FETCH_ASSOC);
    if ($userInfo) {
        $username = $userInfo['user_login'];
        $userEmail = $userInfo['user_email'];
    }
} catch (Exception $e) {
    if (isDebugModeEnabled()) {
        logMessage2("Could not fetch user details: " . $e->getMessage());
    }
}

// Override with client data if available
if (isset($data['clientUserId']) && !empty($data['clientUserId'])) {
    $userId = $data['clientUserId'];
}
if (isset($data['clientUserFirstName']) && isset($data['clientUserLastName'])) {
    $clientName = trim($data['clientUserFirstName'] . ' ' . $data['clientUserLastName']);
    if (!empty($clientName)) {
        $username = $clientName;
    }
}
if (isset($data['clientUserEmail']) && !empty($data['clientUserEmail'])) {
    $userEmail = $data['clientUserEmail'];
}

$caseLog = isset($data['caseLog']) ? $data['caseLog'] : '';
$caseGrade = isset($data['grade']) ? $data['grade'] : 'Unknown';
$instructorNotes = isset($data['instructor_notes']) ? $data['instructor_notes'] : null;

if (isDebugModeEnabled()) {
    logMessage2("Case log length: " . strlen($caseLog) . " characters");
    logMessage2("Case grade: " . $caseGrade);
}

if (empty($caseLog)) {
    if (isDebugModeEnabled()) {
        logMessage2("ERROR: Empty case log provided");
    }
    $errorDetails = 'Empty case log' . ($caseTime ? ' | Case time: ' . $caseTime : '');
    logCaseSaveDebug($userId, $username, $userEmail, $caseGrade, '', 'FAILED', 'VALIDATION_ERROR', $errorDetails, null, $caseName);
    $_SESSION['flash_message'] = ['type' => 'error', 'message' => 'Invalid data detected in case log. Please review your entries and try again. If you need assistance, open the case log, copy all text and save in a txt file or Word doc. Contact jill@website.com'];
    echo json_encode(["success" => false, "errorType" => "VALIDATION_ERROR", "message" => "Case log cannot be empty."]);
    exit();
}

preg_match('/(-?\d+\s*\/\s*\d+)/', $caseLog, $scoreMatches);
$caseScore = isset($scoreMatches[0]) ? $scoreMatches[0] : '';

// Override with client data if available
if (isset($data['clientCaseScore']) && !empty($data['clientCaseScore'])) {
    $caseScore = $data['clientCaseScore'];
}
$caseTime = isset($data['clientCaseTime']) ? $data['clientCaseTime'] : '';
$caseName = isset($data['clientCaseName']) ? $data['clientCaseName'] : 'Unknown Case';

if (isDebugModeEnabled()) {
    logMessage2("Extracted score: " . ($caseScore ? $caseScore : "None found"));
}

try {
    if (isDebugModeEnabled()) {
        logMessage2("Attempting database connection...");
    }
    
    if (!isset($pdo)) {
        $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    
    // Test mode: force database error
    if (isset($data['forceError']) && $data['forceError'] === true) {
        throw new PDOException("Test error: Simulated database failure");
    }
    
    if (isDebugModeEnabled()) {
        logMessage2("Database connection successful");
        logMessage2("Preparing SQL statement...");
    }
    
    $stmt = $pdo->prepare("
        INSERT INTO wp_groupusers_data 
        (user_id, user_data, case_grade, case_score, datetime, instructor_notes) 
        VALUES (:user_id, :case_log, :case_grade, :case_score, NOW(), :instructor_notes)
    ");
    
    $stmt->bindParam(':user_id', $userId, PDO::PARAM_INT);
    $stmt->bindParam(':case_log', $caseLog, PDO::PARAM_STR);
    $stmt->bindParam(':case_grade', $caseGrade, PDO::PARAM_STR);
    $stmt->bindParam(':case_score', $caseScore, PDO::PARAM_STR);
    $stmt->bindParam(':instructor_notes', $instructorNotes, PDO::PARAM_STR);
    
    if (isDebugModeEnabled()) {
        logMessage2("Executing insert query...");
    }
    $stmt->execute();
    
    $insertedId = $pdo->lastInsertId();
    if (isDebugModeEnabled()) {
        logMessage2("SUCCESS: Case saved with ID: " . $insertedId);
        logMessage2("=== CASE SAVE COMPLETED SUCCESSFULLY ===");
    }
    
    $successDetails = 'Case time: ' . $caseTime;
    logCaseSaveDebug($userId, $username, $userEmail, $caseGrade, $caseScore, 'SUCCESS', null, $successDetails, $insertedId, $caseName);
    
    $_SESSION['flash_message'] = ['type' => 'success', 'message' => 'Case log saved successfully.'];
    
    echo json_encode(["success" => true, "message" => "Case log saved successfully.", "insertId" => $insertedId]);

} catch (PDOException $e) {
    $errorMsg = $e->getMessage();
    $errorCode = $e->getCode();
    
    if (isDebugModeEnabled()) {
        logMessage2("ERROR: PDO Exception occurred");
        logMessage2("Error Code: " . $errorCode);
        logMessage2("Error Message: " . $errorMsg);
    }
    
    $errorType = "DATABASE_ERROR";
    $userMessage = "Database temporarily unavailable. Please try again in a few minutes. If the problem continues, open the case log, copy all text and save in a txt file or Word doc. Contact jill@website.com";
    
    if (strpos($errorMsg, 'Connection') !== false || strpos($errorMsg, 'connect') !== false) {
        $errorType = "CONNECTION_ERROR";
        $userMessage = "Unable to communicate with server. Please try saving again in a few moments. If unsuccessful, open the case log, copy all text and save in a txt file or Word doc. Contact jill@website.com";
        if (isDebugModeEnabled()) {
            logMessage2("Categorized as: Connection Error");
        }
    } elseif (strpos($errorMsg, 'Duplicate') !== false) {
        $errorType = "DUPLICATE_ERROR";
        $userMessage = "This case was already saved.";
        if (isDebugModeEnabled()) {
            logMessage2("Categorized as: Duplicate Entry Error");
        }
    } elseif (strpos($errorMsg, 'timeout') !== false || strpos($errorMsg, 'Timeout') !== false) {
        $errorType = "TIMEOUT_ERROR";
        $userMessage = "Server is currently busy. Please wait a moment and try again. If unsuccessful after several attempts, open the case log, copy all text and save in a txt file or Word doc. Contact jill@website.com";
        if (isDebugModeEnabled()) {
            logMessage2("Categorized as: Timeout Error");
        }
    } else {
        if (isDebugModeEnabled()) {
            logMessage2("Categorized as: General Database Error");
        }
    }
    
    if (isDebugModeEnabled()) {
        logMessage2("=== CASE SAVE FAILED ===");
    }
    $errorDetails = $errorMsg . ($caseTime ? ' | Case time: ' . $caseTime : '');
    logCaseSaveDebug($userId, $username, $userEmail, $caseGrade, $caseScore, 'FAILED', $errorType, $errorDetails, null, $caseName);
    
    $_SESSION['flash_message'] = ['type' => 'error', 'message' => $userMessage];
    
    echo json_encode(["success" => false, "errorType" => $errorType, "message" => $userMessage, "technicalDetails" => $errorMsg]);
    
} catch (Exception $e) {
    if (isDebugModeEnabled()) {
        logMessage2("ERROR: General Exception occurred");
        logMessage2("Exception Message: " . $e->getMessage());
        logMessage2("=== CASE SAVE FAILED ===");
    }
    
    $errorDetails = $e->getMessage() . ($caseTime ? ' | Case time: ' . $caseTime : '');
    logCaseSaveDebug($userId, $username, $userEmail, $caseGrade, $caseScore, 'FAILED', 'GENERAL_ERROR', $errorDetails, null, $caseName);
    
    $_SESSION['flash_message'] = ['type' => 'error', 'message' => 'An unexpected error occurred. Please try again. If the problem persists, open the case log, copy all text and save in a txt file or Word doc. Contact jill@website.com'];
    
    echo json_encode(["success" => false, "errorType" => "GENERAL_ERROR", "message" => "An unexpected error occurred.", "technicalDetails" => $e->getMessage()]);
}
?>