// ================================================================
// ENHANCED CASE SAVE FUNCTIONS WITH DEBUG LOGGING AND POPUP MODALS
// ================================================================

// Popup modal system for case save notifications
function showCaseSaveModal(isSuccess, errorType, message) {
    var existingModal = document.getElementById('caseSaveModal');
    if (existingModal) {
        existingModal.remove();
    }
    
    var modal = document.createElement('div');
    modal.id = 'caseSaveModal';
    modal.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.7);z-index:10000;display:flex;align-items:center;justify-content:center;';
    
    var modalContent = document.createElement('div');
    modalContent.style.cssText = 'background:white;padding:30px;border-radius:8px;max-width:500px;position:relative;box-shadow:0 4px 6px rgba(0,0,0,0.3);text-align:center;';
    
    var messageDiv = document.createElement('div');
    
    if (isSuccess === null) {
        messageDiv.innerHTML = '<h3 style="color:#007bff;margin:0 0 15px 0;">Saving...</h3><p style="margin:0;font-size:16px;">Please wait while your case is being saved.</p>';
        modalContent.appendChild(messageDiv);
    } else {
        var closeBtn = document.createElement('span');
        closeBtn.innerHTML = '&times;';
        closeBtn.style.cssText = 'position:absolute;top:10px;right:15px;font-size:28px;cursor:pointer;color:#666;';
        closeBtn.onclick = function() { modal.remove(); };
        
        if (isSuccess) {
            messageDiv.innerHTML = '<h3 style="color:#28a745;margin:0 0 15px 0;">✓ Success</h3><p style="margin:0 0 20px 0;font-size:16px;">Case log was saved to your account.</p>';
        } else {
            var errorMessages = {
                'SESSION_EXPIRED': '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',
                'CONNECTION_ERROR': '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',
                'TIMEOUT_ERROR': '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',
                'DATABASE_ERROR': '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',
                'VALIDATION_ERROR': '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',
                'NETWORK_ERROR': 'Network connection problem detected. Check your internet connection and 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',
                'GENERAL_ERROR': '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'
            };
            
            var errorMsg = message || errorMessages[errorType] || errorMessages['GENERAL_ERROR'];
            messageDiv.innerHTML = '<h3 style="color:#dc3545;margin:0 0 15px 0;">✗ Save Failed</h3><p style="margin:0 0 20px 0;font-size:14px;line-height:1.6;">' + errorMsg + '</p>';
        }
        
        var continueBtn = document.createElement('button');
        continueBtn.textContent = 'Continue';
        continueBtn.style.cssText = 'padding:10px 30px;background:#007bff;color:white;border:none;border-radius:4px;cursor:pointer;font-size:16px;';
        continueBtn.onclick = function() { modal.remove(); };
        
        modalContent.appendChild(closeBtn);
        modalContent.appendChild(messageDiv);
        modalContent.appendChild(continueBtn);
    }
    
    modal.appendChild(modalContent);
    document.body.appendChild(modal);
}

// Enhanced save case data function with comprehensive logging
function saveCaseDataEnhanced() {
    console.log("=== CASE SAVE INITIATED ===");
    console.log("Timestamp:", new Date().toISOString());
    console.log("User Agent:", navigator.userAgent);
    
    var caseLogElement = document.querySelector("#caseLogScroller pre");
    var grade, score;
    
    if (caseLogElement) {
        var caseLog = caseLogElement.innerText;
        console.log("Case log extracted, length:", caseLog.length, "characters");
    } else {
        console.error("ERROR: Case log element not found");
        caseLog = null;
        showCaseSaveModal(false, 'VALIDATION_ERROR', 'Case log not found');
        return;
    }
    
    if (!caseLog || caseLog.trim() === '') {
        console.error("ERROR: Case log is empty");
        showCaseSaveModal(false, 'VALIDATION_ERROR', 'Case log is empty');
        return;
    }
    
    // Extract grade
    var gradeMatch = caseLog.match(/Grade: (\w+)/);
    if (gradeMatch) {
        grade = gradeMatch[1];
        console.log("Grade extracted:", grade);
    } else {
        console.warn("Grade not found in case log, using default");
        grade = "Unknown";
    }
    
    // Extract score
    var scoreElement = document.getElementById("txtScore");
    if (scoreElement) {
        var scoreText = scoreElement.innerText;
        var scoreMatch = scoreText.match(/Score: (\d+) \/ \d+/);
        if (scoreMatch) {
            score = scoreMatch[1];
            console.log("Score extracted:", score);
        } else {
            console.warn("Score not found in score element");
            score = null;
        }
    } else {
        console.warn("Score element not found");
        score = null;
    }
    
    var data = {
        caseLog: caseLog,
        grade: grade,
        score: score
    };
    
    console.log("Sending data to server...");
    console.log("Data payload size:", JSON.stringify(data).length, "bytes");
    
    // Make API call with comprehensive error handling
    fetch("/api/save_case_data.php", {
        method: "POST",
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        console.log("Server response status:", response.status);
        if (!response.ok) {
            throw new Error('Server responded with status: ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        console.log("Server response data:", data);
        
        if (data.success) {
            console.log("SUCCESS: Case saved successfully");
            if (data.insertId) {
                console.log("Insert ID:", data.insertId);
            }
            showCaseSaveModal(true, null, null);
            console.log("=== CASE SAVE COMPLETED ===");
        } else {
            console.error("ERROR: Server returned failure");
            console.error("Error type:", data.errorType);
            console.error("Error message:", data.message);
            if (data.technicalDetails) {
                console.error("Technical details:", data.technicalDetails);
            }
            showCaseSaveModal(false, data.errorType, data.message);
            console.log("=== CASE SAVE FAILED ===");
        }
    })
    .catch(error => {
        console.error("ERROR: Network or parsing error occurred");
        console.error("Error details:", error.message);
        console.error("Error stack:", error.stack);
        showCaseSaveModal(false, 'NETWORK_ERROR', error.message);
        console.log("=== CASE SAVE FAILED ===");
    });
}
