$(function () {
    $('#overviewMonth').val(new Date().toISOString().slice(0, 7));
    loadDrivers();
    loadOverview();
    $('#overviewMonth, #overviewDriver').on('change', loadOverview);
    $('#btnRefreshOverview').on('click', loadOverview);

    $('#btnExportOffDutyCsv').on('click', function () { window.location.href = 'api/data_export.php?type=driver_off_duty&format=csv&month=' + $('#overviewMonth').val(); });
    $('#btnExportOffDutyXlsx').on('click', function () { window.location.href = 'api/data_export.php?type=driver_off_duty&format=xlsx&month=' + $('#overviewMonth').val(); });
    $('#btnExportOffDutyPdf').on('click', function () { window.location.href = 'api/data_export.php?type=driver_off_duty&format=pdf&month=' + $('#overviewMonth').val(); });
});

function loadDrivers() {
    $.get('api/drivers.php', { action: 'list', limit: 1000 }, function (r) {
        if (r.status !== 'success') return;
        var rows = r.data || [];
        var html = '<option value="">All drivers</option>';
        rows.forEach(function (d) { html += '<option value="' + d.id + '">' + escapeHtml(d.full_name || d.name || '-') + '</option>'; });
        $('#overviewDriver').html(html);
    }, 'json');
}

function loadOverview() {
    var params = { action: 'overview', month: $('#overviewMonth').val() };
    var driverId = $('#overviewDriver').val();
    if (driverId) params.driver_id = driverId;

    $.get('api/driver_off_duty.php', params, function (res) {
        if (res.status !== 'success') return;
        var rows = res.data || [];
        var html = '';
        if (!rows.length) html = '<tr><td colspan="6" class="text-center py-4 text-muted">No data</td></tr>';
        else rows.forEach(function (r) {
            var remaining = Math.max(0, 5 - r.days_taken);
            var progress = '<div class="progress" style="height:6px"><div class="progress-bar ' + (remaining === 0 ? 'bg-danger' : r.days_taken >= 3 ? 'bg-warning' : 'bg-success') + '" style="width:' + (r.days_taken / 5 * 100) + '%"></div></div>';
            html += '<tr><td>' + escapeHtml(r.driver_name || '-') + '</td><td>' + escapeHtml(r.month_year) + '</td><td>' + r.days_taken + ' ' + progress + '</td><td>5</td><td class="fw-semibold ' + (remaining === 0 ? 'text-danger' : '') + '">' + remaining + '</td>' +
                '<td class="text-end"><a href="driver_profile.php?id=' + r.driver_id + '" class="btn btn-sm btn-outline-primary"><i class="bi bi-person"></i> Profile</a></td></tr>';
        });
        $('#overviewTable').html(html);
    }, 'json');
}

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