let currentServices = [];

function showManagementTab(tabName) {
    document.querySelectorAll('.management-content').forEach(content => {
        content.classList.remove('active');
    });
    document.querySelectorAll('.management-tabs .tab-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    
    document.getElementById(tabName).classList.add('active');
    event.target.closest('.tab-btn').classList.add('active');
    
    if (tabName === 'services-list') {
        loadServices();
    } else if (tabName === 'options-list') {
        loadServiceFilter();
        loadOptions();
    }
}

function loadServices() {
    const grid = document.getElementById('servicesGrid');
    grid.innerHTML = '<div class="loading-state">Loading services...</div>';
    
    fetch('services.php?action=get_services')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                currentServices = data.services;
                displayServices(data.services);
            } else {
                grid.innerHTML = '<div class="error-state">Failed to load services</div>';
            }
        })
        .catch(error => {
            grid.innerHTML = '<div class="error-state">Error loading services</div>';
            console.error('Error:', error);
        });
}

function displayServices(services) {
    const grid = document.getElementById('servicesGrid');
    
    const filteredServices = services.filter(service => 
        service.category !== 'subscription' && service.name !== 'Monthly Subscriptions'
    );
    
    if (filteredServices.length === 0) {
        grid.innerHTML = '<div class="no-data"><i class="fas fa-box-open"></i><p>No services found</p></div>';
        return;
    }
    
    grid.innerHTML = filteredServices.map(service => {
        const safeName = (service.name || '').replace(/'/g, "\\'");
        const safeDesc = (service.description || '').substring(0, 100);
        let imageUrl = service.image || 'img/default-service.png';
        
        if (imageUrl && !imageUrl.startsWith('http') && !imageUrl.startsWith('../')) {
            imageUrl = '../' + imageUrl;
        }
        
        return `
        <div class="service-card">
            <div class="service-image">
                <img src="${imageUrl}" alt="${service.name}" onerror="this.src='../img/default-service.png'">
            </div>
            <div class="service-info">
                <p class="service-category">${formatCategory(service.category)}</p>
                <h4>${service.name}</h4>
                <p class="service-desc">${safeDesc}${safeDesc.length >= 100 ? '...' : ''}</p>
                ${service.price > 0 ? `<div class="service-price">SAR ${parseFloat(service.price).toFixed(2)}</div>` : ''}
                <div class="service-actions">
                    <button class="btn-icon" onclick="editService(${service.id})" type="button">
                        <i class="fas fa-edit"></i> Edit
                    </button>
                    <button class="btn-icon btn-danger" onclick="deleteService(${service.id}, '${safeName}')" type="button">
                        <i class="fas fa-trash"></i> Delete
                    </button>
                </div>
            </div>
        </div>
        `;
    }).join('');
}

function formatCategory(category) {
    const categories = {
        'complete_washing': 'Complete Washing',
        'ironing': 'Ironing',
        'carpet': 'Carpet & Curtain',
        'shoes': 'Shoes',
        'household': 'Household Items',
        'subscription': 'Subscription'
    };
    return categories[category] || category;
}

function openServiceForm(id = null) {
    const modal = document.getElementById('serviceModal');
    const form = document.getElementById('serviceForm');
    const title = document.getElementById('serviceModalTitle');
    
    form.reset();
    
    if (id) {
        title.textContent = 'Edit Service';
        fetch(`services.php?action=get_service&id=${id}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const service = data.service;
                    document.getElementById('service_id').value = service.id;
                    document.getElementById('service_name').value = service.name;
                    document.getElementById('service_description').value = service.description;
                    document.getElementById('service_price').value = service.price;
                    document.getElementById('service_category').value = service.category;
                    document.getElementById('service_image').value = service.image || '';
                }
            });
    } else {
        title.textContent = 'Add New Service';
        document.getElementById('service_id').value = '';
    }
    
    modal.style.display = 'flex';
}

function editService(id) {
    openServiceForm(id);
}

function deleteService(id, name) {
    if (!confirm(`Are you sure you want to delete "${name}"?\nThis will also delete all related options.`)) {
        return;
    }
    
    const formData = new FormData();
    formData.append('action', 'delete_service');
    formData.append('id', id);
    
    fetch('services.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification(data.message, 'success');
            loadServices();
        } else {
            showNotification(data.message, 'error');
        }
    })
    .catch(error => {
        showNotification('Failed to delete service', 'error');
        console.error('Error:', error);
    });
}

function closeServiceModal() {
    document.getElementById('serviceModal').style.display = 'none';
}

document.getElementById('serviceForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    fetch('services.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification(data.message, 'success');
            closeServiceModal();
            loadServices();
        } else {
            showNotification(data.message, 'error');
        }
    })
    .catch(error => {
        showNotification('Failed to save service', 'error');
        console.error('Error:', error);
    });
});

function loadServiceFilter() {
    const filter = document.getElementById('serviceFilter');
    const optionServiceSelect = document.getElementById('option_service_id');
    
    fetch('services.php?action=get_services')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // استبعاد خدمة Monthly Subscriptions من الفلتر
                const filteredServices = data.services.filter(s => 
                    s.category !== 'subscription' && s.name !== 'Monthly Subscriptions'
                );
                
                const options = filteredServices.map(s => 
                    `<option value="${s.id}">${s.name}</option>`
                ).join('');
                
                filter.innerHTML = '<option value="">All Services</option>' + options;
                optionServiceSelect.innerHTML = options;
            }
        });
}

function loadOptions() {
    const tbody = document.getElementById('optionsTableBody');
    const serviceId = document.getElementById('serviceFilter').value;
    
    tbody.innerHTML = '<tr><td colspan="7" class="loading-state">Loading options...</td></tr>';
    
    const url = serviceId 
        ? `services.php?action=get_options&service_id=${serviceId}`
        : 'services.php?action=get_options';
    
    fetch(url)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayOptions(data.options);
            } else {
                tbody.innerHTML = '<tr><td colspan="7" class="error-state">Failed to load options</td></tr>';
            }
        })
        .catch(error => {
            tbody.innerHTML = '<tr><td colspan="7" class="error-state">Error loading options</td></tr>';
            console.error('Error:', error);
        });
}

function displayOptions(options) {
    const tbody = document.getElementById('optionsTableBody');
    
    if (options.length === 0) {
        tbody.innerHTML = '<tr><td colspan="7" class="no-data">No options found</td></tr>';
        return;
    }
    
    tbody.innerHTML = options.map(opt => `
        <tr>
            <td>${opt.id}</td>
            <td>${opt.service_name}</td>
            <td><span class="badge">${opt.option_type}</span></td>
            <td>${opt.option_name}</td>
            <td><code>${opt.option_value}</code></td>
            <td>${parseFloat(opt.price_modifier) >= 0 ? '+' : ''}${parseFloat(opt.price_modifier).toFixed(2)} SAR</td>
            <td>
                <button class="btn-icon" onclick="editOption(${opt.id})" title="Edit">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="btn-icon btn-danger" onclick="deleteOption(${opt.id}, '${opt.option_name}')" title="Delete">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    `).join('');
}

function openOptionForm(id = null) {
    const modal = document.getElementById('optionModal');
    const form = document.getElementById('optionForm');
    const title = document.getElementById('optionModalTitle');
    
    form.reset();
    loadServiceFilter();
    
    if (id) {
        title.textContent = 'Edit Option';
        fetch(`services.php?action=get_option&id=${id}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const opt = data.option;
                    document.getElementById('option_id').value = opt.id;
                    document.getElementById('option_service_id').value = opt.service_id;
                    document.getElementById('option_type').value = opt.option_type;
                    document.getElementById('option_name').value = opt.option_name;
                    document.getElementById('option_value').value = opt.option_value;
                    document.getElementById('option_price_modifier').value = opt.price_modifier;
                }
            });
    } else {
        title.textContent = 'Add New Option';
        document.getElementById('option_id').value = '';
    }
    
    modal.style.display = 'flex';
}

function editOption(id) {
    openOptionForm(id);
}

function deleteOption(id, name) {
    if (!confirm(`Delete option "${name}"?`)) return;
    
    const formData = new FormData();
    formData.append('action', 'delete_option');
    formData.append('id', id);
    
    fetch('services.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification(data.message, 'success');
            loadOptions();
        } else {
            showNotification(data.message, 'error');
        }
    });
}

function closeOptionModal() {
    document.getElementById('optionModal').style.display = 'none';
}

document.getElementById('optionForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    fetch('services.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification(data.message, 'success');
            closeOptionModal();
            loadOptions();
        } else {
            showNotification(data.message, 'error');
        }
    });
});

function showNotification(message, type) {
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <div class="notification-content">
            <span class="notification-icon">${type === 'success' ? '✓' : '✕'}</span>
            <span class="notification-message">${message}</span>
        </div>
        <button class="notification-close" onclick="this.parentElement.remove()">×</button>
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.classList.add('notification-fade-out');
        setTimeout(() => notification.remove(), 300);
    }, 3000);
}

document.addEventListener('DOMContentLoaded', function() {
    const servicesNav = document.querySelector('[data-section="services"]');
    if (servicesNav) {
        servicesNav.addEventListener('click', function() {
            loadServices();
            loadServiceFilter();
        });
    }
});
