$(document).ready(function () {
    loadDrivers();

    $('#driver_photo').on('change', function () {
        const file = this.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function (e) {
                $('#driverPhotoPreview').show();
                $('#photoPreviewImg').attr('src', e.target.result);
            };
            reader.readAsDataURL(file);
        }
    });

    $('#btnAddDriver').on('click', function () {
        clearDriverForm();
        $('#driverModalTitle').text('Add Driver');
        showDriverModal();
        $.get('api/drivers.php', { action: 'next_code' }, function (res) {
            if (res.status === 'success' && res.code) {
                $('#driver_id_code').val(res.code);
            }
        });
    });

    $('#btnRefreshDrivers').on('click', function () {
        _driverFilter = '';
        $('#searchDriver').val('');
        loadDrivers('');
    });

    $('.kpi-card[data-filter]').on('click', function () {
        var f = $(this).data('filter');
        if (f === 'total') f = '';
        if (_driverFilter === f) { _driverFilter = ''; } else { _driverFilter = f; }
        $('.kpi-card').removeClass('border-primary');
        if (_driverFilter) { $(this).addClass('border-primary'); }
        $('#searchDriver').val('');
        loadDrivers('');
    });

    let typingTimer;
    $('#searchDriver').on('keyup', function () {
        clearTimeout(typingTimer);
        const search = $(this).val();

        typingTimer = setTimeout(function () {
            if (search) _driverFilter = '';
            $('.kpi-card').removeClass('border-primary');
            loadDrivers(search);
        }, 350);
    });

    $('#saveDriver').on('click', saveDriver);

    $(document).on('click', '.btn-edit-driver', function () {
        const id = $(this).data('id');
        if (!id) return;

        $.ajax({
            url: 'api/drivers.php',
            method: 'GET',
            dataType: 'json',
            data: { action: 'get', id: id },
            success: function (res) {
                if (res.status !== 'success') {
                    showDriverError(res.message || 'Failed to load driver');
                    return;
                }
                populateDriverForm(res.data);
            },
            error: function () {
                showDriverError('Server error while loading driver');
            }
        });
    });

    $(document).on('click', '.btn-delete-driver', function () {
        const id = $(this).data('id');
        deleteDriver(id);
    });

    $(document).on('click', '.btn-view-driver', function () {
        const id = $(this).data('id');
        if (id) {
            window.location.href = 'driver_profile.php?id=' + id;
        }
    });
    $('#btnExportDriversCsv').on('click', function () { window.location.href = 'api/data_export.php?type=drivers&format=csv'; });
    $('#btnExportDriversXlsx').on('click', function () { window.location.href = 'api/data_export.php?type=drivers&format=xlsx'; });
    $('#btnExportDriversPdf').on('click', function () { window.location.href = 'api/data_export.php?type=drivers&format=pdf'; });
});

var _driverSearch = '';
var _driverOffset = 0;
var _driverLimit = 50;
var _driverHasMore = false;

function loadDrivers(search) {
    if (search !== undefined) {
        _driverSearch = search;
        _driverOffset = 0;
        $('#driverTable').html('<tr><td colspan="5" class="text-center text-muted">Loading drivers...</td></tr>');
        $('#driverLoadMoreRow').remove();
    }

    $.ajax({
        url: 'api/drivers.php',
        method: 'GET',
        dataType: 'json',
        data: { action: 'list', search: _driverSearch, filter: _driverFilter, limit: _driverLimit + 1, offset: _driverOffset },
        success: function (res) {
            if (res.status !== 'success') {
                showDriverError(res.message || 'Failed to load drivers');
                if (_driverOffset === 0) {
                    $('#driverTable').html('<tr><td colspan="5" class="text-center text-muted">' + escapeHtml(res.message || 'Failed to load drivers') + '</td></tr>');
                }
                return;
            }

            renderDriverKpis(res.meta || {});
            var rows = res.data || [];
            _driverHasMore = rows.length > _driverLimit;
            if (_driverHasMore) rows.pop();

            renderDriverTable(rows, _driverOffset === 0);

            if (_driverOffset === 0) {
                $('#driverTable').closest('.table-responsive').append('' +
                    '<div id="driverLoadMoreRow" class="text-center py-2">' +
                    (_driverHasMore ? '<button type="button" class="btn btn-sm btn-outline-primary" id="btnLoadMoreDrivers">Load More</button>' : '') +
                    '</div>');
            } else {
                var $btn = $('#btnLoadMoreDrivers');
                if (_driverHasMore) {
                    $btn.prop('disabled', false).html('Load More');
                } else {
                    $btn.prop('disabled', true).text('All loaded');
                }
            }

            _driverOffset += _driverLimit;
        },
        error: function () {
            showDriverError('Server error while loading drivers');
        }
    });
}

$(document).on('click', '#btnLoadMoreDrivers', function () {
    loadDrivers();
});

var _driverFilter = '';

function renderDriverKpis(meta) {
    $('#kpiDriversTotal').text(meta.total || 0);
    $('#kpiDriversActive').text(meta.active || 0);
    $('#kpiDriversInactive').text(meta.inactive || 0);
    $('#kpiDriversExpiring').text(meta.expiring_soon || 0);
    $('#kpiDriversExpired').text(meta.expired || 0);
}

function renderDriverTable(drivers, replace) {
    if (!drivers.length) {
        if (replace) {
            $('#driverTable').html('<tr><td colspan="5" class="text-center text-muted">No drivers found</td></tr>');
        }
        return;
    }

    var html = '';

    $.each(drivers, function (_, driver) {
        var picHtml = driver.driver_photo ? 
            '<img src="uploads/drivers/' + escapeHtml(driver.driver_photo) + '" class="driver-pic-list me-2" alt="Photo" onerror="this.style.display=\'none\'">' : '';

        var contactParts = [];
        if (driver.phone) contactParts.push('<div>' + escapeHtml(driver.phone) + '</div>');
        if (driver.driver_address) contactParts.push('<div class="text-muted small">' + escapeHtml(driver.driver_address) + '</div>');

        var licenseNumber = driver.license_number
            ? '<div>' + escapeHtml(driver.license_number) + '</div>'
            : '<div class="text-muted">No license number</div>';

        var licenseExpiry = driver.license_valid_until
            ? '<div class="text-muted small">Valid until ' + formatDate(driver.license_valid_until) + '</div>'
            : '<div class="text-muted small">No expiry date</div>';

        html += '<tr>' +
            '<td>' + picHtml + '<div class="fw-semibold">' + escapeHtml(driver.full_name || 'Unnamed Driver') + '</div><div class="text-muted small">' + escapeHtml(driver.driver_id_code || 'No code') + '</div></td>' +
            '<td>' + (contactParts.join('') || '<span class="text-muted">No contact details</span>') + '</td>' +
            '<td>' + licenseNumber + licenseExpiry + '</td>' +
            '<td>' + renderDriverStatus(driver) + '</td>' +
            '<td><div class="d-flex flex-wrap gap-2">' +
                '<button type="button" class="btn btn-sm btn-info btn-view-driver" data-id="' + driver.id + '">View</button>' +
                '<button type="button" class="btn btn-sm btn-warning btn-edit-driver" data-id="' + driver.id + '">Edit</button>' +
                '<button type="button" class="btn btn-sm btn-danger btn-delete-driver" data-id="' + driver.id + '">Delete</button>' +
            '</div></td>' +
        '</tr>';
    });

    if (replace) {
        $('#driverTable').html(html);
    } else {
        $('#driverTable').append(html);
    }
}

function saveDriver() {
    const formData = new FormData();
    formData.append('id', $('#driver_id').val());
    formData.append('driver_id_code', $('#driver_id_code').val().trim());
    formData.append('surname', $('#driver_surname').val().trim());
    formData.append('first_name', $('#driver_first_name').val().trim());
    formData.append('other_name', $('#driver_other_name').val().trim());
    formData.append('full_name', $('#driver_full_name').val().trim());
    formData.append('phone', $('#driver_phone').val().trim());
    formData.append('driver_address', $('#driver_address').val().trim());
    formData.append('date_of_birth', $('#driver_date_of_birth').val());
    formData.append('resumption_date', $('#driver_resumption_date').val());
    formData.append('confirmation_date', $('#driver_confirmation_date').val());
    formData.append('exit_date', $('#driver_exit_date').val());
    formData.append('remarks', $('#driver_remarks').val().trim());
    formData.append('license_number', $('#driver_license_number').val().trim());
    formData.append('license_valid_until', $('#driver_license_valid_until').val());
    formData.append('driver_status', $('#driver_status').val());
    formData.append('active_status', $('#driver_active_status').val());
    formData.append('next_of_kin_name', $('#next_of_kin_name').val().trim());
    formData.append('next_of_kin_phone', $('#next_of_kin_phone').val().trim());
    formData.append('guarantor_name', $('#guarantor_name').val().trim());
    formData.append('guarantor_phone', $('#guarantor_phone').val().trim());
    formData.append('guarantor_address', $('#guarantor_address').val().trim());

    const fileInput = $('#driver_photo')[0];
    if (fileInput.files && fileInput.files[0]) {
        formData.append('driver_photo', fileInput.files[0]);
    }

    if (!formData.get('full_name')) {
        const fullName = [formData.get('surname'), formData.get('first_name'), formData.get('other_name')]
            .filter(Boolean)
            .join(' ')
            .replace(/\s+/g, ' ')
            .trim();
        formData.set('full_name', fullName);
    }

    if (!formData.get('full_name')) {
        showDriverError('Full name is required');
        return;
    }

    if (saveDriver._submitting) return;
    saveDriver._submitting = true;
    var $btn = $('#saveDriver').prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span>Saving...');

    $.ajax({
        url: 'api/drivers.php?action=save',
        method: 'POST',
        dataType: 'json',
        data: formData,
        processData: false,
        contentType: false,
        success: function (res) {
            if (res.status !== 'success') {
                showDriverError(res.message || 'Unable to save driver');
                return;
            }

            hideDriverModal();
            loadDrivers($('#searchDriver').val());
            showDriverSuccess('Driver saved successfully');
        },
        error: function () {
            showDriverError('Server error while saving driver');
        },
        complete: function () {
            saveDriver._submitting = false;
            $btn.prop('disabled', false).text('Save Driver');
        }
    });
}

function populateDriverForm(driver) {
    clearDriverForm();

    $('#driver_id').val(driver.id || '');
    $('#driver_id_code').val(driver.driver_id_code || '');
    $('#driver_surname').val(driver.surname || '');
    $('#driver_first_name').val(driver.first_name || '');
    $('#driver_other_name').val(driver.other_name || '');
    $('#driver_full_name').val(driver.full_name || '');
    $('#driver_phone').val(driver.phone || '');
    $('#driver_address').val(driver.driver_address || '');
    $('#driver_date_of_birth').val(normalizeDateInput(driver.date_of_birth));
    $('#driver_resumption_date').val(normalizeDateInput(driver.resumption_date));
    $('#driver_confirmation_date').val(normalizeDateInput(driver.confirmation_date));
    $('#driver_exit_date').val(normalizeDateInput(driver.exit_date));
    $('#driver_remarks').val(driver.remarks || '');
    $('#driver_license_number').val(driver.license_number || '');
    $('#driver_license_valid_until').val(normalizeDateInput(driver.license_valid_until));
    $('#driver_status').val(driver.driver_status || (Number(driver.active_status) === 1 ? 'Active' : 'Inactive'));
    $('#driver_active_status').val(String(driver.active_status ? 1 : 0));
    $('#next_of_kin_name').val(driver.next_of_kin_name || '');
    $('#next_of_kin_phone').val(driver.next_of_kin_phone || '');
    $('#guarantor_name').val(driver.guarantor_name || '');
    $('#guarantor_phone').val(driver.guarantor_phone || '');
    $('#guarantor_address').val(driver.guarantor_address || '');

    if (driver.driver_photo) {
        $('#driverPhotoPreview').show().find('#photoPreviewImg').attr('src', 'uploads/drivers/' + driver.driver_photo);
    }

    $('#driverModalTitle').text('Edit Driver');
    showDriverModal();
}

function deleteDriver(id) {
    if (!id || !confirm('Are you sure you want to delete this driver?')) {
        return;
    }

    $.ajax({
        url: 'api/drivers.php?action=delete',
        method: 'POST',
        dataType: 'json',
        data: { id: id },
        success: function (res) {
            if (res.status !== 'success') {
                showDriverError(res.message || 'Unable to delete driver');
                return;
            }

            loadDrivers($('#searchDriver').val());
            showDriverSuccess('Driver deleted successfully');
        },
        error: function () {
            showDriverError('Server error while deleting driver');
        }
    });
}

function renderDriverStatus(driver) {
    const isActive = Number(driver.active_status) === 1;
    const expiryClass = getExpiryClass(driver.license_valid_until);
    const expiryLabel = getExpiryLabel(driver.license_valid_until);

    return `
        <div class="d-flex flex-column gap-2">
            <span class="badge ${isActive ? 'bg-success' : 'bg-secondary'}">${escapeHtml(driver.driver_status || (isActive ? 'Active' : 'Inactive'))}</span>
            <span class="badge ${expiryClass}">${escapeHtml(expiryLabel)}</span>
        </div>
    `;
}

function getExpiryClass(dateValue) {
    if (!dateValue) {
        return 'bg-light text-dark border';
    }

    const today = new Date();
    const expiry = new Date(dateValue + 'T00:00:00');
    const diffDays = Math.ceil((expiry - new Date(today.getFullYear(), today.getMonth(), today.getDate())) / 86400000);

    if (diffDays < 0) {
        return 'bg-danger';
    }
    if (diffDays <= 30) {
        return 'bg-warning text-dark';
    }

    return 'bg-info text-dark';
}

function getExpiryLabel(dateValue) {
    if (!dateValue) {
        return 'No license record';
    }

    const today = new Date();
    const expiry = new Date(dateValue + 'T00:00:00');
    const diffDays = Math.ceil((expiry - new Date(today.getFullYear(), today.getMonth(), today.getDate())) / 86400000);

    if (diffDays < 0) {
        return 'License expired';
    }
    if (diffDays <= 30) {
        return 'Expiring soon';
    }

    return 'License valid';
}

function showDriverModal() {
    new bootstrap.Modal(document.getElementById('driverModal')).show();
}

function hideDriverModal() {
    const modalEl = document.getElementById('driverModal');
    const instance = bootstrap.Modal.getInstance(modalEl);

    if (instance) {
        instance.hide();
    }
}

function clearDriverForm() {
    const form = document.getElementById('driverForm');
    if (form) {
        form.reset();
    }

    $('#driver_id').val('');
    $('#driver_status').val('Active');
    $('#driver_active_status').val('1');
    $('#driverPhotoPreview').hide();
}

function normalizeDateInput(value) {
    if (!value) {
        return '';
    }

    return String(value).slice(0, 10);
}

function formatDate(value) {
    if (!value) {
        return '';
    }

    const date = new Date(value);
    if (Number.isNaN(date.getTime())) {
        return value;
    }

    return date.toLocaleDateString(undefined, {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
    });
}

function safeJson(value) {
    return escapeHtml(JSON.stringify(value));
}

function showDriverSuccess(message) {
    showDriverToast(message, 'success');
}

function showDriverError(message) {
    showDriverToast(message, 'danger');
}

function showDriverToast(message, type) {
    const toastHostId = 'driverToastHost';
    let toastHost = document.getElementById(toastHostId);

    if (!toastHost) {
        toastHost = document.createElement('div');
        toastHost.id = toastHostId;
        toastHost.className = 'toast-container position-fixed top-0 end-0 p-3';
        toastHost.style.zIndex = '1080';
        document.body.appendChild(toastHost);
    }

    const toastEl = document.createElement('div');
    const title = type === 'success' ? 'Success' : 'Error';
    const headerClass = type === 'success' ? 'text-bg-success' : 'text-bg-danger';

    toastEl.className = 'toast border-0';
    toastEl.setAttribute('role', 'alert');
    toastEl.setAttribute('aria-live', 'assertive');
    toastEl.setAttribute('aria-atomic', 'true');
    toastEl.innerHTML = `
        <div class="toast-header ${headerClass}">
            <strong class="me-auto">${title}</strong>
            <small>Now</small>
            <button type="button" class="btn-close btn-close-white ms-2 mb-1" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
        <div class="toast-body bg-white">${escapeHtml(message)}</div>
    `;

    toastHost.appendChild(toastEl);
    const toast = new bootstrap.Toast(toastEl, { delay: 3500 });
    toast.show();

    toastEl.addEventListener('hidden.bs.toast', function () {
        toastEl.remove();
    });
}

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