$(function () {
    $('#csrf_token').val(window.CSRF_TOKEN);
    load();

    $('#company_logo').on('change', function () {
        var f = this.files && this.files[0];
        if (!f) return;
        var url = URL.createObjectURL(f);
        $('#company_logo_preview').attr('src', url).show();
    });

    $('#companySetupForm').on('submit', function (e) {
        e.preventDefault();
        var fd = new FormData(this);
        fd.set('csrf_token', window.CSRF_TOKEN);
        $.ajax({
            url: 'api/company.php?action=save',
            method: 'POST',
            data: fd,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function (res) {
                if (res.status === 'success') {
                    showAlert('Company settings saved!', 'success');
                    load();
                } else {
                    showAlert(res.message || 'Save failed', 'danger');
                }
            },
            error: function () {
                showAlert('Server error', 'danger');
            }
        });
    });
});

function load() {
    $.get('api/company.php', { action: 'get' }, function (res) {
        if (res.status !== 'success') return;
        var d = res.data || {};
        $('#company_name').val(d.name || '');
        $('#company_email').val(d.email || '');
        $('#company_phone').val(d.phone || '');
        if (d.logo_path) {
            $('#company_logo_preview').attr('src', d.logo_path).show();
        } else {
            $('#company_logo_preview').hide();
        }
    }, 'json');
}

function showAlert(msg, type) {
    var box = $('#alertBox');
    box.removeClass('d-none alert-success alert-danger alert-warning alert-info')
        .addClass('alert-' + type).text(msg);
    setTimeout(function () { box.addClass('d-none'); }, 5000);
}
