/**
 * Case Management
 * Case creation, editing, and management functions
 */

// ============================================
// Case Manager Class
// ============================================

class CaseManager {
    constructor() {
        this.currentCaseId = null;
        this.init();
    }
    
    init() {
        this.bindEvents();
        this.initCaseForm();
        this.initFollowUp();
        this.initPrescription();
    }
    
    bindEvents() {
        // Save case form
        const caseForm = document.getElementById('caseForm');
        if (caseForm) {
            caseForm.addEventListener('submit', (e) => this.saveCase(e));
        }
        
        // Delete case button
        const deleteBtn = document.getElementById('deleteCaseBtn');
        if (deleteBtn) {
            deleteBtn.addEventListener('click', () => this.deleteCase());
        }
        
        // Add follow-up
        const followUpBtn = document.getElementById('addFollowUpBtn');
        if (followUpBtn) {
            followUpBtn.addEventListener('click', () => this.addFollowUp());
        }
        
        // Prescribe remedy
        const prescribeBtn = document.getElementById('prescribeBtn');
        if (prescribeBtn) {
            prescribeBtn.addEventListener('click', () => this.prescribeRemedy());
        }
    }
    
    initCaseForm() {
        const caseIdField = document.getElementById('case_id');
        if (caseIdField) {
            this.currentCaseId = caseIdField.value;
        }
        
        // Auto-save draft
        const form = document.getElementById('caseForm');
        if (form) {
            let saveTimeout;
            form.addEventListener('input', () => {
                clearTimeout(saveTimeout);
                saveTimeout = setTimeout(() => this.autoSaveDraft(), 3000);
            });
        }
    }
    
    initFollowUp() {
        const followUpDate = document.getElementById('follow_up_date');
        if (followUpDate) {
            // Set default follow-up date to 14 days from now
            if (!followUpDate.value) {
                const date = new Date();
                date.setDate(date.getDate() + 14);
                followUpDate.value = date.toISOString().split('T')[0];
            }
        }
    }
    
    initPrescription() {
        const remedySelect = document.getElementById('remedy_id');
        if (remedySelect) {
            remedySelect.addEventListener('change', () => this.loadRemedyDetails());
        }
    }
    
    async saveCase(e) {
        e.preventDefault();
        const form = e.target;
        const formData = new FormData(form);
        
        // Add selected rubrics
        const rubricField = document.getElementById('selectedRubricsJson');
        if (rubricField) {
            formData.append('selected_rubrics', rubricField.value);
        }
        
        showLoading();
        
        try {
            const response = await fetch('api/save-case.php', {
                method: 'POST',
                body: formData
            });
            const data = await response.json();
            
            if (data.success) {
                showNotification('Case saved successfully!', 'success');
                if (data.redirect) {
                    setTimeout(() => window.location.href = data.redirect, 1500);
                }
            } else {
                showNotification(data.error || 'Failed to save case', 'error');
            }
        } catch (error) {
            console.error('Save error:', error);
            showNotification('Network error. Please try again.', 'error');
        } finally {
            hideLoading();
        }
    }
    
    async autoSaveDraft() {
        const form = document.getElementById('caseForm');
        if (!form) return;
        
        const formData = new FormData(form);
        formData.append('auto_save', '1');
        
        try {
            const response = await fetch('api/auto-save-case.php', {
                method: 'POST',
                body: formData
            });
            const data = await response.json();
            if (data.success) {
                console.log('Draft auto-saved at', new Date().toLocaleTimeString());
            }
        } catch (error) {
            console.error('Auto-save error:', error);
        }
    }
    
    async deleteCase() {
        if (!confirm('Are you sure you want to delete this case? This action cannot be undone.')) {
            return;
        }
        
        if (!this.currentCaseId) return;
        
        showLoading();
        
        try {
            const response = await fetch(`api/delete-case.php?id=${this.currentCaseId}`, {
                method: 'DELETE'
            });
            const data = await response.json();
            
            if (data.success) {
                showNotification('Case deleted successfully', 'success');
                setTimeout(() => window.location.href = 'list.php', 1500);
            } else {
                showNotification(data.error || 'Failed to delete case', 'error');
            }
        } catch (error) {
            showNotification('Network error. Please try again.', 'error');
        } finally {
            hideLoading();
        }
    }
    
    async addFollowUp() {
        const followUpDate = document.getElementById('follow_up_date')?.value;
        const progress = document.getElementById('progress')?.value;
        const newSymptoms = document.getElementById('new_symptoms')?.value;
        
        if (!progress) {
            showNotification('Please enter progress notes', 'error');
            return;
        }
        
        showLoading();
        
        try {
            const response = await fetch('api/add-follow-up.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    case_id: this.currentCaseId,
                    follow_up_date: followUpDate,
                    progress: progress,
                    new_symptoms: newSymptoms,
                    remedy_repeated: document.getElementById('remedy_repeated')?.checked || false
                })
            });
            const data = await response.json();
            
            if (data.success) {
                showNotification('Follow-up added successfully', 'success');
                setTimeout(() => location.reload(), 1500);
            } else {
                showNotification(data.error || 'Failed to add follow-up', 'error');
            }
        } catch (error) {
            showNotification('Network error. Please try again.', 'error');
        } finally {
            hideLoading();
        }
    }
    
    async prescribeRemedy() {
        const remedyId = document.getElementById('remedy_id')?.value;
        const potency = document.getElementById('potency')?.value;
        const followUpDate = document.getElementById('follow_up_date')?.value;
        
        if (!remedyId) {
            showNotification('Please select a remedy', 'error');
            return;
        }
        
        showLoading();
        
        try {
            const response = await fetch('api/prescribe.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    case_id: this.currentCaseId,
                    remedy_id: remedyId,
                    potency: potency,
                    follow_up_date: followUpDate
                })
            });
            const data = await response.json();
            
            if (data.success) {
                showNotification('Prescription added successfully', 'success');
                setTimeout(() => location.reload(), 1500);
            } else {
                showNotification(data.error || 'Failed to add prescription', 'error');
            }
        } catch (error) {
            showNotification('Network error. Please try again.', 'error');
        } finally {
            hideLoading();
        }
    }
    
    async loadRemedyDetails() {
        const remedyId = document.getElementById('remedy_id')?.value;
        if (!remedyId) return;
        
        const detailsDiv = document.getElementById('remedyDetails');
        if (detailsDiv) {
            detailsDiv.innerHTML = '<div class="spinner-border spinner-border-sm"></div> Loading...';
            
            try {
                const response = await fetch(`api/get-remedy-details.php?id=${remedyId}`);
                const data = await response.json();
                
                if (data.success && data.data) {
                    const remedy = data.data;
                    let html = `
                        <div class="card mt-2">
                            <div class="card-body">
                                <h6>${remedy.name} ${remedy.abbreviation ? `(${remedy.abbreviation})` : ''}</h6>
                    `;
                    
                    if (remedy.modalities) {
                        if (remedy.modalities.better?.length) {
                            html += `<div><strong>Better:</strong> ${remedy.modalities.better.join(', ')}</div>`;
                        }
                        if (remedy.modalities.worse?.length) {
                            html += `<div><strong>Worse:</strong> ${remedy.modalities.worse.join(', ')}</div>`;
                        }
                    }
                    
                    html += `
                                <hr>
                                <div class="small">${remedy.materia_medica ? remedy.materia_medica.substring(0, 200) + '...' : 'No Materia Medica available'}</div>
                                <a href="../materia-medica/view.php?id=${remedy.id}" target="_blank" class="btn btn-sm btn-outline-primary mt-2">View Full Monograph</a>
                            </div>
                        </div>
                    `;
                    detailsDiv.innerHTML = html;
                } else {
                    detailsDiv.innerHTML = '<div class="alert alert-warning mt-2">No details available</div>';
                }
            } catch (error) {
                detailsDiv.innerHTML = '<div class="alert alert-danger mt-2">Error loading details</div>';
            }
        }
    }
    
    exportCase(format = 'pdf') {
        if (!this.currentCaseId) return;
        
        if (format === 'pdf') {
            window.open(`export.php?id=${this.currentCaseId}&format=pdf`, '_blank');
        } else if (format === 'print') {
            window.open(`print.php?id=${this.currentCaseId}`, '_blank');
        }
    }
}

// Initialize Case Manager
let caseManager = null;

document.addEventListener('DOMContentLoaded', () => {
    if (document.getElementById('caseForm') || document.getElementById('deleteCaseBtn')) {
        caseManager = new CaseManager();
        window.caseManager = caseManager;
    }
});