let _licenseExpiryDate = null;
let _isLicenseExpired = true;

$(function () {
    $('#offDutyMonth').val(new Date().toISOString().slice(0, 7));
    loadDriverProfile();
    loadLicenseHistory();
    loadMedicalRecords();
    loadCertifications();
    loadTrainingHistory();
    loadViolations();
    loadOffDuty();

    $('#btnAddRenewal').on('click', function () {
        if (!_isLicenseExpired) {
            showProfileError('Cannot add renewal: current license is still valid until ' + formatDate(_licenseExpiryDate));
            return;
        }
        clearRenewalForm();
        $('#licenseRenewalModalTitle').text('Add License Renewal');
        showRenewalModal();
    });

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

    $(document).on('click', '.btn-edit-renewal', function () {
        const renewal = $(this).data('renewal');
        populateRenewalForm(renewal);
    });

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

    // Medical
    $('#btnAddMedical').on('click', function () {
        clearMedicalForm();
        $('#medicalModalTitle').text('Add Medical Record');
        showModal('medicalModal');
    });
    $('#saveMedical').on('click', saveMedical);
    $(document).on('click', '.btn-edit-medical', function () {
        populateMedicalForm($(this).data('record'));
    });
    $(document).on('click', '.btn-delete-medical', function () {
        deleteRecord('medical', $(this).data('id'));
    });

    // Certifications
    $('#btnAddCert').on('click', function () {
        clearCertForm();
        $('#certModalTitle').text('Add Certification');
        showModal('certModal');
    });
    $('#saveCert').on('click', saveCertification);
    $(document).on('click', '.btn-edit-cert', function () {
        populateCertForm($(this).data('record'));
    });
    $(document).on('click', '.btn-delete-cert', function () {
        deleteRecord('certification', $(this).data('id'));
    });

    // Training
    $('#btnAddTraining').on('click', function () {
        clearTrainingForm();
        $('#trainingModalTitle').text('Add Training Record');
        showModal('trainingModal');
    });
    $('#saveTraining').on('click', saveTraining);
    $(document).on('click', '.btn-edit-training', function () {
        populateTrainingForm($(this).data('record'));
    });
    $(document).on('click', '.btn-delete-training', function () {
        deleteRecord('training', $(this).data('id'));
    });

    // Violations
    $('#btnAddViolation').on('click', function () {
        clearViolationForm();
        $('#violationModalTitle').text('Add Violation');
        showModal('violationModal');
    });
    $('#saveViolation').on('click', saveViolation);
    $(document).on('click', '.btn-edit-violation', function () {
        populateViolationForm($(this).data('record'));
    });
    $(document).on('click', '.btn-delete-violation', function () {
        deleteRecord('violation', $(this).data('id'));
    });

    // Off Duty
    $('#btnAddOffDuty').on('click', function () {
        clearOffDutyForm();
        $('#offDutyModalTitle').text('Add Off-Duty Day');
        showModal('offDutyModal');
    });
    $('#saveOffDuty').on('click', saveOffDuty);
    $(document).on('click', '.btn-edit-offduty', function () {
        populateOffDutyForm($(this).data('record'));
    });
    $(document).on('click', '.btn-delete-offduty', function () {
        deleteRecord('offduty', $(this).data('id'));
    });
    $('#offDutyMonth').on('change', loadOffDuty);
});

function loadDriverProfile() {
    $.get('api/driver_profile.php', { action: 'profile', id: DRIVER_ID }, function (res) {
        if (res.status !== 'success') {
            showProfileError(res.message || 'Failed to load driver profile');
            return;
        }

    const driver = res.data || {};

        _licenseExpiryDate = driver.license_valid_until || null;
        _isLicenseExpired = _licenseExpiryDate ? new Date(_licenseExpiryDate) < new Date(new Date().toDateString()) : true;

        $('#alertBox').addClass('d-none').text('');
        $('#driverTitle').text(driver.full_name || 'Driver Profile');
        $('#driverSubtitle').text(buildSubtitle(driver));
        $('#driverStatus')
            .removeClass('bg-success bg-secondary bg-warning bg-danger text-dark')
            .addClass(getStatusClass(driver.driver_status, driver.active_status))
            .text(driver.driver_status || (Number(driver.active_status) === 1 ? 'Active' : 'Inactive'));

        // Driver photo
        if (driver.driver_photo) {
            $('#driverPicContainer').html(`<img src="uploads/drivers/${driver.driver_photo}" class="driver-pic" alt="Driver Photo">`);
            $('#profileDriverPicContainer').html(`<img src="uploads/drivers/${driver.driver_photo}" class="driver-pic-small" alt="Driver Photo">`);
        } else {
            $('#driverPicContainer, #profileDriverPicContainer').html('<div class="driver-pic-placeholder"><i class="bi bi-person-circle"></i></div>');
        }

        $('#driverCode').text(driver.driver_id_code || '-');
        $('#assignedVehicle').text(driver.assigned_vehicle || 'Unassigned');
        $('#driverPhone').text(driver.phone || '-');
        $('#licenseValidUntil').text(formatDate(driver.license_valid_until));

        $('#fullName').text(driver.full_name || '-');
        $('#surname').text(driver.surname || '-');
        $('#firstName').text(driver.first_name || '-');
        $('#otherName').text(driver.other_name || '-');
        $('#dateOfBirth').text(formatDate(driver.date_of_birth));
        $('#resumptionDate').text(formatDate(driver.resumption_date));
        $('#confirmationDate').text(formatDate(driver.confirmation_date));
        $('#exitDate').text(formatDate(driver.exit_date));
        $('#driverAddress').text(driver.driver_address || '-');
        $('#remarks').text(driver.remarks || '-');

        $('#licenseNumber').text(driver.license_number || '-');
        $('#licenseCategory').text(driver.license_category || '-');
        $('#issuedDate').text(formatDate(driver.issued_date));
        $('#firstIssueDate').text(formatDate(driver.date_of_first_issue));
        $('#notificationDate').text(formatDate(driver.notification_date));
        $('#licenseStatus').html(renderLicenseStatus(driver.license_state));

        $('#nextOfKinName').text(driver.next_of_kin_name || '-');
        $('#nextOfKinPhone').text(driver.next_of_kin_phone || '-');
        $('#guarantorName').text(driver.guarantor_name || '-');
        $('#guarantorPhone').text(driver.guarantor_phone || '-');
        $('#guarantorAddress').text(driver.guarantor_address || '-');
    }, 'json').fail(function () {
        showProfileError('Server error while loading driver profile');
    });
}

function loadLicenseHistory() {
    $.get('api/driver_profile.php', { action: 'license_history', id: DRIVER_ID }, function (res) {
        if (res.status !== 'success') {
            $('#licenseHistoryTable').html('<tr><td colspan="6" class="text-center text-muted">Unable to load renewal history</td></tr>');
            return;
        }

        let html = '';
        const rows = res.data || [];

        if (!rows.length) {
            html = '<tr><td colspan="6" class="text-center text-muted">No yearly renewal records found</td></tr>';
        } else {
            $.each(rows, function (_, row) {
                html += `
                    <tr>
                        <td>${escapeHtml(row.license_number || '-')}</td>
                        <td>${escapeHtml(row.license_category || '-')}</td>
                        <td>${escapeHtml(formatDate(row.issued_date))}</td>
                        <td>${escapeHtml(formatDate(row.valid_until))}</td>
                        <td>${renderLicenseStatus(row.license_state)}</td>
                        <td>
                            <div class="d-flex flex-wrap gap-2">
                                <button type="button" class="btn btn-sm btn-warning btn-edit-renewal" data-renewal='${safeJson(row)}'>Edit</button>
                                <button type="button" class="btn btn-sm btn-danger btn-delete-renewal" data-id="${row.id}">Delete</button>
                            </div>
                        </td>
                    </tr>
                `;
            });
        }

        $('#licenseHistoryTable').html(html);
    }, 'json');
}

function saveRenewal() {
    const payload = {
        id: $('#renewal_id').val(),
        driver_id: DRIVER_ID,
        license_number: $('#renewal_license_number').val().trim(),
        license_category: $('#renewal_category').val().trim(),
        issued_date: $('#renewal_issued_date').val(),
        valid_until: $('#renewal_valid_until').val(),
        date_of_first_issue: $('#renewal_first_issue_date').val(),
        notification_date: $('#renewal_notification_date').val()
    };

    if (!payload.license_number) {
        showProfileError('License number is required');
        return;
    }

    if (!payload.valid_until) {
        showProfileError('Expiry date is required');
        return;
    }

    $.ajax({
        url: 'api/driver_profile.php?action=save_license',
        method: 'POST',
        dataType: 'json',
        data: payload,
        success: function (res) {
            if (res.status !== 'success') {
                showProfileError(res.message || 'Unable to save renewal');
                return;
            }

            hideRenewalModal();
            loadDriverProfile();
            loadLicenseHistory();
        },
        error: function () {
            showProfileError('Server error while saving renewal');
        }
    });
}

function populateRenewalForm(renewal) {
    clearRenewalForm();

    $('#renewal_id').val(renewal.id || '');
    $('#renewal_license_number').val(renewal.license_number || '');
    $('#renewal_category').val(renewal.license_category || '');
    $('#renewal_issued_date').val(normalizeDateInput(renewal.issued_date));
    $('#renewal_valid_until').val(normalizeDateInput(renewal.valid_until));
    $('#renewal_first_issue_date').val(normalizeDateInput(renewal.date_of_first_issue));
    $('#renewal_notification_date').val(normalizeDateInput(renewal.notification_date));

    $('#licenseRenewalModalTitle').text('Edit License Renewal');
    showRenewalModal();
}

function deleteRenewal(id) {
    if (!id || !confirm('Delete this yearly renewal record?')) {
        return;
    }

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

            loadDriverProfile();
            loadLicenseHistory();
        },
        error: function () {
            showProfileError('Server error while deleting renewal');
        }
    });
}

function buildSubtitle(driver) {
    const parts = [];
    if (driver.driver_id_code) {
        parts.push(driver.driver_id_code);
    }
    if (driver.assigned_vehicle) {
        parts.push(driver.assigned_vehicle);
    }

    return parts.length ? parts.join(' | ') : 'Driver record, assignment and license view.';
}

function getStatusClass(driverStatus, activeStatus) {
    const status = (driverStatus || '').toLowerCase();

    if (status === 'suspended') {
        return 'bg-warning text-dark';
    }
    if (status === 'exited') {
        return 'bg-danger';
    }
    if (status === 'inactive' || Number(activeStatus) !== 1) {
        return 'bg-secondary';
    }

    return 'bg-success';
}

function renderLicenseStatus(status) {
    if (status === 'Expired') {
        return '<span class="badge bg-danger">Expired</span>';
    }
    if (status === 'Expiring Soon') {
        return '<span class="badge bg-warning text-dark">Expiring Soon</span>';
    }
    if (status === 'Unknown') {
        return '<span class="badge bg-secondary">Unknown</span>';
    }

    return '<span class="badge bg-success">Valid</span>';
}

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 showProfileError(message) {
    $('#alertBox').removeClass('d-none').text(message);
}

function showRenewalModal() {
    new bootstrap.Modal(document.getElementById('licenseRenewalModal')).show();
}

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

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

function clearRenewalForm() {
    const form = document.getElementById('licenseRenewalForm');
    if (form) {
        form.reset();
    }

    $('#renewal_id').val('');
}

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

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

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

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

// ====== Medical Records ======

function loadMedicalRecords() {
    $.get('api/driver_profile.php', { action: 'medical_list', id: DRIVER_ID }, function (res) {
        if (res.status !== 'success') {
            $('#medicalTable').html('<tr><td colspan="6" class="text-center text-muted">Failed to load</td></tr>');
            return;
        }
        const rows = res.data || [];
        let html = '';
        if (!rows.length) {
            html = '<tr><td colspan="6" class="text-center text-muted">No medical records found</td></tr>';
        } else {
            $.each(rows, function (_, r) {
                html += '<tr>' +
                    '<td>' + escapeHtml(r.examination_type || '-') + '</td>' +
                    '<td>' + formatDate(r.examination_date) + '</td>' +
                    '<td>' + escapeHtml(r.performed_by || '-') + '</td>' +
                    '<td>' + renderMedicalStatus(r.status) + '</td>' +
                    '<td>' + formatDate(r.valid_until) + '</td>' +
                    '<td>' + actionButtons('medical', r) + '</td>' +
                '</tr>';
            });
        }
        $('#medicalTable').html(html);
    }, 'json');
}

function renderMedicalStatus(status) {
    const map = { fit: 'bg-success', unfit: 'bg-danger', conditional: 'bg-warning text-dark', pending: 'bg-secondary' };
    return '<span class="badge ' + (map[status] || 'bg-secondary') + '">' + escapeHtml(status || 'unknown') + '</span>';
}

function clearMedicalForm() {
    $('#medicalForm')[0].reset();
    $('#medical_id').val('');
    $('#medical_status').val('fit');
}

function populateMedicalForm(r) {
    clearMedicalForm();
    $('#medical_id').val(r.id || '');
    $('#medical_examination_type').val(r.examination_type || '');
    $('#medical_examination_date').val(normalizeDateInput(r.examination_date));
    $('#medical_performed_by').val(r.performed_by || '');
    $('#medical_status').val(r.status || 'fit');
    $('#medical_valid_until').val(normalizeDateInput(r.valid_until));
    $('#medical_results').val(r.results || '');
    $('#medical_notes').val(r.notes || '');
    $('#medicalModalTitle').text('Edit Medical Record');
    showModal('medicalModal');
}

function saveMedical() {
    const payload = {
        id: $('#medical_id').val(),
        driver_id: DRIVER_ID,
        examination_type: $('#medical_examination_type').val(),
        examination_date: $('#medical_examination_date').val(),
        performed_by: $('#medical_performed_by').val().trim(),
        status: $('#medical_status').val(),
        valid_until: $('#medical_valid_until').val(),
        results: $('#medical_results').val().trim(),
        notes: $('#medical_notes').val().trim()
    };
    if (!payload.examination_type || !payload.examination_date) {
        showProfileError('Examination type and date are required');
        return;
    }
    $.ajax({
        url: 'api/driver_profile.php?action=medical_save',
        method: 'POST',
        dataType: 'json',
        data: payload,
        success: function (res) {
            if (res.status !== 'success') { showProfileError(res.message); return; }
            hideModal('medicalModal');
            loadMedicalRecords();
        },
        error: function () { showProfileError('Server error'); }
    });
}

// ====== Certifications ======

function loadCertifications() {
    $.get('api/driver_profile.php', { action: 'certification_list', id: DRIVER_ID }, function (res) {
        if (res.status !== 'success') {
            $('#certTable').html('<tr><td colspan="6" class="text-center text-muted">Failed to load</td></tr>');
            return;
        }
        const rows = res.data || [];
        let html = '';
        if (!rows.length) {
            html = '<tr><td colspan="6" class="text-center text-muted">No certifications found</td></tr>';
        } else {
            $.each(rows, function (_, r) {
                html += '<tr>' +
                    '<td>' + escapeHtml(r.certification_name || '-') + '</td>' +
                    '<td>' + escapeHtml(r.certification_type || '-') + '</td>' +
                    '<td>' + escapeHtml(r.issuing_authority || '-') + '</td>' +
                    '<td>' + formatDate(r.expiry_date) + '</td>' +
                    '<td>' + renderCertStatus(r.status) + '</td>' +
                    '<td>' + actionButtons('cert', r) + '</td>' +
                '</tr>';
            });
        }
        $('#certTable').html(html);
    }, 'json');
}

function renderCertStatus(status) {
    const map = { active: 'bg-success', expired: 'bg-danger', suspended: 'bg-warning text-dark', revoked: 'bg-dark' };
    return '<span class="badge ' + (map[status] || 'bg-secondary') + '">' + escapeHtml(status || 'unknown') + '</span>';
}

function clearCertForm() {
    $('#certForm')[0].reset();
    $('#cert_id').val('');
    $('#cert_status').val('active');
}

function populateCertForm(r) {
    clearCertForm();
    $('#cert_id').val(r.id || '');
    $('#cert_type').val(r.certification_type || '');
    $('#cert_name').val(r.certification_name || '');
    $('#cert_authority').val(r.issuing_authority || '');
    $('#cert_number').val(r.certification_number || '');
    $('#cert_issued_date').val(normalizeDateInput(r.issued_date));
    $('#cert_expiry_date').val(normalizeDateInput(r.expiry_date));
    $('#cert_status').val(r.status || 'active');
    $('#cert_notes').val(r.notes || '');
    $('#certModalTitle').text('Edit Certification');
    showModal('certModal');
}

function saveCertification() {
    const payload = {
        id: $('#cert_id').val(),
        driver_id: DRIVER_ID,
        certification_type: $('#cert_type').val(),
        certification_name: $('#cert_name').val().trim(),
        issuing_authority: $('#cert_authority').val().trim(),
        certification_number: $('#cert_number').val().trim(),
        issued_date: $('#cert_issued_date').val(),
        expiry_date: $('#cert_expiry_date').val(),
        status: $('#cert_status').val(),
        notes: $('#cert_notes').val().trim()
    };
    if (!payload.certification_type || !payload.certification_name) {
        showProfileError('Certification type and name are required');
        return;
    }
    $.ajax({
        url: 'api/driver_profile.php?action=certification_save',
        method: 'POST',
        dataType: 'json',
        data: payload,
        success: function (res) {
            if (res.status !== 'success') { showProfileError(res.message); return; }
            hideModal('certModal');
            loadCertifications();
        },
        error: function () { showProfileError('Server error'); }
    });
}

// ====== Training ======

function loadTrainingHistory() {
    $.get('api/driver_profile.php', { action: 'training_list', id: DRIVER_ID }, function (res) {
        if (res.status !== 'success') {
            $('#trainingTable').html('<tr><td colspan="6" class="text-center text-muted">Failed to load</td></tr>');
            return;
        }
        const rows = res.data || [];
        let html = '';
        if (!rows.length) {
            html = '<tr><td colspan="6" class="text-center text-muted">No training records found</td></tr>';
        } else {
            $.each(rows, function (_, r) {
                html += '<tr>' +
                    '<td>' + escapeHtml(r.training_name || '-') + '</td>' +
                    '<td>' + escapeHtml(r.training_type || '-') + '</td>' +
                    '<td>' + escapeHtml(r.training_provider || '-') + '</td>' +
                    '<td>' + formatDate(r.training_date) + '</td>' +
                    '<td>' + renderTrainingStatus(r.status) + '</td>' +
                    '<td>' + actionButtons('training', r) + '</td>' +
                '</tr>';
            });
        }
        $('#trainingTable').html(html);
    }, 'json');
}

function renderTrainingStatus(status) {
    const map = { completed: 'bg-success', in_progress: 'bg-primary', withdrawn: 'bg-warning text-dark', cancelled: 'bg-secondary' };
    return '<span class="badge ' + (map[status] || 'bg-secondary') + '">' + escapeHtml((status || 'unknown').replace('_', ' ')) + '</span>';
}

function clearTrainingForm() {
    $('#trainingForm')[0].reset();
    $('#training_id').val('');
    $('#training_status').val('completed');
    $('#training_certificate_issued').prop('checked', false);
}

function populateTrainingForm(r) {
    clearTrainingForm();
    $('#training_id').val(r.id || '');
    $('#training_type').val(r.training_type || '');
    $('#training_name').val(r.training_name || '');
    $('#training_provider').val(r.training_provider || '');
    $('#training_date').val(normalizeDateInput(r.training_date));
    $('#training_completion_date').val(normalizeDateInput(r.completion_date));
    $('#training_duration_hours').val(r.duration_hours || '');
    $('#training_status').val(r.status || 'completed');
    if (Number(r.certificate_issued) === 1) $('#training_certificate_issued').prop('checked', true);
    $('#training_notes').val(r.notes || '');
    $('#trainingModalTitle').text('Edit Training Record');
    showModal('trainingModal');
}

function saveTraining() {
    const payload = {
        id: $('#training_id').val(),
        driver_id: DRIVER_ID,
        training_type: $('#training_type').val(),
        training_name: $('#training_name').val().trim(),
        training_provider: $('#training_provider').val().trim(),
        training_date: $('#training_date').val(),
        completion_date: $('#training_completion_date').val(),
        duration_hours: $('#training_duration_hours').val(),
        status: $('#training_status').val(),
        certificate_issued: $('#training_certificate_issued').is(':checked') ? 1 : 0,
        notes: $('#training_notes').val().trim()
    };
    if (!payload.training_type || !payload.training_name) {
        showProfileError('Training type and name are required');
        return;
    }
    $.ajax({
        url: 'api/driver_profile.php?action=training_save',
        method: 'POST',
        dataType: 'json',
        data: payload,
        success: function (res) {
            if (res.status !== 'success') { showProfileError(res.message); return; }
            hideModal('trainingModal');
            loadTrainingHistory();
        },
        error: function () { showProfileError('Server error'); }
    });
}

// ====== Violations ======

function loadViolations() {
    $.get('api/driver_profile.php', { action: 'violation_list', id: DRIVER_ID }, function (res) {
        if (res.status !== 'success') {
            $('#violationTable').html('<tr><td colspan="7" class="text-center text-muted">Failed to load</td></tr>');
            return;
        }
        const rows = res.data || [];
        let html = '';
        if (!rows.length) {
            html = '<tr><td colspan="7" class="text-center text-muted">No violations found</td></tr>';
        } else {
            $.each(rows, function (_, r) {
                html += '<tr>' +
                    '<td>' + escapeHtml(r.violation_type || '-') + '</td>' +
                    '<td>' + formatDate(r.violation_date) + '</td>' +
                    '<td>' + escapeHtml(r.location || '-') + '</td>' +
                    '<td>' + (r.penalty_points || 0) + '</td>' +
                    '<td>' + formatCurrency(r.fine_amount) + '</td>' +
                    '<td>' + renderViolationStatus(r.status) + '</td>' +
                    '<td>' + actionButtons('violation', r) + '</td>' +
                '</tr>';
            });
        }
        $('#violationTable').html(html);
    }, 'json');
}

function renderViolationStatus(status) {
    const map = { pending: 'bg-warning text-dark', paid: 'bg-success', contested: 'bg-info text-dark', resolved: 'bg-primary', waived: 'bg-secondary' };
    return '<span class="badge ' + (map[status] || 'bg-secondary') + '">' + escapeHtml(status || 'unknown') + '</span>';
}

function clearViolationForm() {
    $('#violationForm')[0].reset();
    $('#violation_id').val('');
    $('#violation_points').val(0);
    $('#violation_fine').val(0);
    $('#violation_status').val('pending');
}

function populateViolationForm(r) {
    clearViolationForm();
    $('#violation_id').val(r.id || '');
    $('#violation_type').val(r.violation_type || '');
    $('#violation_date').val(normalizeDateInput(r.violation_date));
    $('#violation_offense').val(r.offense_description || '');
    $('#violation_location').val(r.location || '');
    $('#violation_police_report').val(r.police_report_number || '');
    $('#violation_points').val(r.penalty_points || 0);
    $('#violation_fine').val(r.fine_amount || 0);
    $('#violation_status').val(r.status || 'pending');
    $('#violation_resolution_date').val(normalizeDateInput(r.resolution_date));
    $('#violation_notes').val(r.notes || '');
    $('#violationModalTitle').text('Edit Violation');
    showModal('violationModal');
}

function saveViolation() {
    const payload = {
        id: $('#violation_id').val(),
        driver_id: DRIVER_ID,
        violation_type: $('#violation_type').val(),
        violation_date: $('#violation_date').val(),
        offense_description: $('#violation_offense').val().trim(),
        location: $('#violation_location').val().trim(),
        penalty_points: $('#violation_points').val(),
        fine_amount: $('#violation_fine').val(),
        status: $('#violation_status').val(),
        resolution_date: $('#violation_resolution_date').val(),
        police_report_number: $('#violation_police_report').val().trim(),
        notes: $('#violation_notes').val().trim()
    };
    if (!payload.violation_type || !payload.violation_date) {
        showProfileError('Violation type and date are required');
        return;
    }
    $.ajax({
        url: 'api/driver_profile.php?action=violation_save',
        method: 'POST',
        dataType: 'json',
        data: payload,
        success: function (res) {
            if (res.status !== 'success') { showProfileError(res.message); return; }
            hideModal('violationModal');
            loadViolations();
        },
        error: function () { showProfileError('Server error'); }
    });
}

// ====== Shared Helpers ======

function deleteRecord(type, id) {
    if (!id || !confirm('Delete this ' + type + ' record?')) return;

    const actionMap = {
        medical: { action: 'medical_delete', table: 'medical' },
        certification: { action: 'certification_delete', table: 'certification' },
        training: { action: 'training_delete', table: 'training' },
        violation: { action: 'violation_delete', table: 'violation' },
        offduty: { action: 'off_duty_delete', table: 'offduty' }
    };

    const cfg = actionMap[type];
    if (!cfg) return;

    $.ajax({
        url: 'api/driver_profile.php?action=' + cfg.action,
        method: 'POST',
        dataType: 'json',
        data: { id: id, driver_id: DRIVER_ID },
        success: function (res) {
            if (res.status !== 'success') { showProfileError(res.message); return; }
            if (type === 'medical') loadMedicalRecords();
            else if (type === 'certification') loadCertifications();
            else if (type === 'training') loadTrainingHistory();
            else if (type === 'violation') loadViolations();
            else if (type === 'offduty') loadOffDuty();
        },
        error: function () { showProfileError('Server error'); }
    });
}

function actionButtons(type, record) {
    const safe = safeJson(record);
    const prefix = type === 'offduty' ? 'offduty' : type;
    return '<div class="d-flex flex-wrap gap-2">' +
        '<button type="button" class="btn btn-sm btn-warning btn-edit-' + prefix + '" data-record=\'' + safe + '\'>Edit</button>' +
        '<button type="button" class="btn btn-sm btn-danger btn-delete-' + prefix + '" data-id="' + record.id + '">Delete</button>' +
    '</div>';
}

function loadOffDuty() {
    var month = $('#offDutyMonth').val() || new Date().toISOString().slice(0, 7);
    $.get('api/driver_profile.php', { action: 'off_duty_list', id: DRIVER_ID, month: month }, function (res) {
        if (res.status !== 'success') { showProfileError(res.message); return; }
        var rows = res.data || [];
        $('#offDutySummary').html(
            '<div class="col-4"><div class="card border-0 bg-light"><div class="card-body p-3 text-center"><div class="small text-muted">Taken</div><div class="fs-4 fw-bold">' + res.taken + '</div></div></div></div>' +
            '<div class="col-4"><div class="card border-0 bg-light"><div class="card-body p-3 text-center"><div class="small text-muted">Max</div><div class="fs-4 fw-bold">' + res.max + '</div></div></div></div>' +
            '<div class="col-4"><div class="card border-0 bg-light"><div class="card-body p-3 text-center"><div class="small text-muted">Remaining</div><div class="fs-4 fw-bold">' + res.remaining + '</div></div></div></div>'
        );
        var html = '';
        if (!rows.length) html = '<tr><td colspan="4" class="text-center text-muted">No off-duty days this month</td></tr>';
        else rows.forEach(function (r) {
            html += '<tr><td>' + formatDate(r.off_date) + '</td><td>' + escapeHtml(r.reason || '-') + '</td><td>' + escapeHtml(r.notes || '-') + '</td><td>' + actionButtons('offduty', r) + '</td></tr>';
        });
        $('#offDutyTable').html(html);
    }, 'json');
}

function clearOffDutyForm() { $('#offDutyForm')[0].reset(); $('#off_duty_id').val(''); }
function populateOffDutyForm(r) { clearOffDutyForm(); $('#off_duty_id').val(r.id); $('#off_duty_date').val(normalizeDate(r.off_date)); $('#off_duty_reason').val(r.reason || ''); $('#off_duty_notes').val(r.notes || ''); $('#offDutyModalTitle').text('Edit Off-Duty Day'); showModal('offDutyModal'); }

function saveOffDuty() {
    var p = {
        id: $('#off_duty_id').val(),
        driver_id: DRIVER_ID,
        off_date: $('#off_duty_date').val(),
        reason: $('#off_duty_reason').val(),
        notes: $('#off_duty_notes').val()
    };
    if (!p.off_date) { showProfileError('Date is required'); return; }
    $.ajax({
        url: 'api/driver_profile.php?action=off_duty_save',
        method: 'POST',
        dataType: 'json',
        data: $.extend({}, p, { csrf_token: window.CSRF_TOKEN }),
        success: function (res) {
            if (res.status !== 'success') { showProfileError(res.message); return; }
            hideModal('offDutyModal');
            loadOffDuty();
        },
        error: function () { showProfileError('Server error'); }
    });
}

function formatCurrency(value) {
    if (!value && value !== 0) return '-';
    return '₦' + Number(value).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function showModal(id) {
    new bootstrap.Modal(document.getElementById(id)).show();
}

function hideModal(id) {
    const el = document.getElementById(id);
    const inst = bootstrap.Modal.getInstance(el);
    if (inst) inst.hide();
}
