// Reports Module

function loadReportsData() {
    // First, add the reports section to the HTML if it doesn't exist
    addReportsSection();
    
    // Load initial reports
    generateReportsOverview();
}

function addReportsSection() {
    const reportsSection = document.getElementById('reports');
    if (reportsSection && !reportsSection.querySelector('.reports-container')) {
        reportsSection.innerHTML = `
            <div class="section-header">
                <h2>Reports & Analytics</h2>
                <div class="header-actions">
                    <select id="report-period">
                        <option value="month">This Month</option>
                        <option value="quarter">This Quarter</option>
                        <option value="year">This Year</option>
                        <option value="custom">Custom Range</option>
                    </select>
                    <button class="btn btn-primary" onclick="generateAllReports()">
                        <i class="fas fa-chart-line"></i> Generate Reports
                    </button>
                </div>
            </div>
            
            <div class="reports-container">
                <!-- Financial Overview -->
                <div class="report-card">
                    <div class="report-header">
                        <h3><i class="fas fa-dollar-sign"></i> Financial Overview</h3>
                        <button class="btn btn-sm btn-secondary" onclick="exportFinancialReport()">
                            <i class="fas fa-download"></i> Export
                        </button>
                    </div>
                    <div class="report-content">
                        <div class="financial-metrics">
                            <div class="metric">
                                <div class="metric-label">Total Revenue</div>
                                <div class="metric-value" id="total-revenue">$0.00</div>
                            </div>
                            <div class="metric">
                                <div class="metric-label">Total Expenses</div>
                                <div class="metric-value" id="total-expenses">$0.00</div>
                            </div>
                            <div class="metric">
                                <div class="metric-label">Net Profit</div>
                                <div class="metric-value" id="net-profit">$0.00</div>
                            </div>
                            <div class="metric">
                                <div class="metric-label">Profit Margin</div>
                                <div class="metric-value" id="profit-margin">0%</div>
                            </div>
                        </div>
                        <div class="chart-container">
                            <canvas id="profit-expense-chart"></canvas>
                        </div>
                    </div>
                </div>

                <!-- Payroll Summary -->
                <div class="report-card">
                    <div class="report-header">
                        <h3><i class="fas fa-users"></i> Payroll Summary</h3>
                        <button class="btn btn-sm btn-secondary" onclick="exportPayrollReport()">
                            <i class="fas fa-download"></i> Export
                        </button>
                    </div>
                    <div class="report-content">
                        <div class="payroll-metrics">
                            <div class="metric">
                                <div class="metric-label">Total Staff</div>
                                <div class="metric-value" id="payroll-total-staff">0</div>
                            </div>
                            <div class="metric">
                                <div class="metric-label">Monthly Payroll</div>
                                <div class="metric-value" id="payroll-monthly-total">$0.00</div>
                            </div>
                            <div class="metric">
                                <div class="metric-label">Average Salary</div>
                                <div class="metric-value" id="payroll-average-salary">$0.00</div>
                            </div>
                        </div>
                        <div class="department-breakdown" id="department-breakdown">
                            <!-- Department breakdown will be populated here -->
                        </div>
                    </div>
                </div>

                <!-- Patient Analytics -->
                <div class="report-card">
                    <div class="report-header">
                        <h3><i class="fas fa-user-injured"></i> Patient Report</h3>
                        <button class="btn btn-sm btn-secondary" onclick="exportPatientReport()">
                            <i class="fas fa-download"></i> Export
                        </button>
                    </div>
                    <div class="report-content">
                        <div class="patient-metrics">
                            <div class="metric">
                                <div class="metric-label">Total Patients</div>
                                <div class="metric-value" id="report-total-patients">0</div>
                            </div>
                            <div class="metric">
                                <div class="metric-label">Active This Month</div>
                                <div class="metric-value" id="report-active-patients">0</div>
                            </div>
                            <div class="metric">
                                <div class="metric-label">New Patients</div>
                                <div class="metric-value" id="report-new-patients">0</div>
                            </div>
                            <div class="metric">
                                <div class="metric-label">Total Sessions</div>
                                <div class="metric-value" id="report-total-sessions">0</div>
                            </div>
                        </div>
                        <div class="therapy-distribution" id="therapy-distribution">
                            <!-- Therapy type distribution will be populated here -->
                        </div>
                    </div>
                </div>

                <!-- Revenue Breakdown -->
                <div class="report-card">
                    <div class="report-header">
                        <h3><i class="fas fa-chart-pie"></i> Revenue Breakdown</h3>
                        <button class="btn btn-sm btn-secondary" onclick="exportRevenueReport()">
                            <i class="fas fa-download"></i> Export
                        </button>
                    </div>
                    <div class="report-content">
                        <div class="revenue-sources" id="revenue-sources">
                            <!-- Revenue sources will be populated here -->
                        </div>
                        <div class="chart-container">
                            <canvas id="revenue-chart"></canvas>
                        </div>
                    </div>
                </div>

                <!-- Monthly Trends -->
                <div class="report-card full-width">
                    <div class="report-header">
                        <h3><i class="fas fa-trending-up"></i> Monthly Trends</h3>
                        <button class="btn btn-sm btn-secondary" onclick="exportTrendsReport()">
                            <i class="fas fa-download"></i> Export
                        </button>
                    </div>
                    <div class="report-content">
                        <div class="chart-container">
                            <canvas id="trends-chart"></canvas>
                        </div>
                    </div>
                </div>

                <!-- Custom Date Range -->
                <div id="custom-date-range" class="custom-range" style="display: none;">
                    <div class="form-group">
                        <label for="start-date">Start Date:</label>
                        <input type="date" id="start-date" name="startDate">
                    </div>
                    <div class="form-group">
                        <label for="end-date">End Date:</label>
                        <input type="date" id="end-date" name="endDate">
                    </div>
                    <button class="btn btn-primary" onclick="generateCustomReport()">
                        Generate Custom Report
                    </button>
                </div>
            </div>
        `;
    }
    
    // Setup period change handler
    const periodSelect = document.getElementById('report-period');
    if (periodSelect) {
        periodSelect.addEventListener('change', function() {
            const customRange = document.getElementById('custom-date-range');
            if (this.value === 'custom') {
                customRange.style.display = 'block';
            } else {
                customRange.style.display = 'none';
                generateReportsForPeriod(this.value);
            }
        });
    }
}

function generateReportsOverview() {
    const period = document.getElementById('report-period').value;
    generateReportsForPeriod(period);
}

function generateReportsForPeriod(period) {
    const dateRange = getDateRange(period);
    
    // Generate all reports
    generateFinancialReport(dateRange);
    generatePayrollReport(dateRange);
    generatePatientReport(dateRange);
    generateRevenueReport(dateRange);
    generateTrendsReport(dateRange);
}

function getDateRange(period) {
    const now = new Date();
    let startDate, endDate;
    
    switch (period) {
        case 'month':
            startDate = new Date(now.getFullYear(), now.getMonth(), 1);
            endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0);
            break;
        case 'quarter':
            const quarter = Math.floor(now.getMonth() / 3);
            startDate = new Date(now.getFullYear(), quarter * 3, 1);
            endDate = new Date(now.getFullYear(), (quarter + 1) * 3, 0);
            break;
        case 'year':
            startDate = new Date(now.getFullYear(), 0, 1);
            endDate = new Date(now.getFullYear(), 11, 31);
            break;
        default:
            // For custom range, will be handled separately
            return null;
    }
    
    return { startDate, endDate };
}

function generateFinancialReport(dateRange) {
    if (!dateRange) return;
    
    const expenses = window.app.getData('expenses');
    const patients = window.app.getData('patients');
    const schedules = window.app.getData('schedules');
    
    // Calculate expenses for the period
    const periodExpenses = expenses.filter(expense => {
        const expenseDate = new Date(expense.date);
        return expenseDate >= dateRange.startDate && expenseDate <= dateRange.endDate;
    });
    
    const totalExpenses = periodExpenses.reduce((total, expense) => 
        total + parseFloat(expense.amount || 0), 0);
    
    // Calculate revenue (from patient visits)
    let totalRevenue = 0;
    patients.forEach(patient => {
        if (patient.visits) {
            const periodVisits = patient.visits.filter(visit => {
                const visitDate = new Date(visit.date);
                return visitDate >= dateRange.startDate && visitDate <= dateRange.endDate;
            });
            
            totalRevenue += periodVisits.reduce((total, visit) => 
                total + parseFloat(visit.fee || 7500), 0); // Default Ksh 7,500 per session
        }
    });
    
    const netProfit = totalRevenue - totalExpenses;
    const profitMargin = totalRevenue > 0 ? ((netProfit / totalRevenue) * 100).toFixed(1) : 0;
    
    // Update display
    document.getElementById('total-revenue').textContent = window.app.formatCurrency(totalRevenue);
    document.getElementById('total-expenses').textContent = window.app.formatCurrency(totalExpenses);
    document.getElementById('net-profit').textContent = window.app.formatCurrency(netProfit);
    document.getElementById('profit-margin').textContent = profitMargin + '%';
    
    // Update profit margin color
    const profitElement = document.getElementById('net-profit');
    profitElement.className = netProfit >= 0 ? 'metric-value positive' : 'metric-value negative';
}

function generatePayrollReport(dateRange) {
    const staff = window.app.getData('staff');
    
    const totalStaff = staff.length;
    const monthlyPayroll = staff.reduce((total, member) => 
        total + parseFloat(member.salary || 0), 0);
    const averageSalary = totalStaff > 0 ? monthlyPayroll / totalStaff : 0;
    
    // Update display
    document.getElementById('payroll-total-staff').textContent = totalStaff;
    document.getElementById('payroll-monthly-total').textContent = window.app.formatCurrency(monthlyPayroll);
    document.getElementById('payroll-average-salary').textContent = window.app.formatCurrency(averageSalary);
    
    // Department breakdown
    const departmentBreakdown = {};
    staff.forEach(member => {
        const dept = member.department || 'Other';
        if (!departmentBreakdown[dept]) {
            departmentBreakdown[dept] = { count: 0, totalSalary: 0 };
        }
        departmentBreakdown[dept].count++;
        departmentBreakdown[dept].totalSalary += parseFloat(member.salary || 0);
    });
    
    const breakdownContainer = document.getElementById('department-breakdown');
    breakdownContainer.innerHTML = `
        <h4>Department Breakdown</h4>
        <div class="department-stats">
            ${Object.entries(departmentBreakdown).map(([dept, data]) => `
                <div class="department-stat">
                    <div class="dept-name">${dept.charAt(0).toUpperCase() + dept.slice(1)}</div>
                    <div class="dept-count">${data.count} staff</div>
                    <div class="dept-salary">${window.app.formatCurrency(data.totalSalary)}</div>
                </div>
            `).join('')}
        </div>
    `;
}

function generatePatientReport(dateRange) {
    if (!dateRange) return;
    
    const patients = window.app.getData('patients');
    
    // Total patients
    const totalPatients = patients.length;
    
    // New patients in the period
    const newPatients = patients.filter(patient => {
        const createdDate = new Date(patient.createdAt || patient.date);
        return createdDate >= dateRange.startDate && createdDate <= dateRange.endDate;
    }).length;
    
    // Active patients (with visits in the period)
    let activePatients = 0;
    let totalSessions = 0;
    
    patients.forEach(patient => {
        if (patient.visits) {
            const periodVisits = patient.visits.filter(visit => {
                const visitDate = new Date(visit.date);
                return visitDate >= dateRange.startDate && visitDate <= dateRange.endDate;
            });
            
            if (periodVisits.length > 0) {
                activePatients++;
                totalSessions += periodVisits.length;
            }
        }
    });
    
    // Update display
    document.getElementById('report-total-patients').textContent = totalPatients;
    document.getElementById('report-active-patients').textContent = activePatients;
    document.getElementById('report-new-patients').textContent = newPatients;
    document.getElementById('report-total-sessions').textContent = totalSessions;
    
    // Therapy type distribution
    const therapyDistribution = {};
    patients.forEach(patient => {
        const therapy = patient.therapyType || 'Other';
        therapyDistribution[therapy] = (therapyDistribution[therapy] || 0) + 1;
    });
    
    const distributionContainer = document.getElementById('therapy-distribution');
    distributionContainer.innerHTML = `
        <h4>Therapy Type Distribution</h4>
        <div class="therapy-stats">
            ${Object.entries(therapyDistribution).map(([therapy, count]) => `
                <div class="therapy-stat">
                    <div class="therapy-name">${therapy}</div>
                    <div class="therapy-count">${count} patients</div>
                    <div class="therapy-percentage">${((count / totalPatients) * 100).toFixed(1)}%</div>
                </div>
            `).join('')}
        </div>
    `;
}

function generateRevenueReport(dateRange) {
    if (!dateRange) return;
    
    const patients = window.app.getData('patients');
    
    // Revenue by therapy type
    const revenueByTherapy = {};
    
    patients.forEach(patient => {
        if (patient.visits) {
            const periodVisits = patient.visits.filter(visit => {
                const visitDate = new Date(visit.date);
                return visitDate >= dateRange.startDate && visitDate <= dateRange.endDate;
            });
            
            const therapy = patient.therapyType || 'Other';
            if (!revenueByTherapy[therapy]) {
                revenueByTherapy[therapy] = 0;
            }
            
            periodVisits.forEach(visit => {
                revenueByTherapy[therapy] += parseFloat(visit.fee || 7500);
            });
        }
    });
    
    const totalRevenue = Object.values(revenueByTherapy).reduce((sum, amount) => sum + amount, 0);
    
    const revenueContainer = document.getElementById('revenue-sources');
    revenueContainer.innerHTML = `
        <h4>Revenue by Therapy Type</h4>
        <div class="revenue-stats">
            ${Object.entries(revenueByTherapy).map(([therapy, amount]) => `
                <div class="revenue-stat">
                    <div class="revenue-therapy">${therapy}</div>
                    <div class="revenue-amount">${window.app.formatCurrency(amount)}</div>
                    <div class="revenue-percentage">${totalRevenue > 0 ? ((amount / totalRevenue) * 100).toFixed(1) : 0}%</div>
                </div>
            `).join('')}
        </div>
    `;
}

function generateTrendsReport(dateRange) {
    // This would typically generate charts showing trends over time
    // For now, we'll create a simple monthly comparison
    const currentMonth = new Date().getMonth();
    const previousMonth = currentMonth === 0 ? 11 : currentMonth - 1;
    
    // Placeholder for trends data
    console.log('Trends report generated for period:', dateRange);
}

function generateAllReports() {
    const period = document.getElementById('report-period').value;
    
    if (period === 'custom') {
        generateCustomReport();
    } else {
        generateReportsForPeriod(period);
        window.app.showNotification('Reports generated successfully!', 'success');
    }
}

function generateCustomReport() {
    const startDate = new Date(document.getElementById('start-date').value);
    const endDate = new Date(document.getElementById('end-date').value);
    
    if (!startDate || !endDate || startDate > endDate) {
        window.app.showNotification('Please select valid start and end dates', 'error');
        return;
    }
    
    const dateRange = { startDate, endDate };
    
    generateFinancialReport(dateRange);
    generatePayrollReport(dateRange);
    generatePatientReport(dateRange);
    generateRevenueReport(dateRange);
    generateTrendsReport(dateRange);
    
    window.app.showNotification('Custom report generated successfully!', 'success');
}

function exportFinancialReport() {
    const period = document.getElementById('report-period').value;
    const dateRange = getDateRange(period);
    
    const expenses = window.app.getData('expenses');
    const patients = window.app.getData('patients');
    
    // Get data for the period
    const periodExpenses = expenses.filter(expense => {
        const expenseDate = new Date(expense.date);
        return expenseDate >= dateRange.startDate && expenseDate <= dateRange.endDate;
    });
    
    let revenueData = [];
    patients.forEach(patient => {
        if (patient.visits) {
            const periodVisits = patient.visits.filter(visit => {
                const visitDate = new Date(visit.date);
                return visitDate >= dateRange.startDate && visitDate <= dateRange.endDate;
            });
            
            periodVisits.forEach(visit => {
                revenueData.push({
                    'Date': visit.date,
                    'Patient': patient.name,
                    'Therapy Type': patient.therapyType,
                    'Revenue': visit.fee || 7500,
                    'Type': 'Revenue'
                });
            });
        }
    });
    
    const expenseData = periodExpenses.map(expense => ({
        'Date': expense.date,
        'Description': expense.description,
        'Category': expense.category,
        'Amount': expense.amount,
        'Type': 'Expense'
    }));
    
    const combinedData = [...revenueData, ...expenseData];
    
    const currentDate = new Date().toISOString().split('T')[0];
    window.app.exportToCSV(combinedData, `financial-report-${currentDate}.csv`);
    window.app.showNotification('Financial report exported successfully!', 'success');
}

function exportPayrollReport() {
    const staff = window.app.getData('staff');
    
    const payrollData = staff.map(member => ({
        'Name': member.name,
        'Role': member.role,
        'Department': member.department,
        'Monthly Salary': member.salary,
        'Start Date': member.startDate,
        'Contact': member.contact
    }));
    
    const currentDate = new Date().toISOString().split('T')[0];
    window.app.exportToCSV(payrollData, `payroll-report-${currentDate}.csv`);
    window.app.showNotification('Payroll report exported successfully!', 'success');
}

function exportPatientReport() {
    const patients = window.app.getData('patients');
    
    const patientData = patients.map(patient => ({
        'Patient Name': patient.name,
        'Age': patient.age,
        'Parent/Guardian': patient.guardian,
        'Contact': patient.contact,
        'Problem Type': patient.problemType,
        'Therapy Type': patient.therapyType,
        'Total Visits': patient.visits ? patient.visits.length : 0,
        'Last Visit': patient.lastVisit || 'No visits',
        'Registration Date': patient.createdAt ? new Date(patient.createdAt).toLocaleDateString() : ''
    }));
    
    const currentDate = new Date().toISOString().split('T')[0];
    window.app.exportToCSV(patientData, `patient-report-${currentDate}.csv`);
    window.app.showNotification('Patient report exported successfully!', 'success');
}

function exportRevenueReport() {
    const patients = window.app.getData('patients');
    let revenueData = [];
    
    patients.forEach(patient => {
        if (patient.visits) {
            patient.visits.forEach(visit => {
                revenueData.push({
                    'Date': visit.date,
                    'Patient Name': patient.name,
                    'Therapy Type': patient.therapyType,
                    'Therapist': visit.therapist || '',
                    'Session Fee': visit.fee || 7500,
                    'Duration': visit.duration || 60,
                    'Notes': visit.notes || ''
                });
            });
        }
    });
    
    const currentDate = new Date().toISOString().split('T')[0];
    window.app.exportToCSV(revenueData, `revenue-report-${currentDate}.csv`);
    window.app.showNotification('Revenue report exported successfully!', 'success');
}

function exportTrendsReport() {
    // For now, export a summary of key metrics over time
    const months = [];
    const currentDate = new Date();
    
    for (let i = 11; i >= 0; i--) {
        const date = new Date(currentDate.getFullYear(), currentDate.getMonth() - i, 1);
        months.push({
            'Month': date.toLocaleDateString('en-US', { year: 'numeric', month: 'long' }),
            'Patients': 0, // Would calculate from actual data
            'Revenue': 0,  // Would calculate from actual data
            'Expenses': 0  // Would calculate from actual data
        });
    }
    
    const currentDateStr = new Date().toISOString().split('T')[0];
    window.app.exportToCSV(months, `trends-report-${currentDateStr}.csv`);
    window.app.showNotification('Trends report exported successfully!', 'success');
}

// Add CSS for reports styles
const reportsStyles = `
    <style>
        .reports-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 1.5rem;
        }
        
        .report-card {
            background: var(--white);
            border-radius: var(--border-radius);
            box-shadow: var(--shadow);
            overflow: hidden;
        }
        
        .report-card.full-width {
            grid-column: 1 / -1;
        }
        
        .report-header {
            background: var(--primary-teal);
            color: var(--white);
            padding: 1rem 1.5rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .report-header h3 {
            margin: 0;
            font-size: 1.1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .report-content {
            padding: 1.5rem;
        }
        
        .financial-metrics, .payroll-metrics, .patient-metrics {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .metric {
            text-align: center;
            padding: 1rem;
            background: var(--light-gray);
            border-radius: var(--border-radius);
        }
        
        .metric-label {
            font-size: 0.9rem;
            color: #666;
            margin-bottom: 0.5rem;
        }
        
        .metric-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: var(--primary-teal);
        }
        
        .metric-value.positive {
            color: var(--success);
        }
        
        .metric-value.negative {
            color: var(--error);
        }
        
        .department-stats, .therapy-stats, .revenue-stats {
            display: flex;
            flex-direction: column;
            gap: 0.75rem;
        }
        
        .department-stat, .therapy-stat, .revenue-stat {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem;
            background: var(--light-gray);
            border-radius: var(--border-radius);
            border-left: 4px solid var(--primary-orange);
        }
        
        .dept-name, .therapy-name, .revenue-therapy {
            font-weight: 500;
            flex: 1;
        }
        
        .dept-count, .therapy-count, .dept-salary, .revenue-amount {
            font-weight: 600;
            color: var(--primary-teal);
        }
        
        .therapy-percentage, .revenue-percentage {
            font-size: 0.9rem;
            color: #666;
            min-width: 50px;
            text-align: right;
        }
        
        .chart-container {
            height: 300px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: var(--light-gray);
            border-radius: var(--border-radius);
            color: #666;
        }
        
        .custom-range {
            background: var(--white);
            padding: 1.5rem;
            border-radius: var(--border-radius);
            box-shadow: var(--shadow);
            margin-top: 1rem;
            display: flex;
            gap: 1rem;
            align-items: end;
        }
        
        .custom-range .form-group {
            margin-bottom: 0;
        }
        
        .header-actions {
            display: flex;
            gap: 0.5rem;
            align-items: center;
        }
        
        @media (max-width: 768px) {
            .reports-container {
                grid-template-columns: 1fr;
            }
            
            .financial-metrics, .payroll-metrics, .patient-metrics {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .custom-range {
                flex-direction: column;
                align-items: stretch;
            }
            
            .header-actions {
                flex-direction: column;
                align-items: stretch;
            }
        }
    </style>
`;

document.head.insertAdjacentHTML('beforeend', reportsStyles);
