let currentVehicleProfile = {};

let fuelMonthlyLoaded = false;

let dateReferencesCache = null;

$(function () {
    loadProfile();
    loadInsurance();
    loadInsurers();
    loadLicenses();
    bindProfileControls();

    $('button[data-bs-target="#fuel"]').on('shown.bs.tab', function () {
        if (!fuelMonthlyLoaded) {
            fuelMonthlyLoaded = true;
            loadFuelMonthly();
        }
    });
});

function loadProfile() {
    $.get('api/vehicle_profile.php', { action: 'profile', id: VEHICLE_ID }, function (res) {
        if (res.status !== 'success') {
            showProfileError(res.message || 'Failed to load vehicle profile');
            return;
        }

        const vehicle = res.data || {};
        $('#alertBox').addClass('d-none').text('');

        $('#vehicleTitle').text(vehicle.plate_number || 'Vehicle Profile');
        $('#vehicleSubtitle').text(buildSubtitle(vehicle));
        $('#vehicleStatus')
            .removeClass('bg-success bg-warning bg-secondary bg-danger bg-info text-dark')
            .addClass(getVehicleStatusClass(vehicle.vehicle_status))
            .text(vehicle.vehicle_status || 'Unknown');

        $('#currentDriver').text(vehicle.driver_name || 'Unassigned');
        $('#assignmentDriver').text(vehicle.driver_name || 'Unassigned');
        $('#assignmentStart').text(formatDateTime(vehicle.assignment_start));
        $('#assignmentEnd').text(formatDateTime(vehicle.assignment_end));
        $('#assignmentStatus').text(vehicle.assignment_status || '-');
        $('#assignmentLeasedDays').text(vehicle.leased_days != null ? vehicle.leased_days + ' day(s)' : '-');
        $('#standardConsumption').text(formatDecimal(vehicle.fuel_efficiency_baseline, ' L/100km'));
        $('#latestDistance').text(formatInteger(vehicle.latest_distance_km, ' km'));
        $('#complianceCount').text(vehicle.compliance_count || 0);

        $('#plate').text(vehicle.plate_number || '-');
        $('#year').text(vehicle.year_of_manufacturing || '-');
        $('#owner').text(vehicle.owner || '-');
        $('#property').text(vehicle.property || '-');
        $('#type').text(vehicle.vehicle_type || '-');
        $('#model').text(vehicle.vehicle_model || '-');
        $('#useType').text(vehicle.vehicle_use_type || '-');
        $('#source').text(vehicle.vehicle_source || '-');
        $('#displacement').text(vehicle.displacement || '-');
        $('#seats').text(vehicle.seats || '-');
        $('#needObd').text(booleanLabel(vehicle.need_obd));
        $('#obdDeviceNo').text(vehicle.obd_device_no || '-');
        $('#useMrCar').text(booleanLabel(vehicle.use_mr_car));
        $('#scheduleExpirationDate').text(formatDate(vehicle.schedule_expiration_date));

        $('#registrationDate').text(formatDate(vehicle.registration_date));
        $('#firstEffectiveDate').text(formatDate(vehicle.first_effective_date));
        $('#entryDate').text(formatDate(vehicle.entry_date));
        $('#exitDate').text(formatDate(vehicle.exit_date));
        $('#supplierId').text(vehicle.supplier_name || vehicle.supplier_id || '-');
        $('#contractId').text(buildContractLabel(vehicle));
        $('#countryId').text(vehicle.country_name || vehicle.country_id || '-');
        $('#cityId').text(vehicle.city_name || vehicle.city_id || '-');
        $('#regionId').text(vehicle.region_name || vehicle.region_id || '-');
        $('#departmentId').text(vehicle.department_name || vehicle.department_id || '-');
        $('#projectId').text(vehicle.project_name || vehicle.project_id || '-');
        $('#officeId').text(vehicle.office_name || vehicle.office_id || '-');
        $('#locationId').text(vehicle.location_name || vehicle.location_id || '-');
        $('#scheduleId').text(vehicle.schedule_name || vehicle.schedule_id || '-');

        $('#fuelConfigEfficiency').text(formatDecimal(vehicle.fuel_efficiency_baseline, ' L/100km'));
        $('#fuelConfigStandard').text(formatDecimal(vehicle.standard_consumption, ' L/month'));

        currentVehicleProfile = vehicle;
        loadMaintenanceRecords(vehicle.plate_number || '');
    }, 'json').fail(function () {
        showProfileError('Server error while loading vehicle profile');
    });
}

function loadFuelMonthly() {
    $.get('api/vehicle_profile.php', { action: 'fuel_monthly', id: VEHICLE_ID }, function (res) {
        if (res.status !== 'success') {
            $('#fuelMonthlyTable').html('<tr><td colspan="6" class="text-center text-muted">Unable to load monthly fuel data</td></tr>');
            return;
        }

        const rows = res.data || [];
        let html = '';

        if (!rows.length) {
            html = '<tr><td colspan="6" class="text-center text-muted">No monthly fuel records found</td></tr>';
        } else {
            $.each(rows, function (_, row) {
                html += `
                    <tr>
                        <td>${escapeHtml(row.month_year || '-')}</td>
                        <td>${escapeHtml(formatDecimal(row.fuel_purchase_liters, ' L'))}</td>
                        <td>${escapeHtml(formatCurrency(row.naira_per_liter))}</td>
                        <td>${escapeHtml(formatInteger(row.monthly_mileage_km, ' km'))}</td>
                        <td>${escapeHtml(formatInteger(row.distance_km, ' km'))}</td>
                        <td>${escapeHtml(formatDecimal(row.baseline_difference, ''))}</td>
                    </tr>
                `;
            });
        }

        $('#fuelMonthlyTable').html(html);
        renderFuelMonthlyChart(rows);
    }, 'json');
}

function loadInsurance() {
    $.get('api/vehicle_profile.php', { action: 'insurance', id: VEHICLE_ID }, function (res) {
        if (res.status !== 'success') {
            $('#insuranceTable').html('<tr><td colspan="8" class="text-center text-muted">Unable to load insurance records</td></tr>');
            return;
        }

        const rows = res.data || [];
        let html = '';

        if (!rows.length) {
            html = '<tr><td colspan="8" class="text-center text-muted">No insurance records found</td></tr>';
        } else {
            $.each(rows, function (_, row) {
                var activeBadge = row.is_active == 1 ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>';
                html += `
                    <tr>
                        <td>${escapeHtml(row.policy_number || '-')}</td>
                        <td>${escapeHtml(row.insurer_name || '-')}</td>
                        <td>${escapeHtml(row.policy_type || '-')}</td>
                        <td>${escapeHtml(formatDate(row.coverage_start))}</td>
                        <td>${escapeHtml(formatDate(row.coverage_end))}</td>
                        <td>${activeBadge}</td>
                        <td>${renderComplianceStatus(row.record_status)}</td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary edit-insurance me-1" data-id="${escapeHtml(row.id)}" title="Edit"><i class="bi bi-pencil"></i></button>
                            <button class="btn btn-sm btn-outline-danger delete-insurance" data-id="${escapeHtml(row.id)}" title="Delete"><i class="bi bi-trash"></i></button>
                        </td>
                    </tr>
                `;
            });
        }

        $('#insuranceTable').html(html);

        $('#insuranceTable').off('click', '.edit-insurance').on('click', '.edit-insurance', function () {
            const id = $(this).data('id');
            const row = rows.find(function (r) { return r.id == id; });
            if (row) openEditInsuranceModal(row);
        });
        $('#insuranceTable').off('click', '.delete-insurance').on('click', '.delete-insurance', function () {
            const id = $(this).data('id');
            if (confirm('Delete this insurance policy?')) {
                $.post('api/vehicle_profile.php?action=delete_insurance', { id: id }, function (res) {
                    if (res.status === 'success') {
                        showProfileMessage('Insurance policy deleted', 'success');
                        loadInsurance();
                    } else {
                        showProfileMessage(res.message || 'Delete failed', 'danger');
                    }
                }, 'json');
            }
        });
    }, 'json');
}

function loadInsurers() {
    $.get('api/insurers.php?action=list', function (res) {
        if (res.status !== 'success') return;
        var html = '<option value="">Select Insurer</option>';
        $.each(res.data, function (_, ins) {
            var n = String(ins.name).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
            html += '<option value="' + escapeHtml(ins.id) + '">' + n + '</option>';
        });
        $('#insuranceInsurerId').html(html);
    });
}

function loadLicenses() {
    $.get('api/vehicle_profile.php', { action: 'licenses', id: VEHICLE_ID }, function (res) {
        if (res.status !== 'success') {
            $('#licenseTable').html('<tr><td colspan="6" class="text-center text-muted">Unable to load vehicle licenses</td></tr>');
            return;
        }

        const rows = res.data || [];
        let html = '';

        if (!rows.length) {
            html = '<tr><td colspan="6" class="text-center text-muted">No vehicle license records found</td></tr>';
        } else {
            $.each(rows, function (_, row) {
                html += `
                    <tr>
                        <td>${escapeHtml(row.vehicle_license_no || '-')}</td>
                        <td>${escapeHtml(formatDate(row.issued_date))}</td>
                        <td>${escapeHtml(formatDate(row.valid_until))}</td>
                        <td>${escapeHtml(formatDate(row.notification_date))}</td>
                        <td>${renderComplianceStatus(row.record_status)}</td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary edit-license me-1" data-id="${escapeHtml(row.id)}" title="Edit"><i class="bi bi-pencil"></i></button>
                            <button class="btn btn-sm btn-outline-danger delete-license" data-id="${escapeHtml(row.id)}" title="Delete"><i class="bi bi-trash"></i></button>
                        </td>
                    </tr>
                `;
            });
        }

        $('#licenseTable').html(html);

        $('#licenseTable').off('click', '.edit-license').on('click', '.edit-license', function () {
            const id = $(this).data('id');
            const row = rows.find(function (r) { return r.id == id; });
            if (row) openEditLicenseModal(row);
        });
        $('#licenseTable').off('click', '.delete-license').on('click', '.delete-license', function () {
            const id = $(this).data('id');
            if (confirm('Delete this license record?')) {
                $.post('api/vehicle_profile.php?action=delete_license', { licenseId: id }, function (res) {
                    if (res.status === 'success') {
                        showProfileMessage('License record deleted', 'success');
                        loadLicenses();
                    } else {
                        showProfileMessage(res.message || 'Delete failed', 'danger');
                    }
                }, 'json');
            }
        });
    }, 'json');
}

function renderFuelMonthlyChart(rows) {
    const container = document.getElementById('fuelMonthlyChart');
    if (!container) {
        return;
    }

    const maxVal = Math.max(1, ...rows.map(function (row) { return Number(row.distance_km || 0); }));
    const barCount = rows.length;
    const barWidth = Math.max(8, Math.min(40, Math.floor(800 / barCount)));

    let html = '<div style="display:flex;align-items:flex-end;gap:2px;height:120px;padding:4px 0;">';
    $.each(rows, function (_, row) {
        const val = Number(row.distance_km || 0);
        const pct = (val / maxVal) * 100;
        const label = (row.month_year || '').slice(-2);
        html += '<div style="flex:1;display:flex;flex-direction:column;align-items:center;min-width:0;">';
        html += '<div style="width:100%;max-width:' + barWidth + 'px;height:' + pct.toFixed(0) + '%;min-height:' + (val > 0 ? '2px' : '0') + ';background:#0d6efd;border-radius:2px 2px 0 0;" title="' + escapeHtml(row.month_year || '') + ': ' + escapeHtml(val.toFixed(0)) + ' km"></div>';
        html += '<span style="font-size:9px;color:#6c757d;margin-top:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;">' + escapeHtml(label) + '</span>';
        html += '</div>';
    });
    html += '</div>';

    container.innerHTML = html;
}

function buildSubtitle(vehicle) {
    const parts = [vehicle.vehicle_model, vehicle.vehicle_type, vehicle.owner].filter(Boolean);
    return parts.length ? parts.join(' • ') : 'Asset, assignment, fuel and compliance view.';
}

function bindProfileControls() {
    $('#btnEditVehicle, #btnEditDetails').on('click', openEditVehicleModal);
    $('#btnEditDates').on('click', openEditDatesModal);
    $('#btnEditFuelConfig').on('click', openFuelConfigModal);
    $('#btnAddInsurance').on('click', openInsuranceModal);
    $('#btnAddLicense').on('click', openLicenseModal);
    $('#btnScheduleMaintenance').on('click', openMaintenanceModal);

    $('#btnSaveVehicle').on('click', saveVehicle);
    $('#btnSaveDates').on('click', saveDates);
    $('#btnSaveFuelConfig').on('click', saveFuelConfig);
    $('#btnSaveInsurance').on('click', saveInsurance);
    $('#btnSaveLicense').on('click', saveLicense);
    $('#btnSaveMaintenance').on('click', saveMaintenance);
}

var editVehicleRefsCache = null;

function openEditVehicleModal() {
    const fillVehicleRefs = function () {
        $('#editPlate').val(currentVehicleProfile.plate_number || '');
        $('#editYear').val(currentVehicleProfile.year_of_manufacturing || '');
        $('#editOwner').val(currentVehicleProfile.owner || '');
        $('#editProperty').val(currentVehicleProfile.property || '');
        $('#editType').val(currentVehicleProfile.vehicle_type || '');
        $('#editModel').val(currentVehicleProfile.vehicle_model || '');
        $('#editUseType').val(currentVehicleProfile.vehicle_use_type || '');
        $('#editSource').val(currentVehicleProfile.vehicle_source || '');
        $('#editDisplacement').val(currentVehicleProfile.displacement || '');
        $('#editSeats').val(currentVehicleProfile.seats || '');
        $('#editNeedObd').val(currentVehicleProfile.need_obd ?? '0');
        $('#editObdDeviceNo').val(currentVehicleProfile.obd_device_no || '');
        $('#editUseMrCar').val(currentVehicleProfile.use_mr_car ?? '0');
        $('#editScheduleExpirationDate').val(currentVehicleProfile.schedule_expiration_date || '');
    };

    if (editVehicleRefsCache) {
        $('#editVehicleForm')[0].reset();
        $('#editVehicleId').val(VEHICLE_ID);
        populateVehicleRefSelects(editVehicleRefsCache);
        fillVehicleRefs();
        new bootstrap.Modal(document.getElementById('editVehicleModal')).show();
        return;
    }

    $.get('api/vehicle_profile.php', { action: 'date_references' }, function (res) {
        if (res.status === 'success') {
            editVehicleRefsCache = res.data || {};
            populateVehicleRefSelects(editVehicleRefsCache);
        }
        $('#editVehicleForm')[0].reset();
        $('#editVehicleId').val(VEHICLE_ID);
        fillVehicleRefs();
        new bootstrap.Modal(document.getElementById('editVehicleModal')).show();
    }, 'json').fail(function () {
        $('#editVehicleForm')[0].reset();
        $('#editVehicleId').val(VEHICLE_ID);
        fillVehicleRefs();
        new bootstrap.Modal(document.getElementById('editVehicleModal')).show();
    });
}

function populateVehicleRefSelects(refs) {
    var map = {
        editOwner: { key: 'owners', label: 'Owner' },
        editType: { key: 'vehicle_types', label: 'Type' },
        editModel: { key: 'vehicle_models', label: 'Model' }
    };
    $.each(map, function (selectId, cfg) {
        var items = refs[cfg.key] || [];
        var $sel = $('#' + selectId).empty().append('<option value="">Select ' + cfg.label + '</option>');
        $.each(items, function (_, item) {
            $sel.append('<option value="' + escapeHtml(item.name || '') + '">' + escapeHtml(item.name || '') + '</option>');
        });
    });
}

function openEditDatesModal() {
    const fillDates = function () {
        $('#editRegistrationDate').val(currentVehicleProfile.registration_date || '');
        $('#editFirstEffectiveDate').val(currentVehicleProfile.first_effective_date || '');
        $('#editEntryDate').val(currentVehicleProfile.entry_date || '');
        $('#editExitDate').val(currentVehicleProfile.exit_date || '');
        $('#editSupplierId').val(currentVehicleProfile.supplier_id || '');
        $('#editContractId').val(currentVehicleProfile.contract_id || '');
        $('#editCountryId').val(currentVehicleProfile.country_id || '');
        $('#editCityId').val(currentVehicleProfile.city_id || '');
        $('#editRegionId').val(currentVehicleProfile.region_id || '');
        $('#editDepartmentId').val(currentVehicleProfile.department_id || '');
        $('#editProjectId').val(currentVehicleProfile.project_id || '');
        $('#editOfficeId').val(currentVehicleProfile.office_id || '');
        $('#editLocationId').val(currentVehicleProfile.location_id || '');
        $('#editScheduleId').val(currentVehicleProfile.schedule_id || '');
    };

    if (dateReferencesCache) {
        $('#editDatesForm')[0].reset();
        $('#editDatesVehicleId').val(VEHICLE_ID);
        populateDateSelects(dateReferencesCache);
        fillDates();
        new bootstrap.Modal(document.getElementById('editDatesModal')).show();
        return;
    }

    $.get('api/vehicle_profile.php', { action: 'date_references' }, function (res) {
        if (res.status === 'success') {
            dateReferencesCache = res.data || {};
            populateDateSelects(dateReferencesCache);
        }
        $('#editDatesForm')[0].reset();
        $('#editDatesVehicleId').val(VEHICLE_ID);
        fillDates();
        new bootstrap.Modal(document.getElementById('editDatesModal')).show();
    }, 'json').fail(function () {
        $('#editDatesForm')[0].reset();
        $('#editDatesVehicleId').val(VEHICLE_ID);
        fillDates();
        new bootstrap.Modal(document.getElementById('editDatesModal')).show();
    });
}

function populateDateSelects(refs) {
    var map = {
        editSupplierId: { key: 'suppliers', label: 'Supplier' },
        editContractId: { key: 'contracts', label: 'Contract' },
        editCountryId: { key: 'countries', label: 'Country' },
        editCityId: { key: 'cities', label: 'City' },
        editRegionId: { key: 'regions', label: 'Region' },
        editDepartmentId: { key: 'departments', label: 'Department' },
        editProjectId: { key: 'projects', label: 'Project' },
        editOfficeId: { key: 'offices', label: 'Office' },
        editLocationId: { key: 'locations', label: 'Location' },
        editScheduleId: { key: 'schedules', label: 'Schedule' }
    };
    $.each(map, function (selectId, cfg) {
        var items = refs[cfg.key] || [];
        var $sel = $('#' + selectId).empty().append('<option value="">Select ' + cfg.label + '</option>');
        $.each(items, function (_, item) {
            $sel.append('<option value="' + escapeHtml(String(item.id)) + '">' + escapeHtml(item.name || '') + '</option>');
        });
    });
}

function openFuelConfigModal() {
    $('#fuelConfigForm')[0].reset();
    $('#fuelConfigVehicleId').val(VEHICLE_ID);
    $('#editFuelEfficiency').val(currentVehicleProfile.fuel_efficiency_baseline ?? '');
    $('#editFuelStandard').val(currentVehicleProfile.standard_consumption ?? '');
    $('#editAutoBaseline').prop('checked', currentVehicleProfile.auto_calculate_baseline != 0);
    toggleFuelBaselineFields();

    const modal = new bootstrap.Modal(document.getElementById('fuelConfigModal'));
    modal.show();
}

function toggleFuelBaselineFields() {
    const auto = $('#editAutoBaseline').is(':checked');
    $('#fuelBaselineFields, #fuelStandardFields').toggle(!auto);
}

$(document).on('change', '#editAutoBaseline', toggleFuelBaselineFields);

function openInsuranceModal() {
    $('#insuranceForm')[0].reset();
    $('#insuranceVehicleId').val(VEHICLE_ID);
    $('#insuranceIsActive').val(1);
    $('#insuranceModalTitle').text('Add Insurance Policy');

    const modal = new bootstrap.Modal(document.getElementById('insuranceModal'));
    modal.show();
}

function openLicenseModal() {
    $('#licenseForm')[0].reset();
    $('#licenseVehicleId').val(VEHICLE_ID);
    $('#licenseModalTitle').text('Add Vehicle License');

    const modal = new bootstrap.Modal(document.getElementById('licenseModal'));
    modal.show();
}

function openMaintenanceModal() {
    $('#maintenanceForm')[0].reset();
    $('#maintenanceVehicleId').val(VEHICLE_ID);
    $('#maintenanceModalTitle').text('Create Maintenance Record');

    const modal = new bootstrap.Modal(document.getElementById('maintenanceModal'));
    modal.show();
}

function saveVehicle() {
    const data = $('#editVehicleForm').serialize();
    $.post('api/vehicle_profile.php?action=save_vehicle', data, function (res) {
        if (res.status === 'success') {
            bootstrap.Modal.getInstance(document.getElementById('editVehicleModal')).hide();
            showProfileMessage('Vehicle updated successfully', 'success');
            loadProfile();
        } else {
            showProfileMessage(res.message || 'Save failed', 'danger');
        }
    }, 'json').fail(function () {
        showProfileMessage('Server error saving vehicle', 'danger');
    });
}

function saveDates() {
    const data = $('#editDatesForm').serialize();
    $.post('api/vehicle_profile.php?action=save_dates', data, function (res) {
        if (res.status === 'success') {
            bootstrap.Modal.getInstance(document.getElementById('editDatesModal')).hide();
            showProfileMessage('Dates and references updated successfully', 'success');
            loadProfile();
        } else {
            showProfileMessage(res.message || 'Save failed', 'danger');
        }
    }, 'json').fail(function () {
        showProfileMessage('Server error saving dates', 'danger');
    });
}

function saveFuelConfig() {
    const data = $('#fuelConfigForm').serialize();
    $.post('api/vehicle_profile.php?action=save_fuel_config', data, function (res) {
        if (res.status === 'success') {
            bootstrap.Modal.getInstance(document.getElementById('fuelConfigModal')).hide();
            showProfileMessage('Fuel configuration saved successfully', 'success');
            loadProfile();
        } else {
            showProfileMessage(res.message || 'Save failed', 'danger');
        }
    }, 'json').fail(function () {
        showProfileMessage('Server error saving fuel config', 'danger');
    });
}

function saveInsurance() {
    const data = $('#insuranceForm').serialize();
    $.post('api/vehicle_profile.php?action=save_insurance', data, function (res) {
        if (res.status === 'success') {
            bootstrap.Modal.getInstance(document.getElementById('insuranceModal')).hide();
            showProfileMessage('Insurance policy saved successfully', 'success');
            loadInsurance();
        } else {
            showProfileMessage(res.message || 'Save failed', 'danger');
        }
    }, 'json').fail(function () {
        showProfileMessage('Server error saving insurance', 'danger');
    });
}

function saveLicense() {
    const data = $('#licenseForm').serialize();
    $.post('api/vehicle_profile.php?action=save_license', data, function (res) {
        if (res.status === 'success') {
            bootstrap.Modal.getInstance(document.getElementById('licenseModal')).hide();
            showProfileMessage('License record saved successfully', 'success');
            loadLicenses();
        } else {
            showProfileMessage(res.message || 'Save failed', 'danger');
        }
    }, 'json').fail(function () {
        showProfileMessage('Server error saving license', 'danger');
    });
}

function saveMaintenance() {
    const data = $('#maintenanceForm').serialize();
    $.post('api/vehicle_profile.php?action=save_maintenance', data, function (res) {
        if (res.status === 'success') {
            bootstrap.Modal.getInstance(document.getElementById('maintenanceModal')).hide();
            showProfileMessage('Maintenance record created successfully', 'success');
            loadMaintenanceRecords(currentVehicleProfile.plate_number || '');
        } else {
            showProfileMessage(res.message || 'Save failed', 'danger');
        }
    }, 'json').fail(function () {
        showProfileMessage('Server error saving maintenance', 'danger');
    });
}

function openEditInsuranceModal(row) {
    $('#insuranceForm')[0].reset();
    $('#insuranceId').val(row.id || '');
    $('#insuranceVehicleId').val(VEHICLE_ID);
    $('#insurancePolicyNumber').val(row.policy_number || '');
    $('#insuranceInsurerId').val(row.insurer_id || '');
    $('#insurancePolicyType').val(row.policy_type || '');
    $('#insuranceCoverageStart').val(row.coverage_start || '');
    $('#insuranceCoverageEnd').val(row.coverage_end || '');
    $('#insurancePremiumAmount').val(row.premium_amount || '');
    $('#insuranceIsActive').val(row.is_active != null ? row.is_active : 1);
    $('#insuranceNotes').val(row.notes || '');
    $('#insuranceModalTitle').text('Edit Insurance Policy');
    const modal = new bootstrap.Modal(document.getElementById('insuranceModal'));
    modal.show();
}

function openEditLicenseModal(row) {
    $('#licenseForm')[0].reset();
    $('#licenseId').val(row.id || '');
    $('#licenseVehicleId').val(VEHICLE_ID);
    $('#licenseNumber').val(row.vehicle_license_no || '');
    $('#licenseIssuedDate').val(row.issued_date || '');
    $('#licenseExpiryDate').val(row.valid_until || '');
    $('#licenseNotificationDays').val('30');
    $('#licenseNotes').val('');
    $('#licenseModalTitle').text('Edit Vehicle License');
    const modal = new bootstrap.Modal(document.getElementById('licenseModal'));
    modal.show();
}

function showProfileMessage(message, type = 'info') {
    const alertBox = $('#alertBox');
    alertBox.removeClass('alert-success alert-danger alert-warning alert-info')
           .addClass(`alert-${type}`)
           .text(message)
           .removeClass('d-none');

    setTimeout(() => {
        alertBox.addClass('d-none');
    }, 5000);
}

function loadMaintenanceRecords(plate) {
    if (!VEHICLE_ID) {
        $('#maintenanceTable').html('<tr><td colspan="7" class="text-center text-muted">No maintenance records found</td></tr>');
        return;
    }

    $.get('api/maintenance.php', { action: 'jobs', vehicle_id: VEHICLE_ID, search: plate }, function (res) {
        if (res.status !== 'success') {
            $('#maintenanceTable').html('<tr><td colspan="7" class="text-center text-muted">Unable to load maintenance records</td></tr>');
            return;
        }

        const rows = res.data || [];
        let html = '';

        if (!rows.length) {
            html = '<tr><td colspan="7" class="text-center text-muted">No maintenance records found</td></tr>';
        } else {
            $.each(rows, function (_, row) {
                html += `
                    <tr>
                        <td>${escapeHtml(formatDate(row.complaint_date))}</td>
                        <td>${escapeHtml(row.complaint_title || row.nature_of_fault || 'Maintenance')}</td>
                        <td>${escapeHtml(row.complaint_description || '-')}</td>
                        <td>${escapeHtml(row.driver_name || '-')}</td>
                        <td>${escapeHtml(formatCurrency(row.approved_amount || row.quote_amount || row.cost_of_repair || 0))}</td>
                        <td>${renderMaintenanceStatus(row.workflow_stage)}</td>
                        <td><button class="btn btn-sm btn-outline-secondary">View</button></td>
                    </tr>
                `;
            });
        }

        $('#maintenanceTable').html(html);
        renderUpcomingMaintenance(rows);
    }, 'json').fail(function () {
        $('#maintenanceTable').html('<tr><td colspan="7" class="text-center text-muted">Server error loading maintenance records</td></tr>');
    });
}

function renderUpcomingMaintenance(allJobs) {
    const rows = (allJobs || []).filter(function (row) {
        return row.workflow_stage && row.workflow_stage.toLowerCase() !== 'closed' && row.workflow_stage.toLowerCase() !== 'cancelled';
    });
    let html = '';

    if (!rows.length) {
        html = '<tr><td colspan="5" class="text-center text-muted">No upcoming maintenance found</td></tr>';
    } else {
        $.each(rows, function (_, row) {
            html += `
                <tr>
                    <td>${escapeHtml(row.complaint_title || 'Upcoming')}</td>
                    <td>${escapeHtml(formatDate(row.expected_completion_date || row.complaint_date))}</td>
                    <td>${escapeHtml(formatInteger(row.next_service_mileage_km, ' km'))}</td>
                    <td>${escapeHtml(row.workflow_stage || '-')}</td>
                    <td><button class="btn btn-sm btn-outline-secondary">Details</button></td>
                </tr>
            `;
        });
    }

    $('#upcomingMaintenanceTable').html(html);
}

function renderMaintenanceStatus(stage) {
    if (!stage) return '<span class="badge bg-secondary">Unknown</span>';
    const normalized = stage.toLowerCase();
    if (normalized.includes('closed')) return '<span class="badge bg-success">Closed</span>';
    if (normalized.includes('cancel')) return '<span class="badge bg-danger">Cancelled</span>';
    if (normalized.includes('work order') || normalized.includes('workshop')) return '<span class="badge bg-warning text-dark">In Progress</span>';
    if (normalized.includes('review') || normalized.includes('quote')) return '<span class="badge bg-info text-dark">Review</span>';

    return `<span class="badge bg-primary">${escapeHtml(stage)}</span>`;
}

function buildContractLabel(vehicle) {
    const parts = [vehicle.contract_code, vehicle.contract_account_name].filter(Boolean);
    return parts.length ? parts.join(' - ') : (vehicle.contract_id || '-');
}

function getVehicleStatusClass(status) {
    const normalized = (status || '').toLowerCase();

    if (normalized === 'active') {
        return 'bg-success';
    }
    if (normalized === 'maintenance') {
        return 'bg-warning text-dark';
    }
    if (normalized === 'retired') {
        return 'bg-danger';
    }
    if (normalized === 'inactive') {
        return 'bg-secondary';
    }

    return 'bg-info text-dark';
}

function renderComplianceStatus(status) {
    if (status === 'Expired') {
        return '<span class="badge bg-danger">Expired</span>';
    }
    if (status === 'Expiring Soon') {
        return '<span class="badge bg-warning text-dark">Expiring Soon</span>';
    }
    if (status === 'Unknown') {
        return '<span class="badge bg-secondary">Unknown</span>';
    }

    return '<span class="badge bg-success">Valid</span>';
}

function booleanLabel(value) {
    if (value === null || value === '' || typeof value === 'undefined') {
        return '-';
    }

    return Number(value) === 1 ? 'Yes' : 'No';
}

function formatDate(value) {
    if (!value) {
        return '-';
    }

    const date = new Date(value);
    if (Number.isNaN(date.getTime())) {
        return value;
    }

    return date.toLocaleDateString(undefined, {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
    });
}

function formatDateTime(value) {
    if (!value) {
        return '-';
    }

    const date = new Date(value);
    if (Number.isNaN(date.getTime())) {
        return value;
    }

    return date.toLocaleString();
}

function formatCurrency(value) {
    if (!value) {
        return 'N0';
    }

    return 'N' + Number(value).toLocaleString();
}

function formatDecimal(value, suffix) {
    if (value === null || value === '' || typeof value === 'undefined') {
        return '-';
    }

    return Number(value).toLocaleString(undefined, { maximumFractionDigits: 2 }) + (suffix || '');
}

function formatInteger(value, suffix) {
    if (value === null || value === '' || typeof value === 'undefined') {
        return '-';
    }

    return Number(value).toLocaleString() + (suffix || '');
}

function showProfileError(message) {
    const alertBox = $('#alertBox');
    alertBox.removeClass('alert-success alert-danger alert-warning alert-info')
           .addClass('alert-danger')
           .text(message)
           .removeClass('d-none');

    setTimeout(() => {
        alertBox.addClass('d-none');
    }, 8000);
}

function escapeHtml(text) {
    return $('<div>').text(text || '').html();
}
