// Office Expenses Module

let currentEditingExpense = null;

function loadExpensesData() {
    // First, add the expenses section to the HTML if it doesn't exist
    addExpensesSection();
    
    const expensesTableBody = document.querySelector('#expenses-table tbody');
    const expenses = window.app.getData('expenses');
    
    expensesTableBody.innerHTML = expenses.map(expense => `
        <tr>
            <td>${window.app.formatDate(expense.date)}</td>
            <td>${expense.office || 'Main Office'}</td>
            <td>${expense.category}</td>
            <td>${expense.description}</td>
            <td>${window.app.formatCurrency(parseFloat(expense.amount || 0))}</td>
            <td>${expense.receipt ? '<i class="fas fa-file-alt text-success"></i>' : '<i class="fas fa-times text-danger"></i>'}</td>
            <td>
                <button class="btn btn-sm btn-warning" onclick="editExpense(${expense.id})">
                    <i class="fas fa-edit"></i> Edit
                </button>
                <button class="btn btn-sm btn-danger" onclick="deleteExpense(${expense.id})">
                    <i class="fas fa-trash"></i> Delete
                </button>
            </td>
        </tr>
    `).join('');

    // Setup category filter
    const categoryFilter = document.getElementById('expense-category-filter');
    if (categoryFilter) {
        categoryFilter.addEventListener('change', filterExpensesByCategory);
    }

    // Load expense summary
    loadExpenseSummary();
}

function addExpensesSection() {
    const expensesSection = document.getElementById('expenses');
    if (expensesSection && !expensesSection.querySelector('#expenses-table')) {
        expensesSection.innerHTML = `
            <div class="section-header">
                <h2>Office Expenditures</h2>
                <button class="btn btn-primary" onclick="showExpenseModal()">
                    <i class="fas fa-plus"></i> Add Expense
                </button>
            </div>
            
            <div class="filters">
                <select id="expense-category-filter">
                    <option value="">All Categories</option>
                    <option value="rent">Rent</option>
                    <option value="utilities">Utilities</option>
                    <option value="marketing">Marketing</option>
                    <option value="miscellaneous">Miscellaneous</option>
                </select>
                <button class="btn btn-secondary" onclick="exportExpenses()">
                    <i class="fas fa-download"></i> Export Expenses
                </button>
            </div>

            <div class="table-container">
                <table id="expenses-table">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Office</th>
                            <th>Category</th>
                            <th>Description</th>
                            <th>Amount</th>
                            <th>Receipt</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Expenses data will be populated here -->
                    </tbody>
                </table>
            </div>

            <div id="expense-summary" class="expense-summary">
                <h3>Expense Summary</h3>
                <div class="summary-grid">
                    <div class="summary-card">
                        <h4>This Month</h4>
                        <div class="summary-amount" id="monthly-expense-total">$0.00</div>
                        <div class="summary-details" id="monthly-expense-breakdown"></div>
                    </div>
                    <div class="summary-card">
                        <h4>This Year</h4>
                        <div class="summary-amount" id="yearly-expense-total">$0.00</div>
                        <div class="summary-details" id="yearly-expense-breakdown"></div>
                    </div>
                </div>
            </div>
        `;
    }
}

function filterExpensesByCategory() {
    const filter = document.getElementById('expense-category-filter').value;
    const expenses = window.app.getData('expenses');
    const filteredExpenses = filter ? expenses.filter(expense => expense.category === filter) : expenses;
    
    const expensesTableBody = document.querySelector('#expenses-table tbody');
    expensesTableBody.innerHTML = filteredExpenses.map(expense => `
        <tr>
            <td>${window.app.formatDate(expense.date)}</td>
            <td>${expense.office || 'Main Office'}</td>
            <td>${expense.category}</td>
            <td>${expense.description}</td>
            <td>${window.app.formatCurrency(parseFloat(expense.amount || 0))}</td>
            <td>${expense.receipt ? '<i class="fas fa-file-alt text-success"></i>' : '<i class="fas fa-times text-danger"></i>'}</td>
            <td>
                <button class="btn btn-sm btn-warning" onclick="editExpense(${expense.id})">
                    <i class="fas fa-edit"></i> Edit
                </button>
                <button class="btn btn-sm btn-danger" onclick="deleteExpense(${expense.id})">
                    <i class="fas fa-trash"></i> Delete
                </button>
            </td>
        </tr>
    `).join('');
}

function showExpenseModal(expenseId = null) {
    const expense = expenseId ? window.app.getData('expenses').find(e => e.id === expenseId) : null;
    const isEdit = !!expense;
    
    const modalContent = `
        <div class="modal">
            <div class="modal-header">
                <h3>${isEdit ? 'Edit Expense' : 'Add New Expense'}</h3>
                <button class="modal-close" onclick="window.app.closeModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <form id="expense-form">
                    <div class="form-group">
                        <label for="expense-date">Date *</label>
                        <input type="date" id="expense-date" name="date" required 
                               value="${expense ? expense.date : new Date().toISOString().split('T')[0]}">
                    </div>
                    
                    <div class="form-group">
                        <label for="expense-office">Office</label>
                        <input type="text" id="expense-office" name="office" 
                               value="${expense ? expense.office || '' : 'Main Office'}" 
                               placeholder="Office location">
                    </div>
                    
                    <div class="form-group">
                        <label for="expense-category">Category *</label>
                        <select id="expense-category" name="category" required>
                            <option value="">Select Category</option>
                            <option value="rent" ${expense && expense.category === 'rent' ? 'selected' : ''}>Rent</option>
                            <option value="utilities" ${expense && expense.category === 'utilities' ? 'selected' : ''}>Utilities</option>
                            <option value="marketing" ${expense && expense.category === 'marketing' ? 'selected' : ''}>Marketing</option>
                            <option value="miscellaneous" ${expense && expense.category === 'miscellaneous' ? 'selected' : ''}>Miscellaneous</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="expense-description">Description *</label>
                        <textarea id="expense-description" name="description" required rows="3"
                                  placeholder="Describe the expense">${expense ? expense.description || '' : ''}</textarea>
                    </div>
                    
                    <div class="form-group">
                        <label for="expense-amount">Amount *</label>
                        <input type="number" id="expense-amount" name="amount" required step="0.01" min="0"
                               value="${expense ? expense.amount : ''}" placeholder="Enter amount">
                    </div>
                    
                    <div class="form-group">
                        <label for="expense-receipt">Receipt (Optional)</label>
                        <input type="file" id="expense-receipt" name="receipt" accept="image/*,.pdf">
                        ${expense && expense.receipt ? `<div class="current-receipt">Current receipt: ${expense.receipt}</div>` : ''}
                    </div>
                    
                    <div class="form-group">
                        <label for="expense-notes">Notes</label>
                        <textarea id="expense-notes" name="notes" rows="2" 
                                  placeholder="Additional notes">${expense ? expense.notes || '' : ''}</textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="window.app.closeModal()">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="saveExpense(${expenseId})">
                    <i class="fas fa-save"></i> ${isEdit ? 'Update' : 'Add'} Expense
                </button>
            </div>
        </div>
    `;
    
    window.app.showModal(modalContent);
    currentEditingExpense = expenseId;
}

function saveExpense(expenseId) {
    const form = document.getElementById('expense-form');
    const formData = new FormData(form);
    
    // Validate required fields
    const requiredFields = ['date', 'category', 'description', 'amount'];
    for (const field of requiredFields) {
        if (!formData.get(field)) {
            window.app.showNotification(`Please fill in the ${field} field`, 'error');
            return;
        }
    }
    
    const expenseData = {
        id: expenseId || window.app.generateId('expenses'),
        date: formData.get('date'),
        office: formData.get('office') || 'Main Office',
        category: formData.get('category'),
        description: formData.get('description'),
        amount: parseFloat(formData.get('amount')),
        receipt: formData.get('receipt') ? formData.get('receipt').name : (expenseId ? window.app.getData('expenses').find(e => e.id === expenseId)?.receipt : null),
        notes: formData.get('notes') || '',
        createdAt: expenseId ? undefined : new Date().toISOString(),
        updatedAt: new Date().toISOString()
    };
    
    let expenses = window.app.getData('expenses');
    
    if (expenseId) {
        // Update existing expense
        const index = expenses.findIndex(e => e.id === expenseId);
        if (index !== -1) {
            expenses[index] = { ...expenses[index], ...expenseData };
        }
    } else {
        // Add new expense
        expenses.push(expenseData);
    }
    
    window.app.saveData('expenses', expenses);
    window.app.closeModal();
    loadExpensesData();
    
    window.app.showNotification(
        `Expense ${expenseId ? 'updated' : 'added'} successfully!`,
        'success'
    );
}

function editExpense(expenseId) {
    showExpenseModal(expenseId);
}

function deleteExpense(expenseId) {
    if (confirm('Are you sure you want to delete this expense? This action cannot be undone.')) {
        let expenses = window.app.getData('expenses');
        expenses = expenses.filter(e => e.id !== expenseId);
        window.app.saveData('expenses', expenses);
        loadExpensesData();
        window.app.showNotification('Expense deleted successfully!', 'success');
    }
}

function loadExpenseSummary() {
    const expenses = window.app.getData('expenses');
    const currentDate = new Date();
    const currentMonth = currentDate.getMonth();
    const currentYear = currentDate.getFullYear();
    
    // Monthly expenses
    const monthlyExpenses = expenses.filter(expense => {
        const expenseDate = new Date(expense.date);
        return expenseDate.getMonth() === currentMonth && expenseDate.getFullYear() === currentYear;
    });
    
    // Yearly expenses
    const yearlyExpenses = expenses.filter(expense => {
        const expenseDate = new Date(expense.date);
        return expenseDate.getFullYear() === currentYear;
    });
    
    // Calculate totals and breakdowns
    const monthlyTotal = monthlyExpenses.reduce((total, expense) => total + parseFloat(expense.amount || 0), 0);
    const yearlyTotal = yearlyExpenses.reduce((total, expense) => total + parseFloat(expense.amount || 0), 0);
    
    // Category breakdowns
    const monthlyBreakdown = getExpenseBreakdown(monthlyExpenses);
    const yearlyBreakdown = getExpenseBreakdown(yearlyExpenses);
    
    // Update summary display
    document.getElementById('monthly-expense-total').textContent = window.app.formatCurrency(monthlyTotal);
    document.getElementById('yearly-expense-total').textContent = window.app.formatCurrency(yearlyTotal);
    
    document.getElementById('monthly-expense-breakdown').innerHTML = 
        Object.entries(monthlyBreakdown).map(([category, amount]) => 
            `<div class="breakdown-item">${category}: ${window.app.formatCurrency(amount)}</div>`
        ).join('');
    
    document.getElementById('yearly-expense-breakdown').innerHTML = 
        Object.entries(yearlyBreakdown).map(([category, amount]) => 
            `<div class="breakdown-item">${category}: ${window.app.formatCurrency(amount)}</div>`
        ).join('');
}

function getExpenseBreakdown(expenses) {
    const breakdown = {};
    expenses.forEach(expense => {
        const category = expense.category || 'miscellaneous';
        breakdown[category] = (breakdown[category] || 0) + parseFloat(expense.amount || 0);
    });
    return breakdown;
}

function exportExpenses() {
    const expenses = window.app.getData('expenses');
    
    if (expenses.length === 0) {
        window.app.showNotification('No expenses to export', 'error');
        return;
    }
    
    const exportData = expenses.map(expense => ({
        'Date': expense.date,
        'Office': expense.office || 'Main Office',
        'Category': expense.category,
        'Description': expense.description,
        'Amount': expense.amount,
        'Has Receipt': expense.receipt ? 'Yes' : 'No',
        'Notes': expense.notes || ''
    }));
    
    const currentDate = new Date().toISOString().split('T')[0];
    window.app.exportToCSV(exportData, `expenses-${currentDate}.csv`);
    window.app.showNotification('Expenses exported successfully!', 'success');
}

// Add CSS for expense summary styles
const expenseStyles = `
    <style>
        .expense-summary {
            background: var(--white);
            padding: 1.5rem;
            border-radius: var(--border-radius);
            box-shadow: var(--shadow);
            margin-top: 2rem;
        }
        
        .expense-summary h3 {
            color: var(--primary-teal);
            margin-bottom: 1rem;
        }
        
        .summary-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 1.5rem;
        }
        
        .summary-card {
            background: var(--light-gray);
            padding: 1.5rem;
            border-radius: var(--border-radius);
            border-left: 4px solid var(--primary-orange);
        }
        
        .summary-card h4 {
            color: var(--dark-gray);
            margin-bottom: 0.5rem;
            font-size: 1.1rem;
        }
        
        .summary-amount {
            font-size: 2rem;
            font-weight: 700;
            color: var(--primary-teal);
            margin-bottom: 1rem;
        }
        
        .summary-details {
            font-size: 0.9rem;
            color: #666;
        }
        
        .breakdown-item {
            margin-bottom: 0.25rem;
            display: flex;
            justify-content: space-between;
            padding: 0.25rem 0;
            border-bottom: 1px solid var(--medium-gray);
        }
        
        .breakdown-item:last-child {
            border-bottom: none;
        }
        
        .current-receipt {
            margin-top: 0.5rem;
            padding: 0.5rem;
            background: var(--light-gray);
            border-radius: var(--border-radius);
            font-size: 0.9rem;
            color: var(--success);
        }
    </style>
`;

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