
function showSection(sid) {
    var secs = document.querySelectorAll('.dashboard-section');
    for(var i=0;i<secs.length;i++) secs[i].classList.remove('active');
    var ts = document.getElementById(sid);
    if (ts) ts.classList.add('active');
    var navs = document.querySelectorAll('.nav-item');
    for(var i=0;i<navs.length;i++) navs[i].classList.remove('active');
    var an = document.querySelector(`[data-section="${sid}"]`);
    if (an) an.classList.add('active');
}

function filterOrders() {
    const filterValue = document.getElementById('orderStatusFilter').value;
    const searchTerm = document.getElementById('orderSearch').value.toLowerCase();
    const rows = document.querySelectorAll('.orders-table tbody tr');

    rows.forEach(row => {
        const status = row.getAttribute('data-status');
        const orderId = row.cells[0].textContent.toLowerCase();
        const customerName = row.cells[1].textContent.toLowerCase();
        const services = row.cells[2].textContent.toLowerCase();
        const amount = row.cells[3].textContent.toLowerCase();

        const matchesStatus = filterValue === '' || status === filterValue;
        const matchesSearch = searchTerm === '' ||
            orderId.includes(searchTerm) ||
            customerName.includes(searchTerm) ||
            services.includes(searchTerm) ||
            amount.includes(searchTerm);

        if (matchesStatus && matchesSearch) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });
}

function searchOrders() {
    filterOrders();
    showNotification('info', 'Search completed');
}

function resetOrders() {
    document.getElementById('orderStatusFilter').value = '';
    document.getElementById('orderSearch').value = '';
    filterOrders();
    showNotification('info', 'Filters reset');
}

function updateOrdersPerPage() {
    const perPage = document.getElementById('ordersPerPage').value;

    const rows = document.querySelectorAll('.orders-table tbody tr');

    if (perPage === 'all') {
        rows.forEach(row => {
            row.style.display = '';
        });
    } else {
        const perPageNum = parseInt(perPage);
        rows.forEach((row, index) => {
            if (index < perPageNum) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    }

    showNotification('info', `Showing ${perPage === 'all' ? 'all' : perPage} orders per page`);
}

function updateOrderStatus(orderId) {
    fetch(`../php/get_order_details.php?id=${orderId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const order = data.order;

                document.getElementById('order_id').value = order.id;
                document.getElementById('order_id_display').value = `#${order.id}`;
                document.getElementById('customer_name_display').value = order.customer_name || 'N/A';
                document.getElementById('services_display').value = order.service_names || 'N/A';
                document.getElementById('total_amount_display').value = `$${parseFloat(order.total_amount).toFixed(2)}`;
                document.getElementById('order_status').value = order.status;

                document.getElementById('orderModal').style.display = 'block';
            } else {
                showNotification('error', 'Error loading order details: ' + data.error);
            }
        })
        .catch(error => {
            showNotification('error', 'Error loading order details: ' + error);
        });
}

function closeOrderModal() {
    document.getElementById('orderModal').style.display = 'none';
    document.getElementById('orderForm').reset();
}

function cancelOrder(orderId) {
    showCancelOrderNotification(orderId);
}

function confirmCancelOrder(orderId) {
    fetch('../php/update_order_status.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            order_id: orderId,
            status: 'cancelled'
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('success', `Order #${orderId} has been cancelled`);
            refreshOrdersSection();
        } else {
            showNotification('error', 'Error cancelling order: ' + data.error);
        }
    })
    .catch(error => {
        showNotification('error', 'Error cancelling order: ' + error);
    });
    closeCancelOrderNotification();
}

function createOrdersChart() {
    const ctx = document.getElementById('ordersChart');
    if (!ctx) return;
    
    const chartData = window.chartData || {
        labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        data: [0, 0, 0, 0, 0, 0, 0]
    };
    
    const chartConfig = {
        labels: chartData.labels,
        datasets: [{
            label: 'Orders Count',
            data: chartData.data,
            backgroundColor: 'rgba(0, 170, 255, 0.2)',
            borderColor: 'rgba(0, 170, 255, 1)',
            borderWidth: 2,
            tension: 0.4,
            fill: true
        }]
    };
    
    new Chart(ctx, {
        type: 'line',
        data: chartConfig,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            aspectRatio: 2,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            },
            layout: {
                padding: {
                    top: 10,
                    bottom: 10
                }
            }
        }
    });
}

function loadRealNotifications() {
    fetch('../php/get_notifications.php')
    .then(response => response.json())
    .then(data => {
        if (data.success && data.notifications && data.notifications.length > 0) {
            const notificationsList = document.querySelector('.notifications-list');
            if (notificationsList) {
                notificationsList.innerHTML = '';
            }
            
            data.notifications.forEach(notification => {
                addNotification(notification.type, notification.title, notification.message);
            });
        }
    })
    .catch(error => {
    });
}

function updateStats() {
    fetch('../php/get_staff_stats.php')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            document.getElementById('total_staff_count').textContent = data.total_staff;
            document.getElementById('available_staff_count').textContent = data.available_staff;
        }
    })
    .catch(error => {
        console.error('Error updating staff stats:', error);
    });
}

function addNotification(type, title, message) {
    const notificationsList = document.querySelector('.notifications-list');
    if (!notificationsList) return;
    
    const notificationItem = document.createElement('div');
    notificationItem.className = `notification-item ${type}`;
    
    const icon = type === 'warning' ? 'fa-exclamation-triangle' : 'fa-info-circle';
    
    notificationItem.innerHTML = `
        <i class="fas ${icon}"></i>
        <div class="notification-content">
            <h4>${title}</h4>
            <p>${message}</p>
            <span class="notification-time">Now</span>
        </div>
    `;
    
    notificationsList.insertBefore(notificationItem, notificationsList.firstChild);
}

function updateDeliveryStatus(deliveryId, status) {
    console.log(`Updating delivery ${deliveryId} status to: ${status}`);
}

function addCustomer() {
    const name = prompt('Customer name:');
    const email = prompt('Email:');
    
    if (name && email) {
        alert(`Customer added: ${name}`);
        refreshCustomersSection();
    }
}

function deleteCustomer(customerId) {
    if (confirm('Are you sure you want to delete this customer?')) {
        alert(`Customer #${customerId} deleted`);
        refreshCustomersSection();
    }
}

function exportReport(type) {
    alert(`Exporting ${type} report...`);
}

function editPricing() {
    const currentDeliveryFee = document.getElementById('delivery_fee_value').textContent;
    const currentMinOrder = document.getElementById('min_order_value').textContent;
    
    showSettingsModal('Pricing Management', [
        {
            type: 'number',
            name: 'delivery_fee',
            label: 'Delivery Fee ($)',
            value: currentDeliveryFee,
            required: true
        },
        {
            type: 'number',
            name: 'min_order_amount',
            label: 'Minimum Order Amount ($)',
            value: currentMinOrder,
            required: true
        }
    ], async function(data) {
        const deliveryFeeUpdated = await updateSetting('delivery_fee', data.delivery_fee);
        const minOrderUpdated = await updateSetting('min_order_amount', data.min_order_amount);
        
        if (deliveryFeeUpdated && minOrderUpdated) {
            document.getElementById('delivery_fee_value').textContent = data.delivery_fee;
            document.getElementById('min_order_value').textContent = data.min_order_amount;
            showNotification('success', 'Pricing updated successfully!');
        }
    });
}

function manageStaff() {
    showStaffModal();
}

function addNewStaff(data) {
    if (data.name && data.phone && data.password) {
        fetch('../php/manage_staff.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                name: data.name,
                phone: data.phone,
                email: data.email || '',
                password: data.password,
                location: data.location || ''
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('success', `Staff member added successfully!`);
                showStaffList();
                updateStats();
            } else {
                showNotification('error', 'Error adding staff: ' + data.error);
            }
        })
        .catch(error => {
            showNotification('error', 'Error adding staff: ' + error);
        });
    } else {
        showNotification('error', 'Name, phone, and password are required fields');
    }
}


function updateStaffStatus() {
    const staffId = prompt('Enter staff ID:');
    const status = prompt('Enter new status (available/busy/offline):');
    
    if (staffId && status && ['available', 'busy', 'offline'].includes(status)) {
        fetch('../php/manage_staff.php', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                id: staffId,
                status: status
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('success', `Staff #${staffId} status updated to ${status}`);
                showStaffList();
                updateStats();
            } else {
                showNotification('error', 'Error updating staff: ' + data.error);
            }
        })
        .catch(error => {
            showNotification('error', 'Error updating staff: ' + error);
        });
    }
}

function editWorkingHours() {
    const currentStart = document.getElementById('work_start_value').textContent;
    const currentEnd = document.getElementById('work_end_value').textContent;
    
    showSettingsModal('Working Hours', [
        {
            type: 'time',
            name: 'working_hours_start',
            label: 'Start Time',
            value: currentStart,
            required: true
        },
        {
            type: 'time',
            name: 'working_hours_end',
            label: 'End Time',
            value: currentEnd,
            required: true
        }
    ], async function(data) {
        if (isValidTime(data.working_hours_start) && isValidTime(data.working_hours_end)) {
            const startUpdated = await updateSetting('working_hours_start', data.working_hours_start);
            const endUpdated = await updateSetting('working_hours_end', data.working_hours_end);
            
            if (startUpdated && endUpdated) {
                document.getElementById('work_start_value').textContent = data.working_hours_start;
                document.getElementById('work_end_value').textContent = data.working_hours_end;
                showNotification('success', 'Working hours updated successfully!');
            }
        } else {
            showNotification('error', 'Please enter valid time format (HH:MM)');
        }
    });
}

function editDeliverySettings() {
    const currentMaxTime = document.getElementById('max_delivery_value').textContent;
    
    showSettingsModal('Delivery Settings', [
        {
            type: 'number',
            name: 'max_delivery_time',
            label: 'Maximum Delivery Time (minutes)',
            value: currentMaxTime,
            required: true,
            min: 1
        }
    ], async function(data) {
        if (data.max_delivery_time && !isNaN(data.max_delivery_time) && data.max_delivery_time > 0) {
            const updated = await updateSetting('max_delivery_time', data.max_delivery_time);
            if (updated) {
                document.getElementById('max_delivery_value').textContent = data.max_delivery_time;
                showNotification('success', 'Delivery settings updated successfully!');
            }
        } else {
            showNotification('error', 'Please enter a valid number greater than 0');
        }
    });
}

function editContactInfo() {
    const currentPhone = document.getElementById('company_phone_value').textContent;
    const currentEmail = document.getElementById('company_email_value').textContent;
    
    showSettingsModal('Contact Information', [
        {
            type: 'tel',
            name: 'company_phone',
            label: 'Company Phone',
            value: currentPhone,
            required: true
        },
        {
            type: 'email',
            name: 'notification_email',
            label: 'Notification Email',
            value: currentEmail,
            required: true
        }
    ], async function(data) {
        if (data.company_phone && data.notification_email && isValidEmail(data.notification_email)) {
            const phoneUpdated = await updateSetting('company_phone', data.company_phone);
            const emailUpdated = await updateSetting('notification_email', data.notification_email);
            
            if (phoneUpdated && emailUpdated) {
                document.getElementById('company_phone_value').textContent = data.company_phone;
                document.getElementById('company_email_value').textContent = data.notification_email;
                showNotification('success', 'Contact information updated successfully!');
            }
        } else {
            showNotification('error', 'Please enter valid phone and email');
        }
    });
}

function editCompanyAddress() {
    const currentAddress = document.getElementById('company_address_value').textContent;
    
    showSettingsModal('Company Address', [
        {
            type: 'textarea',
            name: 'company_address',
            label: 'Company Address',
            value: currentAddress,
            required: true,
            rows: 3
        }
    ], async function(data) {
        if (data.company_address) {
            const updated = await updateSetting('company_address', data.company_address);
            if (updated) {
                document.getElementById('company_address_value').textContent = data.company_address;
                showNotification('success', 'Company address updated successfully!');
            }
        } else {
            showNotification('error', 'Please enter a valid address');
        }
    });
}

function updateSetting(key, value) {
    return fetch('../php/update_setting.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            setting_key: key,
            setting_value: value
        })
    })
    .then(async response => {
        const text = await response.text();
        try {
            const data = JSON.parse(text);
            if (data.success) {
                return true;
            } else {
                const errorMsg = data.error || 'Unknown error occurred';
                console.error('Error updating setting:', errorMsg);
                showNotification('error', 'Error updating setting: ' + errorMsg);
                return false;
            }
        } catch (e) {
            console.error('Invalid JSON response:', text);
            showNotification('error', 'Server returned an invalid response. Check console for details.');
            return false;
        }
    })
    .catch(error => {
        console.error('Network error:', error);
        showNotification('error', 'Network error: ' + error.message);
        return false;
    });
}

function isValidTime(time) {
    const timeRegex = /^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/;
    return timeRegex.test(time);
}

function isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

function showNotification(type, message) {
    const notification = document.createElement('div');
    notification.className = `notification-item ${type}`;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${type === 'success' ? '#d4edda' : '#f8d7da'};
        color: ${type === 'success' ? '#155724' : '#721c24'};
        padding: 15px 20px;
        border-radius: 5px;
        box-shadow: 0 4px 10px rgba(0,0,0,0.1);
        z-index: 1000;
        animation: slideIn 0.3s ease;
    `;
    
    notification.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'}"></i>
        ${message}
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.remove();
    }, 3000);
}

function updatePricing() {
    const newPrice = prompt('New price:');
    if (newPrice && !isNaN(newPrice)) {
        alert(`Price updated to: $${newPrice}`);
    }
}

function addEmployee() {
    const name = prompt('Employee name:');
    const role = prompt('Role:');
    
    if (name && role) {
        alert(`Employee added: ${name} - ${role}`);
    }
}

function updateWorkingHours() {
    const hours = prompt('Working hours (e.g., 8:00 - 17:00):');
    if (hours) {
        alert(`Working hours updated to: ${hours}`);
    }
}

document.addEventListener('DOMContentLoaded', function() {
        createOrdersChart();

    const navItems = document.querySelectorAll('.nav-item');
    navItems.forEach(item => {
        item.addEventListener('click', function(e) {
            const sectionId = this.getAttribute('data-section');
            if (sectionId) {
                e.preventDefault();
                showSection(sectionId);
            }
        });
    });

    const orderFilter = document.getElementById('orderStatusFilter');
    if (orderFilter) {
        orderFilter.addEventListener('change', filterOrders);
    }

    const orderSearch = document.getElementById('orderSearch');
    if (orderSearch) {
        orderSearch.addEventListener('input', filterOrders);
        orderSearch.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                searchOrders();
            }
        });
    }

    const ordersPerPage = document.getElementById('ordersPerPage');
    if (ordersPerPage) {
        ordersPerPage.addEventListener('change', updateOrdersPerPage);
    }

    const orderForm = document.getElementById('orderForm');
    if (orderForm) {
        orderForm.addEventListener('submit', function(e) {
            e.preventDefault();

            const formData = new FormData(this);
            const orderId = formData.get('order_id');
            const newStatus = formData.get('status');

            fetch('../php/update_order_status.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    order_id: orderId,
                    status: newStatus
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification('success', `Order #${orderId} status updated to ${newStatus}`);
                    closeOrderModal();
                    refreshOrdersSection();
                } else {
                    showNotification('error', 'Error updating order: ' + data.error);
                }
            })
            .catch(error => {
                showNotification('error', 'Error updating order: ' + error);
            });
        });
    }

    setInterval(updateStats, 30000);

    loadRealNotifications();
});

const Dashboard = {
    refreshData: function() {
        location.reload();
    },
    
    sendNotification: function(message) {
        if ('Notification' in window && Notification.permission === 'granted') {
            new Notification('Admin Dashboard', {
                body: message,
                icon: '/img/logo.png'
            });
        }
    },
    
    requestNotificationPermission: function() {
        if ('Notification' in window && Notification.permission === 'default') {
            Notification.requestPermission();
        }
    },
    

    exportData: function(format) {
        const data = {
            orders: document.querySelectorAll('.orders-table tbody tr').length,
            customers: document.querySelectorAll('.customers-table tbody tr').length,
            revenue: document.querySelector('.stat-number').textContent
        };
        
        if (format === 'json') {
            const blob = new Blob([JSON.stringify(data, null, 2)], {type: 'application/json'});
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'dashboard-data.json';
            a.click();
        }
    }
};

Dashboard.requestNotificationPermission();

function showSettingsModal(title, fields, callback) {
    const modal = document.getElementById('settingsModal');
    const modalTitle = document.getElementById('modalTitle');
    const modalFields = document.getElementById('modalFields');
    
    modalTitle.textContent = title;
    modalFields.innerHTML = '';
    
    fields.forEach(field => {
        const formGroup = document.createElement('div');
        formGroup.className = 'form-group';
        
        const label = document.createElement('label');
        label.textContent = field.label;
        if (field.required) label.innerHTML += ' <span style="color: red;">*</span>';
        
        let input;
        if (field.type === 'textarea') {
            input = document.createElement('textarea');
            input.rows = field.rows || 3;
        } else {
            input = document.createElement('input');
            input.type = field.type;
        }
        
        input.name = field.name;
        input.value = field.value || '';
        input.required = field.required || false;
        if (field.min) input.min = field.min;
        if (field.max) input.max = field.max;
        
        formGroup.appendChild(label);
        formGroup.appendChild(input);
        modalFields.appendChild(formGroup);
    });
    
    document.getElementById('settingsForm').onsubmit = function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        const data = {};
        fields.forEach(field => {
            data[field.name] = formData.get(field.name);
        });
        
        callback(data);
        closeModal();
    };
    
    modal.style.display = 'block';
}

function closeModal() {
    document.getElementById('settingsModal').style.display = 'none';
}

function showStaffModal() {
    const modal = document.getElementById('staffModal');
    if (modal) {
        modal.style.display = 'block';
        showStaffList();
    } else {
        console.error('Staff modal element not found');
    }
}

function closeStaffModal() {
    document.getElementById('staffModal').style.display = 'none';
}

function showAddStaffForm() {
    const staffContent = document.getElementById('staffContent');
    staffContent.innerHTML = `
        <form id="addStaffForm">
            <div class="form-group">
                <label>Staff Name <span style="color: red;">*</span></label>
                <input type="text" name="name" required>
            </div>
            <div class="form-group">
                <label>Phone Number <span style="color: red;">*</span></label>
                <input type="tel" name="phone" required>
            </div>
            <div class="form-group">
                <label>Email <span style="color: red;">*</span></label>
                <input type="email" name="email" required>
            </div>
            <div class="form-group">
                <label>Password <span style="color: red;">*</span></label>
                <input type="password" name="password" required minlength="6" placeholder="Minimum 6 characters">
                <small style="color: #666; display: block; margin-top: 5px;">This password will be used for staff login</small>
            </div>
            <div class="form-group">
                <label>Current Location</label>
                <input type="text" name="location" placeholder="e.g., Downtown Area">
            </div>
            <div class="modal-actions">
                <button type="button" class="btn btn-secondary" onclick="showStaffList()">Cancel</button>
                <button type="submit" class="btn btn-primary">Add Staff</button>
            </div>
        </form>
    `;
    
    document.getElementById('addStaffForm').onsubmit = function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        const data = {
            name: formData.get('name'),
            phone: formData.get('phone'),
            email: formData.get('email'),
            password: formData.get('password'),
            location: formData.get('location')
        };
        
        addNewStaff(data);
    };
}

function showStaffList() {
    const staffContent = document.getElementById('staffContent');
    
    if (!staffContent) {
        console.error('Staff content element not found');
        return;
    }
    
    staffContent.innerHTML = `
        <div class="text-center py-4">
            <i class="fas fa-spinner fa-spin fa-2x"></i>
            <p class="mt-2">Loading staff data...</p>
        </div>
    `;

    fetch('../php/manage_staff.php')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data) {
                if (data.data.length === 0) {
                    staffContent.innerHTML = `
                        <div class="text-center py-4">
                            <i class="fas fa-users-slash fa-2x text-muted"></i>
                            <p class="mt-2">No staff members registered</p>
                        </div>
                    `;
                    return;
                }

                let staffHTML = '<div class="staff-list">';

                data.data.forEach(staff => {
                    let statusClass = 'status-offline';
                    let statusText = 'Offline';
                    
                    if (staff.status === 'available') {
                        statusClass = 'status-available';
                        statusText = 'Available';
                    } else if (staff.status === 'busy') {
                        statusClass = 'status-busy';
                        statusText = 'Busy';
                    }

                    staffHTML += `
                        <div class="staff-item">
                            <div class="staff-info">
                                <h4>${staff.name || 'Not specified'}</h4>
                                <p>${staff.phone || ''} ${staff.phone && staff.location ? '•' : ''} ${staff.location || ''}</p>
                            </div>
                            <div class="staff-status">
                                <span class="status-badge ${statusClass}">${statusText}</span>
                                <div class="staff-actions-small">
                                    <button class="btn-small btn-edit" onclick="editStaffStatus(${staff.id})" title="Edit Status">
                                        <i class="fas fa-edit"></i> Status
                                    </button>
                                    <button class="btn-small btn-warning" onclick="resetStaffPassword(${staff.id})" title="Reset Password">
                                        <i class="fas fa-key"></i> Password
                                    </button>
                                    <button class="btn-small btn-delete" onclick="deleteStaff(${staff.id})" title="Delete Staff">
                                        <i class="fas fa-trash"></i> Delete
                                    </button>
                                </div>
                            </div>
                        </div>
                    `;
                });

                staffHTML += '</div>';
                staffContent.innerHTML = staffHTML;
            } else {
                throw new Error(data.error || 'Failed to load staff data');
            }
        })
        .catch(error => {
            console.error('Error loading staff:', error);
            staffContent.innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i>
                    An error occurred while loading staff data
                </div>
            `;
        });
}

function editStaffStatus(staffId) {
    showStaffStatusNotification(staffId);
}

function confirmStaffStatus(staffId, status) {
    fetch('../php/manage_staff.php', {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            id: staffId,
            status: status
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('success', `Staff status updated to ${status}`);
            showStaffList();
            updateStats();
        } else {
            showNotification('error', 'Error updating staff: ' + data.error);
        }
    })
    .catch(error => {
        showNotification('error', 'Error updating staff: ' + error);
    });
    closeStaffStatusNotification();
}

function resetStaffPassword(staffId) {
    showStaffPasswordNotification(staffId);
}

function confirmStaffPassword(staffId, newPassword) {
    if (newPassword && newPassword.length >= 6) {
        fetch('../php/manage_staff.php', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                id: staffId,
                action: 'update_password',
                password: newPassword
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('success', 'Staff password updated successfully!');
            } else {
                showNotification('error', 'Error updating password: ' + data.error);
            }
        })
        .catch(error => {
            showNotification('error', 'Error updating password: ' + error);
        });
    } else {
        showNotification('error', 'Password must be at least 6 characters long');
    }
    closeStaffPasswordNotification();
}

function deleteStaff(staffId) {
    showDeleteStaffNotification(staffId);
}

function confirmDeleteStaff(staffId) {
    fetch('../php/manage_staff.php', {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ id: staffId })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('success', 'Staff member deleted successfully!');
            showStaffList();
            updateStats();
        } else {
            showNotification('error', 'Error deleting staff: ' + data.error);
        }
    })
    .catch(error => {
        showNotification('error', 'Error deleting staff: ' + error);
    });
    closeDeleteStaffNotification();
}

function manageServices() {
    document.getElementById('servicesModal').style.display = 'block';
    showServicesList();
}

function closeServicesModal() {
    document.getElementById('servicesModal').style.display = 'none';
}

function showServicesList() {
    const servicesContent = document.getElementById('servicesContent');
    
    servicesContent.innerHTML = `
        <div class="text-center py-4">
            <i class="fas fa-spinner fa-spin fa-2x"></i>
            <p class="mt-2">Loading services...</p>
        </div>
    `;

    fetch('../php/manage_services.php')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data) {
                if (data.data.length === 0) {
                    servicesContent.innerHTML = `
                        <div class="text-center py-4">
                            <i class="fas fa-box-open fa-2x text-muted"></i>
                            <p class="mt-2">No services available</p>
                        </div>
                    `;
                    return;
                }

                let servicesHTML = '<div class="services-list" style="display: grid; gap: 15px;">';

                data.data.forEach(service => {
                    const imageUrl = service.image ? `/img/${service.image}` : '/img/default-service.png';
                    servicesHTML += `
                        <div class="service-item" style="border: 1px solid #ddd; border-radius: 8px; padding: 15px; display: flex; gap: 15px; align-items: center;">
                            <div class="service-image" style="width: 80px; height: 80px; border-radius: 8px; overflow: hidden; flex-shrink: 0;">
                                <img src="${imageUrl}" alt="${service.name}" style="width: 100%; height: 100%; object-fit: cover;" onerror="this.src='/img/default-service.png'">
                            </div>
                            <div class="service-info" style="flex: 1;">
                                <h4 style="margin: 0 0 5px 0;">${service.name}</h4>
                                <p style="margin: 0 0 5px 0; color: #666; font-size: 14px;">${service.description || 'No description'}</p>
                                <div style="display: flex; gap: 15px; font-size: 14px;">
                                    <span><strong>Price:</strong> SAR ${parseFloat(service.price).toFixed(2)}</span>
                                    <span><strong>Category:</strong> ${service.category || 'N/A'}</span>
                                </div>
                            </div>
                            <div class="service-actions" style="display: flex; flex-direction: column; gap: 8px;">
                                <button class="btn-small btn-edit" onclick="editService(${service.id})" style="padding: 6px 12px; font-size: 13px;">
                                    <i class="fas fa-edit"></i> Edit
                                </button>
                                <button class="btn-small btn-delete" onclick="deleteService(${service.id})" style="padding: 6px 12px; font-size: 13px;">
                                    <i class="fas fa-trash"></i> Delete
                                </button>
                            </div>
                        </div>
                    `;
                });

                servicesHTML += '</div>';
                servicesContent.innerHTML = servicesHTML;
            } else {
                throw new Error(data.error || 'Failed to load services');
            }
        })
        .catch(error => {
            console.error('Error loading services:', error);
            servicesContent.innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i>
                    An error occurred while loading services
                </div>
            `;
        });
}

function showAddServiceForm() {
    const servicesContent = document.getElementById('servicesContent');
    servicesContent.innerHTML = `
        <form id="addServiceForm" enctype="multipart/form-data">
            <div class="form-group">
                <label>Service Name <span style="color: red;">*</span></label>
                <input type="text" name="name" required>
            </div>
            <div class="form-group">
                <label>Description</label>
                <textarea name="description" rows="3"></textarea>
            </div>
            <div class="form-group">
                <label>Price ($) <span style="color: red;">*</span></label>
                <input type="number" name="price" step="0.01" min="0" required>
            </div>
            <div class="form-group">
                <label>Category</label>
                <select name="category">
                    <option value="basic">Basic</option>
                    <option value="specialized">Specialized</option>
                    <option value="household">Household</option>
                    <option value="premium">Premium</option>
                </select>
            </div>
            <div class="form-group">
                <label>Service Image</label>
                <input type="file" name="image" accept="image/*" id="serviceImage">
                <small style="color: #666; display: block; margin-top: 5px;">Recommended: 800x600px, Max 2MB</small>
                <div id="imagePreview" style="margin-top: 10px; display: none;">
                    <img id="previewImg" style="max-width: 200px; border-radius: 8px; border: 1px solid #ddd;">
                </div>
            </div>
            <div class="modal-actions" style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
                <button type="button" class="btn btn-secondary" onclick="showServicesList()">Cancel</button>
                <button type="submit" class="btn btn-primary">Add Service</button>
            </div>
        </form>
    `;
    
    document.getElementById('serviceImage').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('imagePreview').style.display = 'block';
                document.getElementById('previewImg').src = e.target.result;
            };
            reader.readAsDataURL(file);
        }
    });
    
    document.getElementById('addServiceForm').onsubmit = function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        
        fetch('../php/manage_services.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('success', 'Service added successfully!');
                showServicesList();
                if (document.getElementById('total_services_count')) {
                    const currentCount = parseInt(document.getElementById('total_services_count').textContent);
                    document.getElementById('total_services_count').textContent = currentCount + 1;
                }
            } else {
                showNotification('error', 'Error adding service: ' + data.error);
            }
        })
        .catch(error => {
            showNotification('error', 'Error adding service: ' + error);
        });
    };
}

function editService(serviceId) {
    fetch(`../php/manage_services.php?id=${serviceId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data) {
                const service = data.data;
                const servicesContent = document.getElementById('servicesContent');
                
                servicesContent.innerHTML = `
                    <form id="editServiceForm" enctype="multipart/form-data">
                        <input type="hidden" name="id" value="${service.id}">
                        <div class="form-group">
                            <label>Service Name <span style="color: red;">*</span></label>
                            <input type="text" name="name" value="${service.name}" required>
                        </div>
                        <div class="form-group">
                            <label>Description</label>
                            <textarea name="description" rows="3">${service.description || ''}</textarea>
                        </div>
                        <div class="form-group">
                            <label>Price (SAR) <span style="color: red;">*</span></label>
                            <input type="number" name="price" step="0.01" min="0" value="${service.price}" required>
                        </div>
                        <div class="form-group">
                            <label>Category</label>
                            <select name="category">
                                <option value="basic" ${service.category === 'basic' ? 'selected' : ''}>Basic</option>
                                <option value="specialized" ${service.category === 'specialized' ? 'selected' : ''}>Specialized</option>
                                <option value="household" ${service.category === 'household' ? 'selected' : ''}>Household</option>
                                <option value="premium" ${service.category === 'premium' ? 'selected' : ''}>Premium</option>
                            </select>
                        </div>
                        ${service.image ? `
                        <div class="form-group">
                            <label>Current Image</label>
                            <div style="margin-bottom: 10px;">
                                <img src="/img/${service.image}" style="max-width: 200px; border-radius: 8px; border: 1px solid #ddd;" onerror="this.style.display='none'">
                            </div>
                        </div>
                        ` : ''}
                        <div class="form-group">
                            <label>Change Image (optional)</label>
                            <input type="file" name="image" accept="image/*" id="serviceImageEdit">
                            <small style="color: #666; display: block; margin-top: 5px;">Leave empty to keep current image</small>
                            <div id="imagePreviewEdit" style="margin-top: 10px; display: none;">
                                <img id="previewImgEdit" style="max-width: 200px; border-radius: 8px; border: 1px solid #ddd;">
                            </div>
                        </div>
                        <div class="modal-actions" style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
                            <button type="button" class="btn btn-secondary" onclick="showServicesList()">Cancel</button>
                            <button type="submit" class="btn btn-primary">Update Service</button>
                        </div>
                    </form>
                `;
                
                const imageInput = document.getElementById('serviceImageEdit');
                if (imageInput) {
                    imageInput.addEventListener('change', function(e) {
                        const file = e.target.files[0];
                        if (file) {
                            const reader = new FileReader();
                            reader.onload = function(e) {
                                document.getElementById('imagePreviewEdit').style.display = 'block';
                                document.getElementById('previewImgEdit').src = e.target.result;
                            };
                            reader.readAsDataURL(file);
                        }
                    });
                }
                
                document.getElementById('editServiceForm').onsubmit = function(e) {
                    e.preventDefault();
                    const formData = new FormData(this);
                    
                    fetch('../php/manage_services.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            showNotification('success', 'Service updated successfully!');
                            showServicesList();
                        } else {
                            showNotification('error', 'Error updating service: ' + data.error);
                        }
                    })
                    .catch(error => {
                        showNotification('error', 'Error updating service: ' + error);
                    });
                };
            } else {
                showNotification('error', 'Error loading service details');
            }
        })
        .catch(error => {
            showNotification('error', 'Error loading service: ' + error);
        });
}

function deleteService(serviceId) {
    if (confirm('Are you sure you want to delete this service? This action cannot be undone.')) {
        fetch('../php/manage_services.php', {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ id: serviceId })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('success', 'Service deleted successfully!');
                showServicesList();
                if (document.getElementById('total_services_count')) {
                    const currentCount = parseInt(document.getElementById('total_services_count').textContent);
                    document.getElementById('total_services_count').textContent = Math.max(0, currentCount - 1);
                }
            } else {
                showNotification('error', 'Error deleting service: ' + data.error);
            }
        })
        .catch(error => {
            showNotification('error', 'Error deleting service: ' + error);
        });
    }
}

function manageExpenses() {
    document.getElementById('expensesModal').style.display = 'block';
    showExpensesList();
}

function closeExpensesModal() {
    document.getElementById('expensesModal').style.display = 'none';
}

function showExpensesList() {
    const expensesContent = document.getElementById('expensesContent');
    
    expensesContent.innerHTML = `
        <div class="text-center py-4">
            <i class="fas fa-spinner fa-spin fa-2x"></i>
            <p class="mt-2">Loading expenses...</p>
        </div>
    `;

    fetch('../php/manage_expenses.php')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data) {
                if (data.data.length === 0) {
                    expensesContent.innerHTML = `
                        <div class="text-center py-4">
                            <i class="fas fa-receipt fa-2x text-muted"></i>
                            <p class="mt-2">No expenses recorded</p>
                        </div>
                    `;
                    return;
                }

                let expensesHTML = '<div class="expenses-list" style="display: grid; gap: 15px;">';

                data.data.forEach(expense => {
                    const categoryIcons = {
                        'materials': 'fa-box',
                        'salaries': 'fa-users',
                        'fuel': 'fa-gas-pump',
                        'utilities': 'fa-bolt',
                        'maintenance': 'fa-tools',
                        'other': 'fa-ellipsis-h'
                    };
                    
                    const icon = categoryIcons[expense.category] || 'fa-receipt';
                    
                    expensesHTML += `
                        <div class="expense-item-detailed" style="border: 1px solid #ddd; border-radius: 8px; padding: 15px; display: flex; gap: 15px; align-items: center;">
                            <div class="expense-icon" style="width: 50px; height: 50px; border-radius: 50%; background: #dc3545; color: white; display: flex; align-items: center; justify-content: center;">
                                <i class="fas ${icon}"></i>
                            </div>
                            <div class="expense-info" style="flex: 1;">
                                <h4 style="margin: 0 0 5px 0;">${expense.description}</h4>
                                <p style="margin: 0 0 5px 0; color: #666; font-size: 14px;">Category: ${expense.category.charAt(0).toUpperCase() + expense.category.slice(1)}</p>
                                <div style="display: flex; gap: 15px; font-size: 14px;">
                                    <span><strong>Amount:</strong> SAR ${parseFloat(expense.amount).toFixed(2)}</span>
                                    <span><strong>Date:</strong> ${expense.expense_date}</span>
                                    ${expense.receipt_number ? `<span><strong>Receipt:</strong> ${expense.receipt_number}</span>` : ''}
                                </div>
                            </div>
                            <div class="expense-actions" style="display: flex; flex-direction: column; gap: 8px;">
                                <button class="btn-small btn-edit" onclick="editExpense(${expense.id})" style="padding: 6px 12px; font-size: 13px;">
                                    <i class="fas fa-edit"></i> Edit
                                </button>
                                <button class="btn-small btn-delete" onclick="deleteExpense(${expense.id})" style="padding: 6px 12px; font-size: 13px;">
                                    <i class="fas fa-trash"></i> Delete
                                </button>
                            </div>
                        </div>
                    `;
                });

                expensesHTML += '</div>';
                expensesContent.innerHTML = expensesHTML;
            } else {
                throw new Error(data.error || 'Failed to load expenses');
            }
        })
        .catch(error => {
            console.error('Error loading expenses:', error);
            expensesContent.innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i>
                    An error occurred while loading expenses
                </div>
            `;
        });
}

function showAddExpenseForm() {
    const expensesContent = document.getElementById('expensesContent');
    expensesContent.innerHTML = `
        <form id="addExpenseForm">
            <div class="form-group">
                <label>Category <span style="color: red;">*</span></label>
                <select name="category" required>
                    <option value="materials">Materials</option>
                    <option value="salaries">Salaries</option>
                    <option value="fuel">Fuel</option>
                    <option value="utilities">Utilities</option>
                    <option value="maintenance">Maintenance</option>
                    <option value="other">Other</option>
                </select>
            </div>
            <div class="form-group">
                <label>Description <span style="color: red;">*</span></label>
                <input type="text" name="description" required>
            </div>
            <div class="form-group">
                <label>Amount ($) <span style="color: red;">*</span></label>
                <input type="number" name="amount" step="0.01" min="0" required>
            </div>
            <div class="form-group">
                <label>Expense Date <span style="color: red;">*</span></label>
                <input type="date" name="expense_date" required>
            </div>
            <div class="form-group">
                <label>Receipt Number</label>
                <input type="text" name="receipt_number">
            </div>
            <div class="form-group">
                <label>Notes</label>
                <textarea name="notes" rows="3"></textarea>
            </div>
            <div class="modal-actions" style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
                <button type="button" class="btn btn-secondary" onclick="showExpensesList()">Cancel</button>
                <button type="submit" class="btn btn-primary">Add Expense</button>
            </div>
        </form>
    `;
    
    document.querySelector('input[name="expense_date"]').value = new Date().toISOString().split('T')[0];
    
    document.getElementById('addExpenseForm').onsubmit = function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        
        fetch('../php/manage_expenses.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('success', 'Expense added successfully!');
                showExpensesList();
                updateMonthlyExpenses();
            } else {
                showNotification('error', 'Error adding expense: ' + data.error);
            }
        })
        .catch(error => {
            showNotification('error', 'Error adding expense: ' + error);
        });
    };
}

function editExpense(expenseId) {
    fetch(`../php/manage_expenses.php?id=${expenseId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data) {
                const expense = data.data;
                const expensesContent = document.getElementById('expensesContent');
                
                expensesContent.innerHTML = `
                    <form id="editExpenseForm">
                        <input type="hidden" name="id" value="${expense.id}">
                        <div class="form-group">
                            <label>Category <span style="color: red;">*</span></label>
                            <select name="category" required>
                                <option value="materials" ${expense.category === 'materials' ? 'selected' : ''}>Materials</option>
                                <option value="salaries" ${expense.category === 'salaries' ? 'selected' : ''}>Salaries</option>
                                <option value="fuel" ${expense.category === 'fuel' ? 'selected' : ''}>Fuel</option>
                                <option value="utilities" ${expense.category === 'utilities' ? 'selected' : ''}>Utilities</option>
                                <option value="maintenance" ${expense.category === 'maintenance' ? 'selected' : ''}>Maintenance</option>
                                <option value="other" ${expense.category === 'other' ? 'selected' : ''}>Other</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Description <span style="color: red;">*</span></label>
                            <input type="text" name="description" value="${expense.description}" required>
                        </div>
                        <div class="form-group">
                            <label>Amount ($) <span style="color: red;">*</span></label>
                            <input type="number" name="amount" step="0.01" min="0" value="${expense.amount}" required>
                        </div>
                        <div class="form-group">
                            <label>Expense Date <span style="color: red;">*</span></label>
                            <input type="date" name="expense_date" value="${expense.expense_date}" required>
                        </div>
                        <div class="form-group">
                            <label>Receipt Number</label>
                            <input type="text" name="receipt_number" value="${expense.receipt_number || ''}">
                        </div>
                        <div class="form-group">
                            <label>Notes</label>
                            <textarea name="notes" rows="3">${expense.notes || ''}</textarea>
                        </div>
                        <div class="modal-actions" style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
                            <button type="button" class="btn btn-secondary" onclick="showExpensesList()">Cancel</button>
                            <button type="submit" class="btn btn-primary">Update Expense</button>
                        </div>
                    </form>
                `;
                
                document.getElementById('editExpenseForm').onsubmit = function(e) {
                    e.preventDefault();
                    const formData = new FormData(this);
                    
                    fetch('../php/manage_expenses.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            showNotification('success', 'Expense updated successfully!');
                            showExpensesList();
                            updateMonthlyExpenses();
                        } else {
                            showNotification('error', 'Error updating expense: ' + data.error);
                        }
                    })
                    .catch(error => {
                        showNotification('error', 'Error updating expense: ' + error);
                    });
                };
            } else {
                showNotification('error', 'Error loading expense details');
            }
        })
        .catch(error => {
            showNotification('error', 'Error loading expense: ' + error);
        });
}

function deleteExpense(expenseId) {
    if (confirm('Are you sure you want to delete this expense? This action cannot be undone.')) {
        fetch('../php/manage_expenses.php', {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ id: expenseId })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('success', 'Expense deleted successfully!');
                showExpensesList();
                updateMonthlyExpenses();
            } else {
                showNotification('error', 'Error deleting expense: ' + data.error);
            }
        })
        .catch(error => {
            showNotification('error', 'Error deleting expense: ' + error);
        });
    }
}

function updateMonthlyExpenses() {
    fetch('../php/manage_expenses.php')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data) {
                const currentMonth = new Date().getMonth() + 1;
                const currentYear = new Date().getFullYear();
                
                const monthlyTotal = data.data
                    .filter(expense => {
                        const expenseDate = new Date(expense.expense_date);
                        return expenseDate.getMonth() + 1 === currentMonth && expenseDate.getFullYear() === currentYear;
                    })
                    .reduce((total, expense) => total + parseFloat(expense.amount), 0);
                
                const monthlyExpensesElement = document.getElementById('monthly_expenses');
                if (monthlyExpensesElement) {
                    monthlyExpensesElement.textContent = `$${monthlyTotal.toFixed(2)}`;
                }
            }
        })
        .catch(error => {
            console.error('Error updating monthly expenses:', error);
        });
}

function showAddOfferForm() {
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.style.display = 'block';
    modal.innerHTML = `
        <div class="modal-content" style="max-height: 90vh; overflow-y: auto; max-width: 600px; margin: 2% auto;">
            <div class="modal-header">
                <h3>Add New Offer</h3>
                <span class="close" onclick="this.closest('.modal').remove()">&times;</span>
            </div>
            <div class="modal-body" style="max-height: 70vh; overflow-y: auto; padding: 20px;">
                <form id="addOfferForm">
                    <div class="form-group">
                        <label>Offer Title <span style="color: red;">*</span></label>
                        <input type="text" name="title" required>
                    </div>
                    <div class="form-group">
                        <label>Description</label>
                        <textarea name="description" rows="3"></textarea>
                    </div>
                    <div class="form-group">
                        <label>Discount Type <span style="color: red;">*</span></label>
                        <select name="discount_type" required>
                            <option value="percentage">Percentage</option>
                            <option value="fixed">Fixed Amount</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Discount Value <span style="color: red;">*</span></label>
                        <input type="number" name="discount_value" step="0.01" min="0" required>
                    </div>
                    <div class="form-group">
                        <label>Minimum Order Amount</label>
                        <input type="number" name="min_order_amount" step="0.01" min="0" value="0">
                    </div>
                    <div class="form-group">
                        <label>Maximum Discount Amount</label>
                        <input type="number" name="max_discount_amount" step="0.01" min="0">
                    </div>
                    <div class="form-group">
                        <label>Start Date <span style="color: red;">*</span></label>
                        <input type="date" name="start_date" required>
                    </div>
                    <div class="form-group">
                        <label>End Date <span style="color: red;">*</span></label>
                        <input type="date" name="end_date" required>
                    </div>
                    <div class="form-group">
                        <label>Target Customers</label>
                        <select name="target_customers">
                            <option value="all">All Customers</option>
                            <option value="new">New Customers</option>
                            <option value="normal">Normal Customers</option>
                            <option value="regular">Regular Customers</option>
                            <option value="subscribed">Subscribed Customers</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Usage Limit</label>
                        <input type="number" name="usage_limit" min="1">
                        <small>Leave empty for unlimited usage</small>
                    </div>
                    <div class="modal-actions">
                        <button type="button" class="btn btn-secondary" onclick="this.closest('.modal').remove()">Cancel</button>
                        <button type="submit" class="btn btn-primary">Add Offer</button>
                    </div>
                </form>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    const today = new Date().toISOString().split('T')[0];
    const nextWeek = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
    modal.querySelector('input[name="start_date"]').value = today;
    modal.querySelector('input[name="end_date"]').value = nextWeek;
    
    modal.querySelector('#addOfferForm').onsubmit = function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        
        fetch('../php/manage_offers.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('success', 'Offer added successfully!');
                modal.remove();
                refreshOffersSection();
            } else {
                showNotification('error', 'Error adding offer: ' + data.error);
            }
        })
        .catch(error => {
            showNotification('error', 'Error adding offer: ' + error);
        });
    };
}

function editOffer(offerId) {
    fetch(`../php/manage_offers.php?id=${offerId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data) {
                const offer = data.data;
                showEditOfferModal(offer);
            } else {
                showNotification('error', 'Error loading offer details');
            }
        })
        .catch(error => {
            showNotification('error', 'Error loading offer: ' + error);
        });
}

function showEditOfferModal(offer) {
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.style.display = 'block';
    modal.innerHTML = `
        <div class="modal-content" style="max-height: 90vh; overflow-y: auto; max-width: 600px; margin: 2% auto;">
            <div class="modal-header">
                <h3>Edit Offer</h3>
                <span class="close" onclick="this.closest('.modal').remove()">&times;</span>
            </div>
            <div class="modal-body" style="max-height: 70vh; overflow-y: auto; padding: 20px;">
                <form id="editOfferForm">
                    <input type="hidden" name="id" value="${offer.id}">
                    <div class="form-group">
                        <label>Offer Title <span style="color: red;">*</span></label>
                        <input type="text" name="title" value="${offer.title}" required>
                    </div>
                    <div class="form-group">
                        <label>Description</label>
                        <textarea name="description" rows="3">${offer.description || ''}</textarea>
                    </div>
                    <div class="form-group">
                        <label>Discount Type <span style="color: red;">*</span></label>
                        <select name="discount_type" required>
                            <option value="percentage" ${offer.discount_type === 'percentage' ? 'selected' : ''}>Percentage</option>
                            <option value="fixed" ${offer.discount_type === 'fixed' ? 'selected' : ''}>Fixed Amount</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Discount Value <span style="color: red;">*</span></label>
                        <input type="number" name="discount_value" step="0.01" min="0" value="${offer.discount_value}" required>
                    </div>
                    <div class="form-group">
                        <label>Minimum Order Amount</label>
                        <input type="number" name="min_order_amount" step="0.01" min="0" value="${offer.min_order_amount || 0}">
                    </div>
                    <div class="form-group">
                        <label>Maximum Discount Amount</label>
                        <input type="number" name="max_discount_amount" step="0.01" min="0" value="${offer.max_discount_amount || ''}">
                    </div>
                    <div class="form-group">
                        <label>Start Date <span style="color: red;">*</span></label>
                        <input type="date" name="start_date" value="${offer.start_date}" required>
                    </div>
                    <div class="form-group">
                        <label>End Date <span style="color: red;">*</span></label>
                        <input type="date" name="end_date" value="${offer.end_date}" required>
                    </div>
                    <div class="form-group">
                        <label>Target Customers</label>
                        <select name="target_customers">
                            <option value="all" ${offer.target_customers === 'all' ? 'selected' : ''}>All Customers</option>
                            <option value="new" ${offer.target_customers === 'new' ? 'selected' : ''}>New Customers</option>
                            <option value="normal" ${offer.target_customers === 'normal' ? 'selected' : ''}>Normal Customers</option>
                            <option value="regular" ${offer.target_customers === 'regular' ? 'selected' : ''}>Regular Customers</option>
                            <option value="subscribed" ${offer.target_customers === 'subscribed' ? 'selected' : ''}>Subscribed Customers</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Usage Limit</label>
                        <input type="number" name="usage_limit" min="1" value="${offer.usage_limit || ''}">
                        <small>Leave empty for unlimited usage</small>
                    </div>
                    <div class="modal-actions">
                        <button type="button" class="btn btn-secondary" onclick="this.closest('.modal').remove()">Cancel</button>
                        <button type="submit" class="btn btn-primary">Update Offer</button>
                    </div>
                </form>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    modal.querySelector('#editOfferForm').onsubmit = function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        
        fetch('../php/manage_offers.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('success', 'Offer updated successfully!');
                modal.remove();
                refreshOffersSection();
            } else {
                showNotification('error', 'Error updating offer: ' + data.error);
            }
        })
        .catch(error => {
            showNotification('error', 'Error updating offer: ' + error);
        });
    };
}

function deleteOffer(offerId) {
    showDeleteOfferNotification(offerId);
}

function confirmDeleteOffer(offerId) {
    fetch('../php/manage_offers.php', {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ id: offerId })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('success', 'Offer deleted successfully!');
            refreshOffersSection();
        } else {
            showNotification('error', 'Error deleting offer: ' + data.error);
        }
    })
    .catch(error => {
        showNotification('error', 'Error deleting offer: ' + error);
    });
    closeDeleteOfferNotification();
}

function toggleOfferStatus(offerId, newStatus) {
    fetch('../php/manage_offers.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            id: offerId,
            status: newStatus,
            action: 'toggle_status'
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('success', `Offer ${newStatus === 'active' ? 'activated' : 'deactivated'} successfully!`);
            refreshOffersSection();
        } else {
            showNotification('error', 'Error updating offer status: ' + data.error);
        }
    })
    .catch(error => {
        showNotification('error', 'Error updating offer status: ' + error);
    });
}

function sendSingleOffer(offerId, offerTitle, targetCustomers) {
    if (confirm(`Send "${offerTitle}" notification to ${targetCustomers} customers?`)) {
        const btn = event.target;
        const originalText = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        btn.disabled = true;
        
        fetch('../php/manage_offers.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                action: 'send_single_offer',
                offer_id: offerId
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('success', `"${offerTitle}" sent to ${data.count || 0} ${targetCustomers} customers!`);
            } else {
                showNotification('error', 'Error sending notification: ' + data.error);
            }
        })
        .catch(error => {
            showNotification('error', 'Error sending notification: ' + error);
        })
        .finally(() => {
            btn.innerHTML = originalText;
            btn.disabled = false;
        });
    }
}

function refreshOrdersSection() {
    fetch('../php/get_admin_data.php?section=orders')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const ordersTableBody = document.querySelector('.orders-table tbody');
                if (ordersTableBody) {
                    ordersTableBody.innerHTML = '';
                    data.orders.forEach(order => {
                        const row = document.createElement('tr');
                        row.setAttribute('data-status', order.status);
                        
                        const statusText = {
                            'pending': 'Pending',
                            'processing': 'Processing', 
                            'ready': 'Ready',
                            'delivered': 'Delivered',
                            'cancelled': 'Cancelled'
                        };
                        
                        const actionButtons = order.status !== 'delivered' && order.status !== 'cancelled' 
                            ? `<button class="btn-small btn-danger" onclick="cancelOrder(${order.id})" style="background: #dc3545; margin-left: 5px;">
                                <i class="fas fa-times"></i>
                               </button>`
                            : '';
                        
                        row.innerHTML = `
                            <td>#${order.id}</td>
                            <td>${order.customer_name || 'N/A'}</td>
                            <td>${order.service_names || 'N/A'}</td>
                            <td>SAR ${parseFloat(order.total_amount).toFixed(2)}</td>
                            <td>
                                <span class="status-badge status-${order.status}">
                                    ${statusText[order.status] || order.status}
                                </span>
                            </td>
                            <td>${new Date(order.created_at).toLocaleString('en-CA', {year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit'})}</td>
                            <td>
                                <button class="btn-small" onclick="updateOrderStatus(${order.id})">
                                    <i class="fas fa-edit"></i>
                                </button>
                                ${actionButtons}
                            </td>
                        `;
                        ordersTableBody.appendChild(row);
                    });
                }
            }
        })
        .catch(error => {
            console.error('Error refreshing orders:', error);
        });
}

function refreshOffersSection() {
    fetch('../php/get_admin_data.php?section=offers')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const offersContainer = document.querySelector('.offers-list');
                if (offersContainer) {
                    offersContainer.innerHTML = '';
                    data.offers.forEach(offer => {
                        const offerDiv = document.createElement('div');
                        offerDiv.className = 'offer-item';
                        
                        const discountText = offer.discount_type === 'percentage' 
                            ? `${offer.discount_value}% off`
                            : `SAR ${parseFloat(offer.discount_value).toFixed(2)} off`;
                        
                        const conditions = [];
                        if (offer.min_order_amount > 0) {
                            conditions.push(`Min. order: SAR ${parseFloat(offer.min_order_amount).toFixed(2)}`);
                        }
                        if (offer.max_discount_amount) {
                            conditions.push(`Max. discount: SAR ${parseFloat(offer.max_discount_amount).toFixed(2)}`);
                        }
                        
                        const toggleButton = offer.status === 'active'
                            ? `<button class="btn-small btn-warning" onclick="toggleOfferStatus(${offer.id}, 'inactive')">
                                <i class="fas fa-pause"></i> Deactivate
                               </button>`
                            : `<button class="btn-small btn-success" onclick="toggleOfferStatus(${offer.id}, 'active')">
                                <i class="fas fa-play"></i> Activate
                               </button>`;
                        
                        offerDiv.innerHTML = `
                            <div class="offer-header">
                                <div class="offer-info">
                                    <h4>${offer.title}</h4>
                                    <p>${offer.description}</p>
                                </div>
                                <div class="offer-status">
                                    <span class="status-badge status-${offer.status}">
                                        ${offer.status.charAt(0).toUpperCase() + offer.status.slice(1)}
                                    </span>
                                </div>
                            </div>
                            <div class="offer-details">
                                <div class="offer-discount">
                                    <strong>Discount:</strong> ${discountText}
                                </div>
                                <div class="offer-conditions">
                                    ${conditions.join(' • ')}
                                </div>
                                <div class="offer-period">
                                    <span>Valid: ${offer.start_date} to ${offer.end_date}</span>
                                </div>
                                <div class="offer-target">
                                    <span>Target: ${offer.target_customers.charAt(0).toUpperCase() + offer.target_customers.slice(1)} customers</span>
                                </div>
                                ${offer.usage_limit ? `<div class="offer-usage">
                                    <span>Usage: ${offer.used_count || 0} / ${offer.usage_limit}</span>
                                </div>` : ''}
                            </div>
                            <div class="offer-actions">
                                <button class="btn-small" onclick="editOffer(${offer.id})">
                                    <i class="fas fa-edit"></i> Edit
                                </button>
                                <button class="btn-small btn-danger" onclick="deleteOffer(${offer.id})">
                                    <i class="fas fa-trash"></i> Delete
                                </button>
                                ${toggleButton}
                            </div>
                        `;
                        offersContainer.appendChild(offerDiv);
                    });
                    
                    if (data.stats) {
                        const activeOffersElement = document.querySelector('.offers-stats .stat-card:nth-child(1) .stat-number');
                        const totalOffersElement = document.querySelector('.offers-stats .stat-card:nth-child(2) .stat-number');
                        const inactiveOffersElement = document.querySelector('.offers-stats .stat-card:nth-child(3) .stat-number');
                        const expiredOffersElement = document.querySelector('.offers-stats .stat-card:nth-child(4) .stat-number');
                        
                        if (activeOffersElement) activeOffersElement.textContent = data.stats.active_offers;
                        if (totalOffersElement) totalOffersElement.textContent = data.stats.total_offers;
                        if (inactiveOffersElement) inactiveOffersElement.textContent = data.stats.inactive_offers;
                        if (expiredOffersElement) expiredOffersElement.textContent = data.stats.expired_offers;
                    }
                }
            }
        })
        .catch(error => {
            console.error('Error refreshing offers:', error);
        });
}

function refreshCustomersSection() {
    fetch('../php/get_admin_data.php?section=customers')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const customersTableBody = document.querySelector('.customers-table tbody');
                if (customersTableBody) {
                    customersTableBody.innerHTML = '';
                    data.customers.forEach(customer => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${customer.id}</td>
                            <td>${customer.name}</td>
                            <td>${customer.email}</td>
                            <td>
                                <span class="customer-type-${customer.customer_type.toLowerCase()}">
                                    ${customer.customer_type}
                                </span>
                            </td>
                            <td>
                                <span class="role-${customer.role}">
                                    ${customer.role.charAt(0).toUpperCase() + customer.role.slice(1)}
                                </span>
                            </td>
                            <td>${new Date(customer.created_at).toLocaleDateString('en-CA')}</td>
                            <td>${customer.order_count}</td>
                            <td>SAR ${parseFloat(customer.total_spent).toFixed(2)}</td>
                            <td>${new Date(customer.last_activity).toLocaleDateString('en-CA')}</td>
                        `;
                        customersTableBody.appendChild(row);
                    });
                }
                
                if (data.stats) {
                    const activeCustomersElement = document.querySelector('.customers-stats .stat-card:nth-child(1) .stat-number');
                    const totalCustomersElement = document.querySelector('.customers-stats .stat-card:nth-child(2) .stat-number');
                    
                    if (activeCustomersElement) activeCustomersElement.textContent = data.stats.active_customers;
                    if (totalCustomersElement) totalCustomersElement.textContent = data.stats.total_customers;
                }
            }
        })
        .catch(error => {
            console.error('Error refreshing customers:', error);
        });
}

function refreshReviewsSection() {
    fetch('../php/get_admin_data.php?section=reviews')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const reviewsList = document.querySelector('.reviews-list');
                if (reviewsList) {
                    reviewsList.innerHTML = '';
                    data.reviews.forEach(review => {
                        const reviewDiv = document.createElement('div');
                        reviewDiv.className = 'review-item';
                        
                        let stars = '';
                        for (let i = 1; i <= 5; i++) {
                            stars += `<i class="${i <= review.rating ? 'fas' : 'far'} fa-star"></i>`;
                        }
                        
                        reviewDiv.innerHTML = `
                            <div class="review-header">
                                <div class="customer-info">
                                    <h4>${review.customer_name || 'Unknown Customer'}</h4>
                                    <span class="order-info">Order #${review.order_number} - SAR ${parseFloat(review.total_amount).toFixed(2)}</span>
                                </div>
                                <div class="review-rating">
                                    ${stars}
                                    <span class="rating-text">${review.rating}/5</span>
                                </div>
                            </div>
                            <div class="review-content">
                                <p>${review.comment || 'No comment provided'}</p>
                            </div>
                            <div class="review-footer">
                                <span class="review-date">${new Date(review.created_at).toLocaleString('en-CA', {year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit'})}</span>
                            </div>
                        `;
                        reviewsList.appendChild(reviewDiv);
                    });
                }
                
                if (data.stats) {
                    const avgRatingElement = document.querySelector('.reviews-stats .stat-card:nth-child(1) .stat-number');
                    const totalReviewsElement = document.querySelector('.reviews-stats .stat-card:nth-child(2) .stat-number');
                    
                    if (avgRatingElement) avgRatingElement.textContent = `${parseFloat(data.stats.avg_rating || 0).toFixed(1)}/5`;
                    if (totalReviewsElement) totalReviewsElement.textContent = data.stats.total_reviews || 0;
                }
            }
        })
        .catch(error => {
            console.error('Error refreshing reviews:', error);
        });
}

function refreshSubscriptionsSection() {
    fetch('../php/get_admin_data.php?section=subscriptions')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const subscriptionsTableBody = document.querySelector('.subscriptions-table tbody');
                if (subscriptionsTableBody) {
                    subscriptionsTableBody.innerHTML = '';
                    data.subscriptions.forEach(subscription => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${subscription.customer_name}</td>
                            <td>${subscription.plan_name}</td>
                            <td>SAR ${parseFloat(subscription.price).toFixed(2)}</td>
                            <td>${new Date(subscription.start_date).toLocaleDateString('en-CA')}</td>
                            <td>${new Date(subscription.end_date).toLocaleDateString('en-CA')}</td>
                            <td>${subscription.usage_count} / ${subscription.max_usage}</td>
                            <td>
                                <span class="status-badge status-${subscription.status}">
                                    ${subscription.status === 'active' ? 'Active' : subscription.status}
                                </span>
                            </td>
                        `;
                        subscriptionsTableBody.appendChild(row);
                    });
                }
                
                if (data.stats) {
                    const activeSubsElement = document.querySelector('.subscriptions-stats .stat-card .stat-number');
                    if (activeSubsElement) activeSubsElement.textContent = data.stats.active_subscriptions;
                }
            }
        })
        .catch(error => {
            console.error('Error refreshing subscriptions:', error);
        });
}

function refreshDeliverySection() {
    fetch('../php/get_admin_data.php?section=delivery')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const deliveryTableBody = document.querySelector('.delivery-table tbody');
                if (deliveryTableBody) {
                    deliveryTableBody.innerHTML = '';
                    data.delivery_staff.forEach(staff => {
                        const row = document.createElement('tr');
                        
                        const statusText = {
                            'available': 'Available',
                            'busy': 'Busy',
                            'offline': 'Offline'
                        };
                        
                        let stars = '';
                        const rating = Math.round(staff.rating);
                        for (let i = 1; i <= 5; i++) {
                            stars += `<i class="${i <= rating ? 'fas' : 'far'} fa-star"></i>`;
                        }
                        
                        row.innerHTML = `
                            <td>${staff.name}</td>
                            <td>${staff.phone}</td>
                            <td>
                                <span class="status-badge status-${staff.status}">
                                    ${statusText[staff.status] || staff.status}
                                </span>
                            </td>
                            <td>${staff.total_deliveries}</td>
                            <td>${staff.average_delivery_time} min</td>
                            <td>
                                <div class="rating">
                                    ${stars}
                                </div>
                            </td>
                        `;
                        deliveryTableBody.appendChild(row);
                    });
                }
                
                if (data.stats) {
                    const availableStaffElement = document.querySelector('.delivery-stats .stat-card:nth-child(1) .stat-number');
                    const avgTimeElement = document.querySelector('.delivery-stats .stat-card:nth-child(2) .stat-number');
                    const totalStaffElement = document.querySelector('.delivery-stats .stat-card:nth-child(3) .stat-number');
                    
                    if (availableStaffElement) availableStaffElement.textContent = data.stats.available_staff;
                    if (avgTimeElement) avgTimeElement.textContent = `${Math.round(data.stats.avg_delivery_time)} min`;
                    if (totalStaffElement) totalStaffElement.textContent = data.stats.total_staff;
                }
            }
        })
        .catch(error => {
            console.error('Error refreshing delivery:', error);
        });
}

function refreshFinancialSection() {
    fetch('../php/get_admin_data.php?section=financial')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                if (data.stats) {
                    const totalRevenueElement = document.querySelector('.financial-grid .stat-card:nth-child(1) .stat-number');
                    const subscriptionRevenueElement = document.querySelector('.financial-grid .stat-card:nth-child(2) .stat-number');
                    const totalExpensesElement = document.querySelector('.financial-grid .stat-card:nth-child(3) .stat-number');
                    const netProfitElement = document.querySelector('.financial-grid .stat-card:nth-child(4) .stat-number');
                    
                    if (totalRevenueElement) totalRevenueElement.textContent = `SAR ${parseFloat(data.stats.total_revenue).toFixed(2)}`;
                    if (subscriptionRevenueElement) subscriptionRevenueElement.textContent = `SAR ${parseFloat(data.stats.subscription_revenue).toFixed(2)}`;
                    if (totalExpensesElement) totalExpensesElement.textContent = `SAR ${parseFloat(data.stats.total_expenses).toFixed(2)}`;
                    if (netProfitElement) {
                        const netProfit = data.stats.net_profit;
                        netProfitElement.textContent = `SAR ${parseFloat(netProfit).toFixed(2)}`;
                        netProfitElement.style.color = netProfit >= 0 ? '#28a745' : '#dc3545';
                    }
                }
                
                if (data.service_stats) {
                    const servicesGrid = document.querySelector('.services-grid');
                    if (servicesGrid) {
                        servicesGrid.innerHTML = '';
                        data.service_stats.forEach(service => {
                            const serviceDiv = document.createElement('div');
                            serviceDiv.className = 'service-revenue-item';
                            serviceDiv.innerHTML = `
                                <div class="service-info">
                                    <h5>${service.name}</h5>
                                    <p>SAR ${parseFloat(service.total_revenue || 0).toFixed(2)}</p>
                                </div>
                                <div class="service-details">
                                    <small>${service.order_count} orders</small>
                                </div>
                            `;
                            servicesGrid.appendChild(serviceDiv);
                        });
                    }
                }
                
                if (data.expense_categories) {
                    const expensesGrid = document.querySelector('.expenses-grid');
                    if (expensesGrid) {
                        expensesGrid.innerHTML = '';
                        data.expense_categories.forEach(category => {
                            const expenseDiv = document.createElement('div');
                            expenseDiv.className = 'expense-item';
                            expenseDiv.innerHTML = `
                                <div class="expense-info">
                                    <h5>${category.category.charAt(0).toUpperCase() + category.category.slice(1)}</h5>
                                    <p>SAR ${parseFloat(category.total_amount).toFixed(2)}</p>
                                </div>
                                <div class="expense-details">
                                    <small>${category.count} transactions</small>
                                </div>
                            `;
                            expensesGrid.appendChild(expenseDiv);
                        });
                    }
                }
            }
        })
        .catch(error => {
            console.error('Error refreshing financial:', error);
        });
}

function refreshNotificationsSection() {
    fetch('../php/get_admin_data.php?section=notifications')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const notificationsList = document.querySelector('.notifications-list');
                if (notificationsList) {
                    notificationsList.innerHTML = '';
                    
                    if (data.notifications && data.notifications.length > 0) {
                        data.notifications.forEach(notification => {
                            const notificationDiv = document.createElement('div');
                            notificationDiv.className = `notification-item ${notification.type}`;
                            
                            const iconClass = notification.type === 'warning' ? 'fa-exclamation-triangle' : 
                                            notification.type === 'success' ? 'fa-check-circle' : 
                                            notification.type === 'error' ? 'fa-times-circle' : 'fa-info-circle';
                            
                            notificationDiv.innerHTML = `
                                <i class="fas ${iconClass}"></i>
                                <div class="notification-content">
                                    <h4>${notification.title}</h4>
                                    <p>${notification.message}</p>
                                    <span class="notification-time">${new Date(notification.created_at).toLocaleString('en-CA', {year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit'})}</span>
                                </div>
                            `;
                            notificationsList.appendChild(notificationDiv);
                        });
                    } else {
                        if (data.system_notifications) {
                            data.system_notifications.forEach(notification => {
                                const notificationDiv = document.createElement('div');
                                notificationDiv.className = `notification-item ${notification.type}`;
                                
                                const iconClass = notification.type === 'warning' ? 'fa-exclamation-triangle' : 
                                                notification.type === 'success' ? 'fa-check-circle' : 
                                                notification.type === 'info' ? 'fa-info-circle' : 'fa-bell';
                                
                                notificationDiv.innerHTML = `
                                    <i class="fas ${iconClass}"></i>
                                    <div class="notification-content">
                                        <h4>${notification.title}</h4>
                                        <p>${notification.message}</p>
                                        <span class="notification-time">${notification.time}</span>
                                    </div>
                                `;
                                notificationsList.appendChild(notificationDiv);
                            });
                        } else {
                            notificationsList.innerHTML = `
                                <div class="no-data">
                                    <i class="fas fa-bell-slash"></i>
                                    <p>No notifications available</p>
                                </div>
                            `;
                        }
                    }
                }
            }
        })
        .catch(error => {
            console.error('Error refreshing notifications:', error);
        });
}

window.onclick = function(event) {
    const settingsModal = document.getElementById('settingsModal');
    const staffModal = document.getElementById('staffModal');
    const orderModal = document.getElementById('orderModal');
    const servicesModal = document.getElementById('servicesModal');
    const expensesModal = document.getElementById('expensesModal');

    if (event.target === settingsModal) {
        closeModal();
    }
    if (event.target === staffModal) {
        closeStaffModal();
    }
    if (event.target === orderModal) {
        closeOrderModal();
    }
    if (event.target === servicesModal) {
        closeServicesModal();
    }
    if (event.target === expensesModal) {
        closeExpensesModal();
    }
    
    if (event.target.classList.contains('modal')) {
        event.target.remove();
    }
}

function showCancelOrderNotification(orderId) {
    const existingNotifications = document.querySelectorAll('.cancel-order-notification');
    existingNotifications.forEach(notification => {
        notification.remove();
    });

    const notification = document.createElement('div');
    notification.className = 'cancel-order-notification';
    
    notification.innerHTML = `
        <div class="cancel-order-notification-content">
            <div class="cancel-order-notification-icon">⚠️</div>
            <div class="cancel-order-notification-text">
                <h4>Cancel Order #${orderId}?</h4>
                <p>Are you sure you want to cancel this order? This action cannot be undone.</p>
            </div>
            <div class="cancel-order-notification-actions">
                <button class="cancel-order-btn-yes" onclick="confirmCancelOrder(${orderId})">Yes, Cancel Order</button>
                <button class="cancel-order-btn-no" onclick="closeCancelOrderNotification()">Keep Order</button>
            </div>
        </div>
    `;

    document.body.appendChild(notification);

    setTimeout(() => {
        if (notification && notification.parentElement) {
            notification.remove();
        }
    }, 8000);
}

function closeCancelOrderNotification() {
    const notification = document.querySelector('.cancel-order-notification');
    if (notification) {
        notification.remove();
    }
}

function showDeleteOfferNotification(offerId) {
    const existingNotifications = document.querySelectorAll('.delete-offer-notification');
    existingNotifications.forEach(notification => {
        notification.remove();
    });

    const notification = document.createElement('div');
    notification.className = 'delete-offer-notification';
    
    notification.innerHTML = `
        <div class="delete-offer-notification-content">
            <div class="delete-offer-notification-icon">🗑️</div>
            <div class="delete-offer-notification-text">
                <h4>Delete Offer?</h4>
                <p>Are you sure you want to delete this offer? This action cannot be undone.</p>
            </div>
            <div class="delete-offer-notification-actions">
                <button class="delete-offer-btn-yes" onclick="confirmDeleteOffer(${offerId})">Yes, Delete</button>
                <button class="delete-offer-btn-no" onclick="closeDeleteOfferNotification()">Cancel</button>
            </div>
        </div>
    `;

    document.body.appendChild(notification);

    setTimeout(() => {
        if (notification && notification.parentElement) {
            notification.remove();
        }
    }, 7000);
}

function closeDeleteOfferNotification() {
    const notification = document.querySelector('.delete-offer-notification');
    if (notification) {
        notification.remove();
    }
}

function showStaffStatusNotification(staffId) {
    const existingNotifications = document.querySelectorAll('.staff-status-notification');
    existingNotifications.forEach(notification => {
        notification.remove();
    });

    const notification = document.createElement('div');
    notification.className = 'staff-status-notification';
    
    notification.innerHTML = `
        <div class="staff-status-notification-content">
            <div class="staff-status-notification-icon">👤</div>
            <div class="staff-status-notification-text">
                <h4>Update Staff Status</h4>
                <p>Select new status for staff member:</p>
            </div>
            <div class="staff-status-notification-actions">
                <button class="staff-status-btn available" onclick="confirmStaffStatus(${staffId}, 'available')">Available</button>
                <button class="staff-status-btn busy" onclick="confirmStaffStatus(${staffId}, 'busy')">Busy</button>
                <button class="staff-status-btn offline" onclick="confirmStaffStatus(${staffId}, 'offline')">Offline</button>
                <button class="staff-status-btn cancel" onclick="closeStaffStatusNotification()">Cancel</button>
            </div>
        </div>
    `;

    document.body.appendChild(notification);

    setTimeout(() => {
        if (notification && notification.parentElement) {
            notification.remove();
        }
    }, 10000);
}

function closeStaffStatusNotification() {
    const notification = document.querySelector('.staff-status-notification');
    if (notification) {
        notification.remove();
    }
}

function showStaffPasswordNotification(staffId) {
    const existingNotifications = document.querySelectorAll('.staff-password-notification');
    existingNotifications.forEach(notification => {
        notification.remove();
    });

    const notification = document.createElement('div');
    notification.className = 'staff-password-notification';
    
    notification.innerHTML = `
        <div class="staff-password-notification-content">
            <div class="staff-password-notification-icon">🔑</div>
            <div class="staff-password-notification-text">
                <h4>Reset Staff Password</h4>
                <p>Enter new password (minimum 6 characters):</p>
                <input type="password" id="newStaffPassword" placeholder="New password..." minlength="6" />
            </div>
            <div class="staff-password-notification-actions">
                <button class="staff-password-btn-yes" onclick="confirmStaffPasswordFromInput(${staffId})">Update Password</button>
                <button class="staff-password-btn-no" onclick="closeStaffPasswordNotification()">Cancel</button>
            </div>
        </div>
    `;

    document.body.appendChild(notification);

    setTimeout(() => {
        document.getElementById('newStaffPassword').focus();
    }, 100);

    setTimeout(() => {
        if (notification && notification.parentElement) {
            notification.remove();
        }
    }, 15000);
}

function confirmStaffPasswordFromInput(staffId) {
    const passwordInput = document.getElementById('newStaffPassword');
    const newPassword = passwordInput ? passwordInput.value : '';
    confirmStaffPassword(staffId, newPassword);
}

function closeStaffPasswordNotification() {
    const notification = document.querySelector('.staff-password-notification');
    if (notification) {
        notification.remove();
    }
}

function showDeleteStaffNotification(staffId) {
    const existingNotifications = document.querySelectorAll('.delete-staff-notification');
    existingNotifications.forEach(notification => {
        notification.remove();
    });

    const notification = document.createElement('div');
    notification.className = 'delete-staff-notification';
    
    notification.innerHTML = `
        <div class="delete-staff-notification-content">
            <div class="delete-staff-notification-icon">⚠️</div>
            <div class="delete-staff-notification-text">
                <h4>Delete Staff Member?</h4>
                <p>Are you sure you want to delete this staff member? This action cannot be undone.</p>
            </div>
            <div class="delete-staff-notification-actions">
                <button class="delete-staff-btn-yes" onclick="confirmDeleteStaff(${staffId})">Yes, Delete</button>
                <button class="delete-staff-btn-no" onclick="closeDeleteStaffNotification()">Cancel</button>
            </div>
        </div>
    `;

    document.body.appendChild(notification);

    setTimeout(() => {
        if (notification && notification.parentElement) {
            notification.remove();
        }
    }, 8000);
}

function closeDeleteStaffNotification() {
    const notification = document.querySelector('.delete-staff-notification');
    if (notification) {
        notification.remove();
    }
}
