$(function () {
    loadList();
    loadReference();
    $('#searchBox').on('input', debounce(loadList, 300));
    $('#statusFilter, #dateFrom, #dateTo').on('change', loadList);
    $('#btnNewRequest').on('click', function () { clearForm(); $('#modalTitle').text('New Vehicle Request'); new bootstrap.Modal(document.getElementById('requestModal')).show(); });
    $('#btnSaveDraft').on('click', function () { saveRequest(function () { loadList(); bootstrap.Modal.getInstance(document.getElementById('requestModal')).hide(); }); });
    $('#btnSubmit').on('click', submitRequest);
    $('#btnApprove').on('click', function () { approveAction('approve'); });
    $('#btnReject').on('click', function () { approveAction('reject'); });
    $('#btnReturn').on('click', function () { approveAction('return'); });
    $('#btnPendingApprovals').on('click', function () { $('#statusFilter').val('pending'); loadList(); });
    $('#btnMyRequests').on('click', function () { window._showMine = !(window._showMine || false); $(this).toggleClass('btn-outline-secondary btn-primary'); loadList(); });
    $('#btnSaveAssignment').on('click', saveAssignment);
    $('#btnAIRecommend').on('click', function () { loadAIRecommendations($('#assignRequestId').val()); });
    $(document).on('click', '.btn-pick-recommendation', function () {
        var vid = $(this).data('vehicle-id');
        $('#assignVehicleId').val(vid);
        showAlert('Vehicle selected from AI recommendation', 'success');
    });
    $(document).on('click', '.btn-edit', function () { editRequest($(this).data('id')); });
    $(document).on('click', '.btn-delete', function () { deleteRequest($(this).data('id')); });
    $(document).on('click', '.btn-approve', function () { openApproval($(this).data('id')); });
    $(document).on('click', '.btn-assign', function () { openAssign($(this).data('id')); });
    $(document).on('click', '.btn-view', function () { viewRequest($(this).data('id')); });
});

var _cache = [], _refs = { vehicles: [], drivers: [] };

function clearForm() {
    $('#itemId, #pickupLocation, #destination, #journeyPurpose, #notes').val('');
    $('#startDate, #endDate').val('');
    $('#passengerCount').val(1);
    $('#priority').val('normal');
    $('#supportingDoc').val('');
}

function loadReference() {
    $.get('api/vehicle_requests.php?action=reference', function (r) {
        if (r.status !== 'success') return;
        _refs = r.data || _refs;
        var vh = '<option value="">Select vehicle</option>', dh = '<option value="">Select driver (optional)</option>';
        (_refs.vehicles || []).forEach(function (v) { vh += '<option value="' + v.id + '">' + esc(v.label) + '</option>'; });
        (_refs.drivers || []).forEach(function (d) { dh += '<option value="' + d.id + '">' + esc(d.label) + '</option>'; });
        $('#assignVehicleId').html(vh);
        $('#assignDriverId').html(dh);
    }, 'json');
}

function loadList() {
    var params = { action: 'list' };
    if (window._showMine) params.mine = '1';
    var s = $('#searchBox').val(); if (s) params.search = s;
    var st = $('#statusFilter').val(); if (st) params.status = st;
    var df = $('#dateFrom').val(); if (df) params.date_from = df;
    var dt = $('#dateTo').val(); if (dt) params.date_to = dt;
    $.get('api/vehicle_requests.php', params, function (r) {
        if (r.status !== 'success') return;
        var data = r.data || []; _cache = data;
        var t = 0, p = 0, a = 0, rj = 0;
        data.forEach(function (x) { t++; if (x.status === 'pending') p++; else if (x.status === 'approved' || x.status === 'assigned') a++; else if (x.status === 'rejected') rj++; });
        $('#kpiTotal').text(t); $('#kpiPending').text(p); $('#kpiApproved').text(a); $('#kpiRejected').text(rj);
        if (r.pending_approval_count !== undefined) $('#pendingBadge').text(r.pending_approval_count);
        var html = '';
        if (!data.length) html = '<tr><td colspan="8" class="text-center py-4 text-muted">No requests found</td></tr>';
        else data.forEach(function (x) {
            var badge = statusBadge(x.status);
            var priorityBadge = priorityLabel(x.priority);
            var dates = (x.start_date || '') + (x.end_date ? ' &rarr; ' + x.end_date : '');
            var route = (x.pickup_location || '') + (x.destination ? ' &rarr; ' + x.destination : '');
            var acts = '<div class="d-flex gap-1 justify-content-end">';
            if (x.status === 'draft' || x.status === 'returned') acts += '<button class="btn btn-sm btn-outline-primary btn-edit" data-id="' + x.id + '"><i class="bi bi-pencil"></i></button><button class="btn btn-sm btn-outline-danger btn-delete" data-id="' + x.id + '"><i class="bi bi-trash3"></i></button>';
            if (x.status === 'approved' && window._canAssign) acts += '<button class="btn btn-sm btn-outline-success btn-assign" data-id="' + x.id + '"><i class="bi bi-truck"></i> Assign</button>';
            if (x.status === 'pending' && window._canApprove) acts += '<button class="btn btn-sm btn-outline-warning btn-approve" data-id="' + x.id + '"><i class="bi bi-check2-square"></i> Review</button>';
            acts += '<button class="btn btn-sm btn-outline-info btn-view" data-id="' + x.id + '"><i class="bi bi-eye"></i></button>';
            acts += '</div>';
            html += '<tr><td class="fw-semibold"><code>' + esc(x.request_number) + '</code></td><td>' + esc(x.staff_name || '-') + '</td><td>' + esc(trunc(x.journey_purpose, 40)) + '</td><td>' + route + '</td><td>' + dates + '</td><td>' + priorityBadge + '</td><td>' + badge + '</td><td>' + acts + '</td></tr>';
        });
        $('#tableBody').html(html);
    }, 'json');
}

function saveRequest(cb) {
    var fd = new FormData();
    fd.append('id', $('#itemId').val());
    fd.append('pickup_location', $('#pickupLocation').val().trim());
    fd.append('destination', $('#destination').val().trim());
    fd.append('journey_purpose', $('#journeyPurpose').val().trim());
    fd.append('start_date', $('#startDate').val());
    fd.append('end_date', $('#endDate').val());
    fd.append('passenger_count', $('#passengerCount').val());
    fd.append('priority', $('#priority').val());
    fd.append('notes', $('#notes').val().trim());
    fd.append('csrf_token', window.CSRF_TOKEN);
    var doc = $('#supportingDoc')[0].files[0];
    if (doc) fd.append('supporting_document', doc);
    $.ajax({ url: 'api/vehicle_requests.php?action=save', method: 'POST', data: fd, processData: false, contentType: false, dataType: 'json' })
        .done(function (r) {
            if (r.status !== 'success') { showAlert(r.message, 'danger'); return; }
            $('#itemId').val(r.id || $('#itemId').val());
            showAlert(r.message, 'success');
            if (cb) cb();
        }).fail(function () { showAlert('Server error', 'danger'); });
}

function submitRequest() {
    var id = $('#itemId').val();
    if (!id || id === '0') {
        saveRequest(function () {
            id = $('#itemId').val();
            if (id && id !== '0') doSubmit(id);
        });
    } else {
        doSubmit(id);
    }
}

function doSubmit(id) {
    $.post('api/vehicle_requests.php?action=submit', { id: id, csrf_token: window.CSRF_TOKEN }, function (r) {
        if (r.status !== 'success') { showAlert(r.message, 'danger'); return; }
        showAlert(r.message, 'success');
        bootstrap.Modal.getInstance(document.getElementById('requestModal')).hide();
        loadList();
    }, 'json').fail(function () { showAlert('Server error', 'danger'); });
}

function editRequest(id) {
    var r = _cache.find(function (x) { return String(x.id) === String(id); });
    if (!r) return;
    $('#itemId').val(r.id);
    $('#pickupLocation').val(r.pickup_location || '');
    $('#destination').val(r.destination || '');
    $('#journeyPurpose').val(r.journey_purpose || '');
    $('#startDate').val(r.start_date || '');
    $('#endDate').val(r.end_date || '');
    $('#passengerCount').val(r.passenger_count || 1);
    $('#priority').val(r.priority || 'normal');
    $('#notes').val(r.notes || '');
    $('#modalTitle').text('Edit Request - ' + r.request_number);
    new bootstrap.Modal(document.getElementById('requestModal')).show();
}

function deleteRequest(id) {
    if (!confirm('Delete this request?')) return;
    $.post('api/vehicle_requests.php?action=delete', { id: id, csrf_token: window.CSRF_TOKEN }, function (r) {
        if (r.status !== 'success') { showAlert(r.message, 'danger'); return; }
        showAlert(r.message, 'success');
        loadList();
    }, 'json');
}

function openApproval(id) {
    var r = _cache.find(function (x) { return String(x.id) === String(id); });
    if (!r) return;
    $('#approvalId').val(r.id);
    $('#approvalComment').val('');
    $('#approvalInfo').html('<strong>' + esc(r.request_number) + '</strong> — ' + esc(r.journey_purpose) + '<br><small class="text-muted">' + esc(r.pickup_location) + ' &rarr; ' + esc(r.destination) + '</small>');
    var stepsHtml = '';
    var total = r.total_approvals || 0;
    var appr = r.approved_approvals || 0;
    for (var i = 1; i <= total; i++) {
        var done = i <= appr;
        stepsHtml += '<li class="list-group-item d-flex align-items-center gap-2 ' + (done ? 'text-success' : '') + '"><i class="bi bi-' + (done ? 'check-circle-fill' : 'circle') + '"></i> Step ' + i + (done ? ' (Approved)' : ' (Pending)') + '</li>';
    }
    $('#approvalSteps').html(stepsHtml || '<li class="list-group-item text-muted">No steps loaded</li>');
    new bootstrap.Modal(document.getElementById('approvalModal')).show();
}

function approveAction(action) {
    var requestId = $('#approvalId').val();
    if (!requestId) return;
    var comment = $('#approvalComment').val().trim();
    if ((action === 'reject' || action === 'return') && !comment) { showAlert('Comment is required for ' + action, 'warning'); return; }
    var url = 'api/vehicle_requests.php?action=' + action;
    $.post(url, { request_id: requestId, comment: comment, csrf_token: window.CSRF_TOKEN }, function (r) {
        if (r.status !== 'success') { showAlert(r.message, 'danger'); return; }
        showAlert(r.message, 'success');
        bootstrap.Modal.getInstance(document.getElementById('approvalModal')).hide();
        loadList();
    }, 'json').fail(function () { showAlert('Server error', 'danger'); });
}

function viewRequest(id) {
    var r = _cache.find(function (x) { return String(x.id) === String(id); });
    if (!r) return;
    var info = 'Request: <strong>' + esc(r.request_number) + '</strong><br>'
        + 'Staff: ' + esc(r.staff_name || '-') + '<br>'
        + 'Purpose: ' + esc(r.journey_purpose || '-') + '<br>'
        + 'Route: ' + esc(r.pickup_location || '-') + ' &rarr; ' + esc(r.destination || '-') + '<br>'
        + 'Dates: ' + (r.start_date || '-') + (r.end_date ? ' &rarr; ' + r.end_date : '') + '<br>'
        + 'Priority: ' + esc(r.priority || 'normal') + '<br>'
        + 'Passengers: ' + (r.passenger_count || 1) + '<br>'
        + 'Status: ' + esc(r.status) + '<br>'
        + (r.assigned_vehicle_plate ? 'Vehicle: ' + esc(r.assigned_vehicle_plate) + '<br>' : '')
        + (r.assigned_driver_name ? 'Driver: ' + esc(r.assigned_driver_name) : '');
    showAlert(info, 'info');
}

function statusBadge(s) {
    var m = { draft: 'secondary', pending: 'warning', approved: 'success', rejected: 'danger', returned: 'info', assigned: 'primary', in_progress: 'primary', completed: 'success', cancelled: 'secondary' };
    return '<span class="badge bg-' + (m[s] || 'secondary') + '">' + esc(s || 'unknown') + '</span>';
}

function priorityLabel(p) {
    var m = { low: 'success', normal: 'primary', high: 'warning', urgent: 'danger' };
    return '<span class="badge bg-' + (m[p] || 'secondary') + ' bg-opacity-10 text-' + (m[p] || 'secondary') + '">' + esc(p || 'normal') + '</span>';
}

function openAssign(id) {
    var r = _cache.find(function (x) { return String(x.id) === String(id); });
    if (!r) return;
    $('#assignRequestId').val(r.id);
    $('#assignVehicleId').val('');
    $('#assignDriverId').val('');
    $('#aiRecommendations').html('<div class="text-muted small py-2">Click "Get Recommendations" to let AI suggest the best vehicle match.</div>');
    new bootstrap.Modal(document.getElementById('assignModal')).show();
}

function saveAssignment() {
    var id = $('#assignRequestId').val();
    var vid = $('#assignVehicleId').val();
    if (!vid) { showAlert('Vehicle is required', 'warning'); return; }

    // Mark AI recommendation as accepted if it was selected
    var recVehicleId = $('#aiRecommendations .btn-pick-recommendation[data-vehicle-id="' + vid + '"]').length;
    if (recVehicleId) {
        $.post('api/ai_allocation.php?action=accept', { request_id: id, vehicle_id: vid, csrf_token: window.CSRF_TOKEN }, function () {}, 'json');
    }

    $.post('api/vehicle_requests.php?action=assign', { id: id, vehicle_id: vid, driver_id: $('#assignDriverId').val(), csrf_token: window.CSRF_TOKEN }, function (r) {
        if (r.status !== 'success') { showAlert(r.message, 'danger'); return; }
        showAlert(r.message, 'success');
        bootstrap.Modal.getInstance(document.getElementById('assignModal')).hide();
        loadList();
    }, 'json').fail(function () { showAlert('Server error', 'danger'); });
}

function loadAIRecommendations(requestId) {
    if (!requestId) return;
    $('#aiRecommendations').html('<div class="text-center py-3"><div class="spinner-border spinner-border-sm text-primary me-2"></div>AI is analyzing fleet data...</div>');

    $.get('api/ai_allocation.php', { action: 'recommend', request_id: requestId }, function (r) {
        if (r.status !== 'success') {
            $('#aiRecommendations').html('<div class="alert alert-warning mb-0 py-2">' + esc(r.message || 'Failed to get recommendations') + '</div>');
            return;
        }
        var recs = r.data || [];
        var req = r.request || {};

        if (!recs.length) {
            $('#aiRecommendations').html('<div class="alert alert-info mb-0 py-2">No suitable vehicles found.</div>');
            return;
        }

        var html = '<div class="small text-muted mb-2">Based on ' + (req.passenger_count || '?') + ' passengers, priority: ' + esc(req.priority || 'normal') + '</div>';
        html += '<div class="d-flex flex-column gap-2">';

        var colors = ['success', 'primary', 'info', 'warning', 'secondary'];
        $.each(recs, function (i, rec) {
            var color = colors[i] || 'secondary';
            var width = Math.min(rec.score, 100);
            html += '<div class="card border-' + color + ' ai-rec-card" style="cursor:pointer" onclick="$(\'#assignVehicleId\').val(' + rec.vehicle_id + ');showAlert(\'Selected: ' + esc(rec.plate_number) + '\',\'success\')">' +
                '<div class="card-body py-2 px-3">' +
                '<div class="d-flex justify-content-between align-items-center">' +
                '<div class="d-flex align-items-center gap-2">' +
                '<span class="badge bg-' + color + ' rounded-pill">#' + rec.rank + '</span>' +
                '<strong>' + esc(rec.plate_number) + '</strong>' +
                '<span class="text-muted">' + esc(rec.vehicle_type || '') + (rec.vehicle_model ? ' &middot; ' + esc(rec.vehicle_model) : '') + '</span>' +
                '<span class="badge bg-light text-dark">' + rec.seats + ' seats</span>' +
                '</div>' +
                '<div class="d-flex align-items-center gap-2">' +
                '<span class="fw-bold text-' + color + '">' + rec.score + '%</span>' +
                '<button type="button" class="btn btn-sm btn-outline-' + color + ' btn-pick-recommendation" data-vehicle-id="' + rec.vehicle_id + '">Select</button>' +
                '</div>' +
                '</div>' +
                '<div class="progress mt-1" style="height:4px"><div class="progress-bar bg-' + color + '" style="width:' + width + '%"></div></div>' +
                '<div class="d-flex flex-wrap gap-2 mt-1">' +
                '<span class="badge bg-light text-dark small" title="' + esc(rec.details.availability.detail || '') + '"><i class="bi bi-calendar-check"></i> Avail: ' + formatScore(rec.availability_score) + '</span>' +
                '<span class="badge bg-light text-dark small" title="' + esc(rec.details.type_match.detail || '') + '"><i class="bi bi-people"></i> Match: ' + formatScore(rec.type_match_score) + '</span>' +
                '<span class="badge bg-light text-dark small" title="' + esc(rec.details.fuel.detail || '') + '"><i class="bi bi-fuel-pump"></i> Fuel: ' + formatScore(rec.fuel_score) + '</span>' +
                '<span class="badge bg-light text-dark small" title="' + esc(rec.details.maintenance.detail || '') + '"><i class="bi bi-tools"></i> Maint: ' + formatScore(rec.maintenance_score) + '</span>' +
                '</div>' +
                '</div>' +
                '</div>';
        });

        html += '</div>';
        $('#aiRecommendations').html(html);
    }, 'json').fail(function () {
        $('#aiRecommendations').html('<div class="alert alert-danger mb-0 py-2">Server error loading recommendations</div>');
    });
}

function formatScore(val) {
    if (val === undefined || val === null) return '-';
    return Math.round(val) + '%';
}

function showAlert(msg, type) { var box = $('#alertBox'); box.removeClass('d-none alert-success alert-danger alert-warning alert-info').addClass('alert-' + type).html(msg); setTimeout(function () { box.addClass('d-none'); }, 8000); }
function esc(t) { return $('<div>').text(t || '').html(); }
function trunc(s, n) { return s && s.length > n ? s.substring(0, n) + '...' : s; }
function debounce(fn, ms) { var t; return function () { var c = this, a = arguments; clearTimeout(t); t = setTimeout(function () { fn.apply(c, a); }, ms); }; }


