// API Base URL
const API_BASE = 'api/';

// Global variables
let clients = [];
let objects = [];
let equipment = [];
let equipmentTypes = [];
let incidents = [];
let visits = [];
let repairs = [];

// Initialize the application
document.addEventListener('DOMContentLoaded', function() {
    initializeNavigation();
    loadDashboardData();
    loadAllData();
});

// Navigation functionality
function initializeNavigation() {
    const navButtons = document.querySelectorAll('.nav-btn');
    const sections = document.querySelectorAll('.section');

    navButtons.forEach(button => {
        button.addEventListener('click', function() {
            const targetSection = this.getAttribute('data-section');
            
            // Update active nav button
            navButtons.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');
            
            // Update active section
            sections.forEach(section => section.classList.remove('active'));
            document.getElementById(targetSection).classList.add('active');
            
            // Load section data
            loadSectionData(targetSection);
        });
    });
}

// Load data for specific section
function loadSectionData(section) {
    switch(section) {
        case 'dashboard':
            loadDashboardData();
            break;
        case 'clients':
            loadClients();
            break;
        case 'objects':
            loadObjects();
            break;
        case 'equipment':
            loadEquipment();
            break;
        case 'incidents':
            loadIncidents();
            break;
        case 'visits':
            loadVisits();
            break;
        case 'repairs':
            loadRepairs();
            break;
    }
}

// Load all data
async function loadAllData() {
    await Promise.all([
        loadClients(),
        loadEquipmentTypes(),
        loadObjects(),
        loadEquipment(),
        loadIncidents(),
        loadVisits(),
        loadRepairs()
    ]);
}

// Dashboard functions
async function loadDashboardData() {
    try {
        const [clientsRes, equipmentRes, incidentsRes, visitsRes] = await Promise.all([
            fetch(API_BASE + 'clients.php'),
            fetch(API_BASE + 'equipment.php'),
            fetch(API_BASE + 'incidents.php'),
            fetch(API_BASE + 'visits.php')
        ]);

        const clientsData = await clientsRes.json();
        const equipmentData = await equipmentRes.json();
        const incidentsData = await incidentsRes.json();
        const visitsData = await visitsRes.json();

        // Update dashboard stats
        document.getElementById('total-clients').textContent = clientsData.length;
        document.getElementById('total-equipment').textContent = equipmentData.length;
        
        const openIncidents = incidentsData.filter(incident => incident.status === 'open').length;
        document.getElementById('open-incidents').textContent = openIncidents;
        
        const currentMonth = new Date().getMonth();
        const currentYear = new Date().getFullYear();
        const recentVisits = visitsData.filter(visit => {
            const visitDate = new Date(visit.visit_date);
            return visitDate.getMonth() === currentMonth && visitDate.getFullYear() === currentYear;
        }).length;
        document.getElementById('recent-visits').textContent = recentVisits;
        
    } catch (error) {
        console.error('Error loading dashboard data:', error);
    }
}

// Clients functions
async function loadClients() {
    try {
        const response = await fetch(API_BASE + 'clients.php');
        clients = await response.json();
        displayClients();
    } catch (error) {
        console.error('Error loading clients:', error);
    }
}

function displayClients() {
    const tbody = document.querySelector('#clients-table tbody');
    tbody.innerHTML = '';
    
    clients.forEach(client => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${client.name}</td>
            <td>${client.contact_person || '-'}</td>
            <td>${client.phone || '-'}</td>
            <td>${client.email || '-'}</td>
            <td class="action-buttons">
                <button class="btn btn-secondary btn-small" onclick="editClient(${client.client_id})">
                    <i class="fas fa-edit"></i> Редактирай
                </button>
                <button class="btn btn-danger btn-small" onclick="deleteClient(${client.client_id})">
                    <i class="fas fa-trash"></i> Изтрий
                </button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// Equipment Types functions
async function loadEquipmentTypes() {
    try {
        const response = await fetch(API_BASE + 'equipment_types.php');
        equipmentTypes = await response.json();
    } catch (error) {
        console.error('Error loading equipment types:', error);
    }
}

// Objects functions
async function loadObjects() {
    try {
        const response = await fetch(API_BASE + 'objects.php');
        objects = await response.json();
        displayObjects();
    } catch (error) {
        console.error('Error loading objects:', error);
    }
}

function displayObjects() {
    const tbody = document.querySelector('#objects-table tbody');
    tbody.innerHTML = '';
    
    objects.forEach(object => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${object.object_name}</td>
            <td>${object.client_name}</td>
            <td>${object.address || '-'}</td>
            <td>${object.contact_person || '-'}</td>
            <td class="action-buttons">
                <button class="btn btn-secondary btn-small" onclick="editObject(${object.object_id})">
                    <i class="fas fa-edit"></i> Редактирай
                </button>
                <button class="btn btn-danger btn-small" onclick="deleteObject(${object.object_id})">
                    <i class="fas fa-trash"></i> Изтрий
                </button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// Equipment functions
async function loadEquipment() {
    try {
        const response = await fetch(API_BASE + 'equipment.php');
        equipment = await response.json();
        displayEquipment();
    } catch (error) {
        console.error('Error loading equipment:', error);
    }
}

function displayEquipment() {
    const tbody = document.querySelector('#equipment-table tbody');
    tbody.innerHTML = '';
    
    equipment.forEach(item => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${item.serial_number}</td>
            <td>${item.type_name}</td>
            <td>${item.object_name}</td>
            <td>${item.client_name}</td>
            <td>${item.installation_date || '-'}</td>
            <td class="action-buttons">
                <button class="btn btn-secondary btn-small" onclick="editEquipment(${item.equipment_id})">
                    <i class="fas fa-edit"></i> Редактирай
                </button>
                <button class="btn btn-danger btn-small" onclick="deleteEquipment(${item.equipment_id})">
                    <i class="fas fa-trash"></i> Изтрий
                </button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// Incidents functions
async function loadIncidents() {
    try {
        const response = await fetch(API_BASE + 'incidents.php');
        incidents = await response.json();
        displayIncidents();
    } catch (error) {
        console.error('Error loading incidents:', error);
    }
}

function displayIncidents() {
    const tbody = document.querySelector('#incidents-table tbody');
    tbody.innerHTML = '';
    
    incidents.forEach(incident => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${new Date(incident.incident_date).toLocaleDateString('bg-BG')}</td>
            <td>${incident.serial_number} (${incident.type_name})</td>
            <td>${incident.description}</td>
            <td><span class="status-badge status-${incident.status}">${getStatusText(incident.status)}</span></td>
            <td class="action-buttons">
                <button class="btn btn-secondary btn-small" onclick="editIncident(${incident.incident_id})">
                    <i class="fas fa-edit"></i> Редактирай
                </button>
                <button class="btn btn-danger btn-small" onclick="deleteIncident(${incident.incident_id})">
                    <i class="fas fa-trash"></i> Изтрий
                </button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// Visits functions
async function loadVisits() {
    try {
        const response = await fetch(API_BASE + 'visits.php');
        visits = await response.json();
        displayVisits();
    } catch (error) {
        console.error('Error loading visits:', error);
    }
}

function displayVisits() {
    const tbody = document.querySelector('#visits-table tbody');
    tbody.innerHTML = '';
    
    visits.forEach(visit => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${new Date(visit.visit_date).toLocaleDateString('bg-BG')}</td>
            <td>${visit.technician_name}</td>
            <td>${visit.incident_description.substring(0, 50)}...</td>
            <td>${visit.serial_number}</td>
            <td class="action-buttons">
                <button class="btn btn-secondary btn-small" onclick="editVisit(${visit.visit_id})">
                    <i class="fas fa-edit"></i> Редактирай
                </button>
                <button class="btn btn-danger btn-small" onclick="deleteVisit(${visit.visit_id})">
                    <i class="fas fa-trash"></i> Изтрий
                </button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// Repairs functions
async function loadRepairs() {
    try {
        const response = await fetch(API_BASE + 'repairs.php');
        repairs = await response.json();
        displayRepairs();
    } catch (error) {
        console.error('Error loading repairs:', error);
    }
}

function displayRepairs() {
    const tbody = document.querySelector('#repairs-table tbody');
    tbody.innerHTML = '';
    
    repairs.forEach(repair => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${new Date(repair.repair_date).toLocaleDateString('bg-BG')}</td>
            <td>${repair.technician_name}</td>
            <td>${repair.damage_description.substring(0, 50)}...</td>
            <td>${repair.repair_description ? repair.repair_description.substring(0, 50) + '...' : '-'}</td>
            <td>${repair.cost ? repair.cost + ' лв.' : '-'}</td>
            <td class="action-buttons">
                <button class="btn btn-secondary btn-small" onclick="editRepair(${repair.repair_id})">
                    <i class="fas fa-edit"></i> Редактирай
                </button>
                <button class="btn btn-danger btn-small" onclick="deleteRepair(${repair.repair_id})">
                    <i class="fas fa-trash"></i> Изтрий
                </button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// Utility functions
function getStatusText(status) {
    const statusMap = {
        'open': 'Отворена',
        'in_progress': 'В процес',
        'closed': 'Затворена'
    };
    return statusMap[status] || status;
}

// Modal functions
function showModal(title, content) {
    const modal = document.getElementById('modal');
    const modalBody = document.getElementById('modal-body');
    
    modalBody.innerHTML = `
        <h2>${title}</h2>
        ${content}
    `;
    
    modal.style.display = 'block';
}

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

// Close modal when clicking outside
window.onclick = function(event) {
    const modal = document.getElementById('modal');
    if (event.target === modal) {
        closeModal();
    }
}

// Add/Edit functions for each entity
function showAddClientModal() {
    const content = `
        <form onsubmit="saveClient(event)">
            <div class="form-group">
                <label for="client-name">Име на клиента *</label>
                <input type="text" id="client-name" required>
            </div>
            <div class="form-group">
                <label for="client-contact">Контактно лице</label>
                <input type="text" id="client-contact">
            </div>
            <div class="form-group">
                <label for="client-phone">Телефон</label>
                <input type="text" id="client-phone">
            </div>
            <div class="form-group">
                <label for="client-email">Email</label>
                <input type="email" id="client-email">
            </div>
            <div class="form-group">
                <label for="client-address">Адрес</label>
                <textarea id="client-address"></textarea>
            </div>
            <div class="form-actions">
                <button type="button" class="btn btn-secondary" onclick="closeModal()">Отказ</button>
                <button type="submit" class="btn btn-primary">Запази</button>
            </div>
        </form>
    `;
    showModal('Добави нов клиент', content);
}

async function saveClient(event) {
    event.preventDefault();
    
    const clientData = {
        name: document.getElementById('client-name').value,
        contact_person: document.getElementById('client-contact').value,
        phone: document.getElementById('client-phone').value,
        email: document.getElementById('client-email').value,
        address: document.getElementById('client-address').value
    };
    
    try {
        const response = await fetch(API_BASE + 'clients.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(clientData)
        });
        
        if (response.ok) {
            closeModal();
            loadClients();
            loadDashboardData();
        }
    } catch (error) {
        console.error('Error saving client:', error);
    }
}

// Similar functions would be implemented for other entities...
// For brevity, I'll include just the client example

// Delete functions
async function deleteClient(clientId) {
    if (confirm('Сигурни ли сте, че искате да изтриете този клиент?')) {
        try {
            const response = await fetch(API_BASE + 'clients.php', {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ id: clientId })
            });
            
            if (response.ok) {
                loadClients();
                loadDashboardData();
            }
        } catch (error) {
            console.error('Error deleting client:', error);
        }
    }
}

// Placeholder functions for other entities
function showAddObjectModal() { alert('Функционалността ще бъде добавена скоро'); }
function showAddEquipmentModal() { alert('Функционалността ще бъде добавена скоро'); }
function showAddIncidentModal() { alert('Функционалността ще бъде добавена скоро'); }
function showAddVisitModal() { alert('Функционалността ще бъде добавена скоро'); }
function showAddRepairModal() { alert('Функционалността ще бъде добавена скоро'); }

function editClient(id) { alert('Редактирането ще бъде добавено скоро'); }
function editObject(id) { alert('Редактирането ще бъде добавено скоро'); }
function editEquipment(id) { alert('Редактирането ще бъде добавено скоро'); }
function editIncident(id) { alert('Редактирането ще бъде добавено скоро'); }
function editVisit(id) { alert('Редактирането ще бъде добавено скоро'); }
function editRepair(id) { alert('Редактирането ще бъде добавено скоро'); }

function deleteObject(id) { alert('Изтриването ще бъде добавено скоро'); }
function deleteEquipment(id) { alert('Изтриването ще бъде добавено скоро'); }
function deleteIncident(id) { alert('Изтриването ще бъде добавено скоро'); }
function deleteVisit(id) { alert('Изтриването ще бъде добавено скоро'); }
function deleteRepair(id) { alert('Изтриването ще бъде добавено скоро'); }

