$(function () {
    loadDriverList();
    $('#scorecardDriverSelect').on('change', function () {
        var id = $(this).val();
        if (id) loadScorecard(id);
        else { $('#scorecardContent').addClass('d-none'); $('#scorecardEmpty').removeClass('d-none'); }
    });
});

function loadDriverList() {
    $.get('api/driver_scorecard.php', { action: 'list' }, function (res) {
        if (res.status!=='success') return;
        var h = '<option value="">Select a driver...</option>';
        (res.data||[]).forEach(function(d){ h += '<option value="'+escapeHtml(d.id)+'">'+escapeHtml(d.name)+' ('+escapeHtml(d.current_vehicle||'no vehicle')+')</option>'; });
        $('#scorecardDriverSelect').html(h);
    },'json');
}

function loadScorecard(id) {
    $.get('api/driver_scorecard.php', { action: 'show', driver_id: id }, function (res) {
        if (res.status!=='success') return;
        var d = res.data;
        $('#scorecardEmpty').addClass('d-none');
        $('#scorecardContent').removeClass('d-none');

        var driver = d.driver || {};
        var trips = d.trip_stats || {};
        var fuel = d.fuel_stats || {};
        var inc = d.incident_stats || {};

        $('#driverName').text(escapeHtml(driver.full_name||''));
        $('#driverDetails').text((driver.phone||'') + ' | License: ' + escapeHtml(d.license_number||'-'));

        var licBadge = d.license_status==='valid'?'bg-success':d.license_status==='expiring_soon'?'bg-warning text-dark':'bg-danger';
        var licText = d.license_status==='valid'?'Valid':d.license_status==='expiring_soon'?'Expiring Soon':'Expired';
        if (d.days_to_expiry !== null) licText += ' ('+Math.abs(d.days_to_expiry)+'d)';
        $('#licenseBadge').text(licText).attr('class','badge fs-6 '+licBadge);

        $('#scTotalTrips').text((trips.total_trips||0) + ' / ' + (trips.active_trips||0));
        $('#scTotalKm').text(Number(trips.total_km||0).toLocaleString() + ' km');
        $('#scFuelEfficiency').text(d.km_per_litre ? d.km_per_litre + ' km/L' : 'N/A');
        $('#scFuelCost').text('₦' + Number(fuel.total_fuel_cost||0).toLocaleString());
        $('#scIncidents').text((inc.total_incidents||0) + ' / ' + (inc.major_incidents||0));
        $('#scFuelings').text(fuel.fuel_entries||0);
        $('#scTotalLitres').text(Number(fuel.total_litres||0).toLocaleString());
        var avgCost = fuel.total_litres > 0 ? fuel.total_fuel_cost / fuel.total_litres : 0;
        $('#scAvgCostPerLitre').text('₦' + avgCost.toFixed(2));
        $('#scLicenseExpiry').text(d.license_expiry || '-');
        var days = d.days_to_expiry;
        $('#scLicenseDays').text(days !== null ? (days + 'd ' + (d.license_status === 'expired' ? 'overdue' : d.license_status === 'expiring_soon' ? 'remaining' : 'valid')) : '-');

        var ah = '';
        if (!d.recent_assignments||!d.recent_assignments.length) ah = '<tr><td colspan="3" class="text-muted text-center">No assignments</td></tr>';
        else d.recent_assignments.forEach(function(a){
            ah += '<tr><td>'+escapeHtml(a.plate_number||'-')+'</td><td>'+formatDate(a.created_at)+'</td><td>'+(a.deleted_at ? formatDate(a.deleted_at) : 'Current')+'</td></tr>';
        });
        $('#assignmentTable').html(ah);
    },'json');
}

function formatDate(d){if(!d)return'-';var dt=new Date(d);return Number.isNaN(dt.getTime())?d:dt.toLocaleDateString(undefined,{year:'numeric',month:'short',day:'numeric'});}
function escapeHtml(t){return $('<div>').text(t||'').html();}
