const API = 'api/maintenance.php';

let _intervals = [];
let _vehicles = [];
let _saving = false;

$(function () {
    loadVehicles();
    loadIntervals();
    $('#btnAddInterval').on('click', () => openIntervalModal());
    $('#btnSaveInterval').on('click', saveInterval);
    $('#btnCheckDue').on('click', checkDueServices);
    $('#btnGeneratePm').on('click', generatePmJob);
    $('#btnRefreshIntervals').on('click', loadIntervals);
    $('#filterDueOnly').on('change', loadIntervals);
    $('#filterVehicleSearch').on('input', debounce(loadIntervals, 300));
    $(document).on('click', '.btn-edit-interval', function () {
        openIntervalModal($(this).data('id'));
    });
    $(document).on('click', '.btn-delete-interval', function () {
        deleteInterval($(this).data('id'));
    });
    $(document).on('click', '.btn-generate-pm', function () {
        openGeneratePmModal($(this).data('id'));
    });
    $('#editIntervalKm, #editIntervalDays').on('input', function () {
        const km = parseInt($('#editIntervalKm').val()) || 0;
        const days = parseInt($('#editIntervalDays').val()) || 0;
        $('#btnSaveInterval').prop('disabled', km <= 0 && days <= 0);
    });
    $('#intervalModal').on('hidden.bs.modal', () => {
        $('#intervalForm')[0]?.reset();
        $('#editIntervalId').val('');
        $('#editIntervalKm').val(5000);
        $('#editIntervalDays').val(90);
    });
});

function loadVehicles() {
    $.get(API, { action: 'reference_data' }, (res) => {
        if (res.status === 'success' && res.data?.vehicles) {
            _vehicles = res.data.vehicles;
            const sel = $('#editVehicleId');
            sel.find('option:not(:first)').remove();
            _vehicles.forEach((v) => {
                sel.append('<option value="' + v.id + '">' + esc(v.label) + '</option>');
            });
        }
    });
}

function loadIntervals() {
    const tbody = $('#intervalTableBody');
    tbody.html('<tr><td colspan="7" class="text-center text-muted py-4">Loading...</td></tr>');

    const params = { action: 'service_intervals' };
    if ($('#filterDueOnly').is(':checked')) params.due_only = '1';

    $.get(API, params, (res) => {
        if (res.status === 'success') {
            _intervals = res.data || [];
            const search = $('#filterVehicleSearch').val().toLowerCase().trim();
            let filtered = _intervals;
            if (search) {
                filtered = _intervals.filter(r => (r.plate_number || '').toLowerCase().includes(search));
            }
            renderTable(filtered);
            updateKpis(_intervals);
        } else {
            tbody.html('<tr><td colspan="7" class="text-center text-danger py-4">' + esc(res.message || 'Error') + '</td></tr>');
        }
    });
}

function renderTable(data) {
    const tbody = $('#intervalTableBody');
    if (!data.length) {
        tbody.html('<tr><td colspan="7" class="text-center text-muted py-4">No service schedules defined. Click "Add Schedule" to create one.</td></tr>');
        return;
    }
    tbody.html(data.map((r) => {
        const dueIcon = r.is_due ? '<span class="badge bg-danger ms-1"><i class="bi bi-exclamation-triangle-fill"></i> DUE</span>' : '';
        const statusBadge = r.is_active
            ? '<span class="badge bg-success">Active</span>'
            : '<span class="badge bg-secondary">Inactive</span>';

        let intervalStr = '';
        if (r.interval_type === 'mileage') intervalStr = comma(r.interval_km) + ' km';
        else if (r.interval_type === 'time') intervalStr = r.interval_days + ' days';
        else intervalStr = comma(r.interval_km) + ' km / ' + r.interval_days + ' days';

        let lastStr = '-';
        if (r.last_service_date) {
            lastStr = r.last_service_date;
            if (r.last_service_mileage > 0) lastStr += ' (' + comma(r.last_service_mileage) + ' km)';
        }

        let dueStr = '-';
        if (r.due_date || r.due_mileage > 0) {
            const parts = [];
            if (r.due_date) {
                const diff = Math.ceil((new Date(r.due_date) - new Date()) / (1000 * 60 * 60 * 24));
                const label = diff < 0 ? '<span class="text-danger fw-bold">' + Math.abs(diff) + 'd overdue</span>'
                    : diff === 0 ? '<span class="text-warning fw-bold">Today</span>'
                    : '<span class="text-muted">' + diff + 'd</span>';
                parts.push(esc(r.due_date) + ' <small>' + label + '</small>');
            }
            if (r.due_mileage > 0) {
                const remain = (r.due_mileage - (r.current_odometer || 0));
                const kmLabel = remain <= 0 ? '<span class="text-danger fw-bold">over</span>'
                    : '<span class="text-muted">(' + comma(remain) + ' km left)</span>';
                parts.push(comma(r.due_mileage) + ' km <small>' + kmLabel + '</small>');
            }
            dueStr = parts.join(' / ') + dueIcon;
        }

        const genBtn = r.is_due && r.is_active
            ? '<button class="btn btn-sm btn-outline-success btn-generate-pm me-1" data-id="' + r.id + '" title="Generate PM Job"><i class="bi bi-tools"></i></button>'
            : '';
        const odometer = r.current_odometer ? comma(r.current_odometer) + ' km' : '-';

        return '<tr class="' + (r.is_due ? 'table-warning' : '') + '">' +
            '<td><strong>' + esc(r.plate_number || '-') + '</strong><br><small class="text-muted">' + esc(r.vehicle_model || r.vehicle_type || '') + ' | Odo: ' + odometer + '</small></td>' +
            '<td>' + esc(r.task_description || '-') + '</td>' +
            '<td>' + intervalStr + '</td>' +
            '<td>' + lastStr + '</td>' +
            '<td>' + dueStr + '</td>' +
            '<td>' + statusBadge + '</td>' +
            '<td style="white-space:nowrap">' +
            genBtn +
            '<button class="btn btn-sm btn-outline-primary btn-edit-interval me-1" data-id="' + r.id + '" title="Edit"><i class="bi bi-pencil"></i></button>' +
            '<button class="btn btn-sm btn-outline-danger btn-delete-interval" data-id="' + r.id + '" title="Delete"><i class="bi bi-trash"></i></button>' +
            '</td></tr>';
    }).join(''));
}

function updateKpis(data) {
    const dueDate = data.filter(r => r.is_due && r.date_due).length;
    const dueMileage = data.filter(r => r.is_due && r.mileage_due).length;
    const onTrack = data.filter(r => r.is_active && !r.is_due).length;
    $('#kpiDueDate').text(dueDate);
    $('#kpiDueMileage').text(dueMileage);
    $('#kpiOnTrack').text(onTrack);
    $('#kpiTotal').text(data.filter(r => r.is_active).length);
}

function openIntervalModal(id) {
    id = id || null;
    const form = $('#intervalForm')[0];
    if (form) form.reset();
    $('#editIntervalId').val(id || '');
    $('#editIsActive').val('1');
    $('#editIntervalType').val('both');
    $('#editIntervalKm').val(5000);
    $('#editIntervalDays').val(90);
    $('#intervalModalTitle').text(id ? 'Edit Service Schedule' : 'Add Service Schedule');

    if (id) {
        const r = _intervals.find(i => String(i.id) === String(id));
        if (r) {
            $('#editVehicleId').val(r.vehicle_id);
            $('#editTaskDescription').val(r.task_description || '');
            $('#editIntervalType').val(r.interval_type || 'both');
            $('#editIsActive').val(String(r.is_active));
            $('#editIntervalKm').val(r.interval_km || 0);
            $('#editIntervalDays').val(r.interval_days || 0);
        }
    }
    $('#intervalModal').modal('show');
}

function saveInterval() {
    if (_saving) return;
    const vehicleId = $('#editVehicleId').val();
    if (!vehicleId) { showToast('Please select a vehicle', 'danger'); return; }
    _saving = true;
    const btn = $('#btnSaveInterval').prop('disabled', true);

    $.post(API + '?action=save_service_interval', {
        id: $('#editIntervalId').val(),
        vehicle_id: vehicleId,
        task_description: $('#editTaskDescription').val(),
        interval_type: $('#editIntervalType').val(),
        interval_km: $('#editIntervalKm').val(),
        interval_days: $('#editIntervalDays').val(),
        is_active: $('#editIsActive').val()
    }, (res) => {
        if (res.status === 'success') {
            $('#intervalModal').modal('hide');
            loadIntervals();
            showToast('Schedule saved!');
        } else {
            showToast(res.message || 'Save failed', 'danger');
        }
    }).always(() => { _saving = false; btn.prop('disabled', false); });
}

function deleteInterval(id) {
    if (!confirm('Delete this service schedule?')) return;
    $.post(API + '?action=delete_service_interval', { id: id }, (res) => {
        if (res.status === 'success') {
            loadIntervals();
            showToast('Schedule deleted');
        } else {
            showToast(res.message || 'Delete failed', 'danger');
        }
    });
}

function checkDueServices() {
    $.get(API, { action: 'check_due_services' }, (res) => {
        if (res.status === 'success') {
            const due = res.data || [];
            if (!due.length) {
                showToast('No services are currently due!', 'success');
                return;
            }
            showToast(due.length + ' service(s) due now. Check the table for details.', 'warning');
            loadIntervals();
        }
    });
}

let _generateIntervalId = null;

function openGeneratePmModal(intervalId) {
    _generateIntervalId = intervalId;
    const r = _intervals.find(i => String(i.id) === String(intervalId));
    if (r) {
        $('#generatePmInfo').html(
            '<strong>Vehicle:</strong> ' + esc(r.plate_number || '-') + '<br>' +
            '<strong>Task:</strong> ' + esc(r.task_description || 'Preventive Maintenance') + '<br>' +
            '<strong>Due:</strong> ' + (r.due_date || '') + (r.due_mileage > 0 ? ' / ' + comma(r.due_mileage) + ' km' : '') + '<br>' +
            '<strong>Current Odometer:</strong> ' + comma(r.current_odometer || 0) + ' km'
        );
    }
    $('#generatePmModal').modal('show');
}

function generatePmJob() {
    if (!_generateIntervalId) return;
    const btn = $('#btnGeneratePm').prop('disabled', true);
    $.post(API + '?action=generate_pm_job', { interval_id: _generateIntervalId }, (res) => {
        if (res.status === 'success') {
            $('#generatePmModal').modal('hide');
            loadIntervals();
            showToast('PM job created: ' + (res.data?.job_title || ''));
        } else {
            showToast(res.message || 'Generation failed', 'danger');
        }
    }).always(() => { btn.prop('disabled', false); });
}

function showToast(msg, type) {
    type = type || 'success';
    const el = document.createElement('div');
    el.className = 'position-fixed top-0 end-0 p-3';
    el.style.cssText = 'z-index:9999';
    el.innerHTML = '<div class="alert alert-' + type + ' alert-dismissible fade show" role="alert">' +
        msg + '<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>';
    document.body.appendChild(el);
    setTimeout(() => el.remove(), 5000);
}

function esc(text) {
    const d = document.createElement('div');
    d.textContent = text == null ? '' : String(text);
    return d.innerHTML;
}

function comma(n) {
    return Number(n || 0).toLocaleString();
}

function debounce(fn, ms) {
    let t;
    return function (...a) { clearTimeout(t); t = setTimeout(() => fn(...a), ms); };
}
