const WORKSHOP_API = 'api/workshop.php';

$(function () {
    loadWorkshops();
    $('#btnRefreshWorkshops').on('click', loadWorkshops);
    $('#workshopSearchDir').on('input', debounce(loadWorkshops, 300));
    $('#workshopStatusFilter').on('change', loadWorkshops);
    $('#btnAddNewWorkshop').on('click', () => openEditModal());
    $('#btnSaveWorkshopDir').on('click', saveWorkshop);

    $('#workshopEditModal').on('hidden.bs.modal', () => {
        $('#workshopEditForm')[0]?.reset();
    });
});

function loadWorkshops() {
    const search = $('#workshopSearchDir').val();
    const status = $('#workshopStatusFilter').val();
    const tbody = $('#workshopDirectoryTable');
    tbody.html('<tr><td colspan="7" class="text-center text-muted py-4">Loading...</td></tr>');

    $.get(WORKSHOP_API, { action: 'list', search: search, status: status }, function (res) {
        if (res.status === 'success') {
            tbody.html((res.data || []).map(function (w) {
                return '<tr><td><strong>' + esc(w.name) + '</strong></td>' +
                    '<td>' + esc(w.vendor_type || 'Workshop') + '</td>' +
                    '<td>' + esc(w.contact_person || '-') + '</td>' +
                    '<td><a href="tel:' + esc(w.phone) + '" class="text-decoration-none">' + esc(w.phone || '-') + '</a></td>' +
                    '<td><a href="mailto:' + esc(w.email) + '" class="text-decoration-none">' + esc(w.email || '-') + '</a></td>' +
                    '<td>' + esc(w.city || '-') + '</td>' +
                    '<td>' + (w.status_badge || '-') + '</td>' +
                    '<td>' +
                    '<button class="btn btn-sm btn-outline-primary me-1 btn-edit-ws" data-id="' + w.id + '" title="Edit"><i class="bi bi-pencil"></i></button>' +
                    '<button class="btn btn-sm ' + (w.status === 'active' ? 'btn-outline-danger' : 'btn-outline-success') + ' btn-toggle-ws" data-id="' + w.id + '" data-status="' + w.status + '" title="' + (w.status === 'active' ? 'Deactivate' : 'Activate') + '"><i class="bi bi-power"></i></button>' +
                    '</td></tr>';
            }).join('') || '<tr><td colspan="8" class="text-center text-muted py-4">No workshops found</td></tr>');
        } else {
            showToast(res.message || 'Load failed', 'danger');
        }
    });

    // Delegate events for dynamically created buttons
    $(document).off('click', '.btn-edit-ws').on('click', '.btn-edit-ws', function () {
        openEditModal($(this).data('id'));
    });
    $(document).off('click', '.btn-toggle-ws').on('click', '.btn-toggle-ws', function () {
        toggleStatus($(this).data('id'), $(this).data('status'));
    });
}

function openEditModal(id) {
    id = id || null;
    const form = $('#workshopEditForm')[0];
    if (form) form.reset();
    $('#editWorkshopId').val(id || '');
    $('#workshopEditTitle').text(id ? 'Edit Workshop' : 'Add New Workshop');
    $('#editStatus').val('active');

    const citySelect = $('#editCity');
    if (!citySelect.find('option[value!=""]').length) {
        $.get(WORKSHOP_API, { action: 'cities' }, function (res) {
            if (res.status === 'success') {
                citySelect.find('option:not(:first)').remove();
                (res.data || []).forEach(function (c) {
                    citySelect.append('<option value="' + esc(c.name) + '">' + esc(c.name) + '</option>');
                });
                if (id) fillWorkshopForm(id);
            }
        });
    } else if (id) {
        fillWorkshopForm(id);
    }
    $('#workshopEditModal').modal('show');
}

function fillWorkshopForm(id) {
    $.get(WORKSHOP_API, { action: 'get', id: id }, function (res) {
        if (res.status === 'success' && res.data[0]) {
            const w = res.data[0];
            $('#editWorkshopName').val(w.name);
            $('#editContactPerson').val(w.contact_person || '');
            $('#editPhone').val(w.phone || '');
            $('#editEmail').val(w.email || '');
            $('#editAddress').val(w.address || '');
            $('#editCity').val(w.city || '');
            $('#editVendorType').val(w.vendor_type || 'Workshop');
            $('#editStatus').val(w.status);
            $('#editInactiveReason').val(w.inactive_reason || '');
        }
    });
}

let _savingWsDir = false;

function saveWorkshop() {
    if (_savingWsDir) return;
    const status = $('#editStatus').val();
    if (status === 'inactive' && !$('#editInactiveReason').val().trim()) {
        showToast('Inactive reason is required', 'danger');
        return;
    }
    _savingWsDir = true;
    const btn = $('#btnSaveWorkshopDir').prop('disabled', true);

    $.post(WORKSHOP_API + '?action=save', {
        id: $('#editWorkshopId').val(),
        name: $('#editWorkshopName').val(),
        contact_person: $('#editContactPerson').val(),
        phone: $('#editPhone').val(),
        email: $('#editEmail').val(),
        address: $('#editAddress').val(),
        city: $('#editCity').val(),
        vendor_type: $('#editVendorType').val(),
        status: status,
        inactive_reason: status === 'inactive' ? $('#editInactiveReason').val() : ''
    }, function (res) {
        if (res.status === 'success') {
            $('#workshopEditModal').modal('hide');
            loadWorkshops();
            showToast('Workshop saved!', 'success');
        } else {
            showToast(res.message || 'Save failed', 'danger');
        }
    }).always(function () {
        _savingWsDir = false;
        btn.prop('disabled', false);
    });
}

function toggleStatus(id, currentStatus) {
    if (!confirm('Are you sure to ' + (currentStatus === 'active' ? 'deactivate' : 'activate') + ' this workshop?')) return;
    const newStatus = currentStatus === 'active' ? 'inactive' : 'active';
    let reason = '';
    if (newStatus === 'inactive') {
        reason = prompt('Reason for deactivation:');
        if (reason === null) return;
    }

    $.post(WORKSHOP_API + '?action=save', {
        id: id,
        status: newStatus,
        inactive_reason: reason || ''
    }, function (res) {
        if (res.status === 'success') {
            loadWorkshops();
            showToast('Status updated!', 'success');
        } else {
            showToast(res.message || 'Update failed', 'danger');
        }
    });
}

function showToast(msg, type) {
    const el = document.createElement('div');
    el.className = 'position-fixed';
    el.style.cssText = 'top:20px;right:20px;z-index:9999;min-width:300px';
    el.innerHTML = '<div class="alert alert-' + (type === 'success' ? 'success' : 'danger') + ' alert-dismissible fade show" role="alert">' +
        msg + '<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>';
    document.body.appendChild(el);
    setTimeout(() => el.remove(), 5000);
}

function debounce(fn, ms) {
    let t;
    return function (...a) { clearTimeout(t); t = setTimeout(() => fn(...a), ms); };
}

function esc(text) {
    const d = document.createElement('div');
    d.textContent = text == null ? '' : String(text);
    return d.innerHTML;
}
