<!DOCTYPE html>
<html lang="ro">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inregistrari Service - Masina-Dock</title>
    <link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
    <header>
        <div class="logo">
            <img src="/static/images/logo.svg" alt="Masina-Dock">
            <h1>Masina-Dock</h1>
        </div>
        <nav>
            <a href="/dashboard" data-translate="dashboard">Tablou de bord</a>
            <a href="#" onclick="navigateToVehicle(); return false;" data-translate="overview">Prezentare generala</a>
            <a href="/service-records" class="active" data-translate="service_records">Inregistrari service</a>
            <a href="/repairs" data-translate="repairs">Reparatii</a>
            <a href="/fuel" data-translate="fuel">Combustibil</a>
            <a href="/taxes" data-translate="taxes">Taxe</a>
            <a href="/notes" data-translate="notes">Notite</a>
            <a href="/reminders" data-translate="reminders">Memento-uri</a>
            <button class="theme-toggle" onclick="toggleTheme()" data-translate="toggle_theme">Schimba tema</button>
            <button class="btn btn-danger" onclick="logout()" data-translate="logout">Deconectare</button>
        </nav>
    </header>
    
    <div class="container">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h2 id="vehicle-title" data-translate="service_records">Inregistrari service</h2>
            <button class="btn" onclick="navigateToVehicle()" data-translate="back_to_vehicle">Inapoi la vehicul</button>
        </div>
        
        <button class="btn btn-success" onclick="showModal('add-service-modal')" data-translate="add_service_record">+ Adauga inregistrare service</button>
        <button class="btn" onclick="exportServiceRecords()" data-translate="export_csv">Exporta CSV</button>
        
        <div class="card" style="margin-top: 20px;">
            <table>
                <thead>
                    <tr>
                        <th data-translate="date">Data</th>
                        <th data-translate="odometer">Kilometraj</th>
                        <th data-translate="description">Descriere</th>
                        <th data-translate="category">Categorie</th>
                        <th data-translate="cost">Cost</th>
                        <th data-translate="notes">Notite</th>
                        <th data-translate="attachment">Atasament</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="service-records-tbody"></tbody>
            </table>
        </div>
    </div>
    
    <div id="add-service-modal" class="modal">
        <div class="modal-content">
            <h2 data-translate="add_service_record">Adauga inregistrare service</h2>
            <form id="add-service-form" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="service-date" data-translate="date">Data</label>
                    <input type="date" id="service-date" name="date" required>
                </div>
                <div class="form-group">
                    <label for="service-odometer" data-translate="odometer">Kilometraj</label>
                    <input type="number" id="service-odometer" name="odometer" required min="0">
                </div>
                <div class="form-group">
                    <label for="service-description" data-translate="description">Descriere</label>
                    <input type="text" id="service-description" name="description" required>
                </div>
                <div class="form-group">
                    <label for="service-category" data-translate="category">Categorie</label>
                    <select id="service-category" name="category">
                        <option value="Maintenance" data-translate="maintenance">Intretinere</option>
                        <option value="Repair" data-translate="repair">Reparatie</option>
                        <option value="Inspection" data-translate="inspection">Inspectie tehnica</option>
                        <option value="Upgrade" data-translate="upgrade">Imbunatatire</option>
                        <option value="Other" data-translate="other">Altele</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="service-cost" data-translate="cost">Cost</label>
                    <input type="number" id="service-cost" name="cost" step="0.01" min="0" value="0">
                </div>
                <div class="form-group">
                    <label for="service-notes" data-translate="notes">Notite</label>
                    <textarea id="service-notes" name="notes" rows="3"></textarea>
                </div>
                <div class="form-group">
                    <label for="service-attachment" data-translate="optional">Atasament (Optional)</label>
                    <input type="file" id="service-attachment" name="attachment" accept=".pdf,.png,.jpg,.jpeg,.txt,.doc,.docx,.xls,.xlsx">
                    <small data-translate="supported_files">Suportat: PDF, Imagini, Text, Word, Excel</small>
                </div>
                <div style="display: flex; gap: 10px; margin-top: 20px;">
                    <button type="submit" class="btn btn-success" data-translate="add_record">Adauga inregistrare</button>
                    <button type="button" class="btn" onclick="closeModal('add-service-modal')" data-translate="cancel">Anuleaza</button>
                resetEditMode();
                </div>
            </form>
        </div>
    </div>
    
    <script src="/static/js/translations.js"></script>
    <script src="/static/js/app.js"></script>
    <script>
        let currentVehicleId = null;
        
        document.addEventListener('DOMContentLoaded', async () => {
            currentVehicleId = getSelectedVehicle();
            
            if (!currentVehicleId) {
                alert('Va rugam selectati un vehicul din tabloul de bord.');
                window.location.href = '/dashboard';
                return;
            }
            
            await loadVehicleInfo();
            await loadServiceRecords(currentVehicleId);
        });
        
        async function loadVehicleInfo() {
            try {
                const vehicle = await apiRequest(`/api/vehicles/${currentVehicleId}`);
                document.getElementById('vehicle-title').textContent = 
                    `${vehicle.year} ${vehicle.make} ${vehicle.model} - Inregistrari service`;
            } catch (error) {
                console.error('Failed to load vehicle info:', error);
            }
        }
        
        function navigateToVehicle() {
            if (currentVehicleId) {
                window.location.href = `/vehicle-detail?id=${currentVehicleId}`;
            } else {
                window.location.href = '/dashboard';
            }
        }
        
        function exportServiceRecords() {
            if (currentVehicleId) {
                exportData('service_records', currentVehicleId);
            }
        }
        
        document.getElementById('add-service-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            let attachmentPath = null;
            const attachmentFile = document.getElementById('service-attachment').files[0];
            
            if (attachmentFile) {
                const formData = new FormData();
                formData.append('attachment', attachmentFile);
                
                try {
                    const response = await fetch('/api/upload/attachment', {
                        method: 'POST',
                        credentials: 'include',
                        body: formData
                    });
                    const data = await response.json();
                    attachmentPath = data.file_path;
                } catch (error) {
                    console.error('Attachment upload failed:', error);
                }
            }
            
            const formData = {
                date: document.getElementById('service-date').value,
                odometer: parseInt(document.getElementById('service-odometer').value),
                description: document.getElementById('service-description').value,
                category: document.getElementById('service-category').value,
                cost: parseFloat(document.getElementById('service-cost').value) || 0,
                notes: document.getElementById('service-notes').value || null,
                document_path: attachmentPath
            };
            
            try {
                if (editingServiceRecordId) {
                    await apiRequest(`/api/vehicles/${editingVehicleId}/service-records/${editingServiceRecordId}`, {
                        method: 'PUT',
                        body: JSON.stringify(formData)
                    });
                    editingServiceRecordId = null;
                    editingVehicleId = null;
                    const modal = document.getElementById('add-service-modal');
                    const modalTitle = modal.querySelector('h2');
                    if (modalTitle) modalTitle.textContent = 'Add Service Record';
                } else {
                    await apiRequest(`/api/vehicles/${currentVehicleId}/service-records`, {
                        method: 'POST',
                        body: JSON.stringify(formData)
                    });
                }
                closeModal('add-service-modal');
                resetEditMode();
                await loadServiceRecords(currentVehicleId);
                document.getElementById('add-service-form').reset();
            } catch (error) {
                alert('Adaugarea inregistrarii a esuat: ' + error.message);
            }
        });
    </script>
</body>
</html>
