import { Controller } from "@hotwired/stimulus" export default class extends Controller { static targets = ["select", "phoneField", "birthYearField", "firstNameField", "surnameField", "newCustomerFields"] connect() { this.selectInstance = new TomSelect(this.selectTarget, { valueField: 'id', labelField: 'label', searchField: ['label'], maxItems: 1, create: true, createOnBlur: true, placeholder: 'Type to search customers...', create: function(input) { return { id: `${input}__new`, label: `${input} (New Customer)` }; }, options: [], load: async (query, callback) => { if (!query.length) return callback(); try { const response = await fetch(`/customers/search?q=${encodeURIComponent(query)}`, { headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' } }); const data = await response.json(); callback(data); } catch (error) { console.error('Error loading customers:', error); callback(); } }, shouldLoad: function(query) { return query.length >= 2; }, render: { no_results: (data, escape) => { return '
No customers found. Fill in the details below.
'; }, option: function(item) { return `
${item.label}
`; } }, // Events onLoad: (data) => { if (!data || data.length === 0) { this.showNewCustomerFields(); } }, onChange: (value) => { if (value === null) { this.showNewCustomerFields(); } }, onItemAdd: (value) => { this.customerSelected(value); }, onDropdownClose: (dropdown) => { if (!this.selectInstance.getValue()) { this.showNewCustomerFields(); } } }); } customerSelected(value) { if (value.endsWith('__new')) { const firstName = value.replace('__new', ''); this.firstNameFieldTarget.value = firstName; this.showNewCustomerFields(); return; } const [firstName, surname, phone] = value.split('_'); if (firstName && surname && phone) { const customerData = this.selectInstance.options[value]; this.phoneFieldTarget.value = phone; this.firstNameFieldTarget.value = firstName; this.surnameFieldTarget.value = surname; if (customerData && customerData.birthyear) { this.birthYearFieldTarget.value = customerData.birthyear; } this.newCustomerFieldsTarget.classList.add('hidden'); } } showNewCustomerFields() { this.newCustomerFieldsTarget.classList.remove('hidden'); } clearFields() { this.phoneFieldTarget.value = ''; this.firstNameFieldTarget.value = ''; this.surnameFieldTarget.value = ''; this.birthYearFieldTarget.value = ''; } disconnect() { if (this.selectInstance) { this.selectInstance.destroy(); } } }