let _tripCache = [];

$(function () {
    loadTrips();
    loadVehiclesForTrips();
    loadDriversForTrips();

    $('#tripSearch, #tripVehicleFilter, #tripStatusFilter, #tripDateFrom, #tripDateTo').on('change', loadTrips);
    $('#tripSearch').on('input', debounce(loadTrips, 300));
    $('#btnRefreshTrips').on('click', loadTrips);
    $('#btnAddTrip').on('click', function () {
        clearTripForm();
        $('#tripModalTitle').text('New Trip');
        $('#tripModalSubtitle').text('Log a vehicle journey');
        $('#trip_status').val('active');
        new bootstrap.Modal(document.getElementById('tripModal')).show();
    });
    $('#saveTrip').on('click', saveTrip);
    $(document).on('click', '.btn-edit-trip', function () {
        const row = _tripCache.find(r => String(r.id) === String($(this).data('id')));
        if (row) populateTripForm(row);
    });
    $(document).on('click', '.btn-end-trip', function () {
        endTrip($(this).data('id'));
    });
    $(document).on('click', '.btn-delete-trip', function () {
        deleteTrip($(this).data('id'));
    });
    $('#btnExportTripsCsv').on('click', function () { window.location.href = 'api/data_export.php?type=trips&format=csv'; });
    $('#btnExportTripsXlsx').on('click', function () { window.location.href = 'api/data_export.php?type=trips&format=xlsx'; });
    $('#btnExportTripsPdf').on('click', function () { window.location.href = 'api/data_export.php?type=trips&format=pdf'; });
});

function loadVehiclesForTrips() {
    $.get('api/compliance.php', { action: 'vehicles' }, function (res) {
        if (res.status === 'success') {
            populateSelect('#tripVehicleFilter', res.data, 'All');
            populateSelect('#trip_vehicle_id', res.data, 'Select vehicle');
        }
    }, 'json');
}

function loadDriversForTrips() {
    $.get('api/drivers.php', { action: 'list' }, function (res) {
        if (res.status === 'success') {
            const drivers = (res.data || []).map(function (d) { return { id: d.id, label: d.full_name, name: d.full_name }; });
            populateSelect('#trip_driver_id', drivers, 'Select driver');
        }
    }, 'json');
}

function loadTrips() {
    const params = {
        action: 'list',
        search: $('#tripSearch').val(),
        status: $('#tripStatusFilter').val(),
        vehicle_id: $('#tripVehicleFilter').val(),
        date_from: $('#tripDateFrom').val(),
        date_to: $('#tripDateTo').val()
    };

    $.get('api/trips.php', params, function (res) {
        if (res.status !== 'success') { $('#tripTable').html('<tr><td colspan="9" class="text-center text-muted py-4">Error loading trips</td></tr>'); return; }

        const rows = res.data || [];
        _tripCache = rows;

        let active = 0, completed = 0, totalKm = 0;
        rows.forEach(function (r) {
            if (r.status === 'active') active++;
            if (r.status === 'completed') completed++;
            if (r.end_odometer && r.start_odometer) totalKm += (r.end_odometer - r.start_odometer);
        });
        $('#kpiActiveTrips').text(active);
        $('#kpiCompletedTrips').text(completed);
        $('#kpiTotalTrips').text(rows.length);
        $('#kpiTotalKm').text(totalKm.toLocaleString());

        let html = '';
        if (!rows.length) { html = '<tr><td colspan="9" class="text-center text-muted py-4">No trips found</td></tr>'; }
        else {
            rows.forEach(function (r) {
                const dist = r.end_odometer && r.start_odometer ? (r.end_odometer - r.start_odometer).toLocaleString() + ' km' : '-';
                const statusBadge = r.status === 'active' ? '<span class="badge bg-success">Active</span>' : r.status === 'completed' ? '<span class="badge bg-secondary">Completed</span>' : '<span class="badge bg-danger">Cancelled</span>';
                html += '<tr><td>' + escapeHtml(r.plate_number || '-') + '</td><td>' + escapeHtml(r.driver_name || '-') + '</td><td>' + formatDate(r.start_date) + '</td><td>' + formatDate(r.end_date) + '</td><td>' + dist + '</td><td>' + escapeHtml(r.purpose || '-') + '</td><td>' + escapeHtml(r.start_location || '') + (r.end_location ? ' → ' + escapeHtml(r.end_location) : '') + '</td><td>' + statusBadge + '</td><td class="text-end"><div class="d-flex gap-1 justify-content-end">' +
                    (r.status === 'active' ? '<button class="btn btn-sm btn-outline-success btn-end-trip" title="End Trip" data-id="' + r.id + '"><i class="bi bi-stop-fill"></i></button> ' : '') +
                    '<button class="btn btn-sm btn-outline-primary btn-edit-trip" title="Edit" data-id="' + r.id + '"><i class="bi bi-pencil"></i></button> ' +
                    '<button class="btn btn-sm btn-outline-danger btn-delete-trip" title="Delete" data-id="' + r.id + '"><i class="bi bi-trash3"></i></button></div></td></tr>';
            });
        }
        $('#tripTable').html(html);
    }, 'json');
}

function saveTrip() {
    const payload = {
        id: $('#trip_id').val(),
        vehicle_id: $('#trip_vehicle_id').val(),
        driver_id: $('#trip_driver_id').val(),
        start_date: $('#trip_start_date').val(),
        end_date: $('#trip_end_date').val(),
        start_odometer: $('#trip_start_odometer').val(),
        end_odometer: $('#trip_end_odometer').val(),
        start_location: $('#trip_start_location').val(),
        end_location: $('#trip_end_location').val(),
        purpose: $('#trip_purpose').val(),
        route_description: $('#trip_route_description').val(),
        status: $('#trip_status').val(),
        notes: $('#trip_notes').val(),
        csrf_token: window.CSRF_TOKEN
    };

    if (!payload.vehicle_id || !payload.start_date) { showToast('Vehicle and start date are required', 'danger'); return; }

    $.post('api/trips.php?action=save', payload, function (res) {
        if (res.status !== 'success') { showToast(res.message || 'Error saving trip', 'danger'); return; }
        bootstrap.Modal.getInstance(document.getElementById('tripModal')).hide();
        loadTrips();
        showToast('Trip saved!', 'success');
    }, 'json').fail(function () { showToast('Server error', 'danger'); });
}

function endTrip(id) {
    const odometer = prompt('End odometer reading (km):');
    $.post('api/trips.php?action=end', { id: id, end_odometer: odometer, end_location: '', csrf_token: window.CSRF_TOKEN }, function (res) {
        if (res.status === 'success') { loadTrips(); showToast('Trip ended', 'success'); }
        else showToast(res.message, 'danger');
    }, 'json');
}

function deleteTrip(id) {
    if (!confirm('Delete this trip?')) return;
    $.post('api/trips.php?action=delete', { id: id, csrf_token: window.CSRF_TOKEN }, function (res) {
        if (res.status === 'success') { loadTrips(); showToast('Trip deleted', 'success'); }
        else showToast(res.message, 'danger');
    }, 'json');
}

function clearTripForm() {
    $('#tripForm')[0].reset();
    $('#trip_id').val('');
}

function populateTripForm(row) {
    clearTripForm();
    $('#trip_id').val(row.id);
    $('#trip_vehicle_id').val(row.vehicle_id);
    $('#trip_driver_id').val(row.driver_id || '');
    $('#trip_start_date').val(row.start_date ? row.start_date.slice(0, 16) : '');
    $('#trip_end_date').val(row.end_date ? row.end_date.slice(0, 16) : '');
    $('#trip_start_odometer').val(row.start_odometer || '');
    $('#trip_end_odometer').val(row.end_odometer || '');
    $('#trip_start_location').val(row.start_location || '');
    $('#trip_end_location').val(row.end_location || '');
    $('#trip_purpose').val(row.purpose || '');
    $('#trip_route_description').val(row.route_description || '');
    $('#trip_status').val(row.status || 'active');
    $('#trip_notes').val(row.notes || '');
    $('#tripModalTitle').text('Edit Trip');
    $('#tripModalSubtitle').text('Update trip details');
    new bootstrap.Modal(document.getElementById('tripModal')).show();
}

function populateSelect(sel, rows, placeholder) {
    let h = '<option value="">' + escapeHtml(placeholder) + '</option>';
    (rows || []).forEach(function (r) { h += '<option value="' + escapeHtml(r.id) + '">' + escapeHtml(r.label || r.name || '-') + '</option>'; });
    $(sel).html(h);
}

function formatDate(d) { if (!d) return '-'; const dt = new Date(d); return Number.isNaN(dt.getTime()) ? d : dt.toLocaleDateString(undefined, { year:'numeric', month:'short', day:'numeric' }); }

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

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

function debounce(fn, ms) { let timer; return function () { var ctx = this, args = arguments; clearTimeout(timer); timer = setTimeout(function () { fn.apply(ctx, args); }, ms); }; }
