<?php if (isset($component)) { $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54 = $attributes; } ?>
<?php $component = App\View\Components\AppLayout::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('app-layout'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\App\View\Components\AppLayout::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes([]); ?>
     <?php $__env->slot('header', null, []); ?> 
        <div class="flex items-center justify-between w-full">
            <div>
                <h1 class="text-lg font-semibold text-gray-800">Add Item</h1>
                <p class="text-xs text-gray-400 mt-0.5">HS Code / UoM / Rate FBR se live fetch hote hain</p>
            </div>
            <a href="<?php echo e(route('items.index')); ?>" class="text-sm text-gray-500 hover:text-gray-700 font-medium">
                Back to Items
            </a>
        </div>
     <?php $__env->endSlot(); ?>

    <div class="max-w-3xl mx-auto" x-data="itemForm()" x-init="init()">

        <form @submit.prevent="submit" class="bg-white rounded-xl border border-gray-100 shadow-sm p-6 space-y-5">

            <div class="grid sm:grid-cols-2 gap-5">

                <div class="sm:col-span-2">
                    <label class="block text-xs font-medium text-gray-500 mb-1">Name <span class="text-red-500">*</span></label>
                    <input type="text" x-model="form.name"
                           class="w-full rounded-lg border-gray-200 text-sm focus:border-indigo-400 focus:ring-indigo-400"
                           :class="errors.name && 'border-red-400'">
                    <p class="text-xs text-red-500 mt-1" x-show="errors.name" x-text="errors.name?.[0]"></p>
                </div>

                <div>
                    <label class="block text-xs font-medium text-gray-500 mb-1">SKU</label>
                    <input type="text" x-model="form.sku"
                           class="w-full rounded-lg border-gray-200 text-sm focus:border-indigo-400 focus:ring-indigo-400"
                           :class="errors.sku && 'border-red-400'">
                    <p class="text-xs text-red-500 mt-1" x-show="errors.sku" x-text="errors.sku?.[0]"></p>
                </div>

                
                <div class="relative">
                    <label class="block text-xs font-medium text-gray-500 mb-1">HS Code <span class="text-red-500">*</span></label>
                    <div class="relative">
                        <input type="text" x-model="hsSearch"
                               @input.debounce.350ms="searchHsCode()"
                               @keydown.arrow-down.prevent="moveHsHighlight(1)"
                               @keydown.arrow-up.prevent="moveHsHighlight(-1)"
                               @keydown.enter.prevent="hsResults[hsHighlight] && selectHsCode(hsResults[hsHighlight])"
                               @keydown.escape="hsOpen = false"
                               @focus="hsResults.length && (hsOpen = true)" @click.outside="hsOpen = false"
                               placeholder="Search HS code or product description..."
                               autocomplete="off"
                               class="w-full rounded-lg border-gray-200 text-sm focus:border-indigo-400 focus:ring-indigo-400 pr-7"
                               :class="errors.hs_code && 'border-red-400'">
                        <button type="button" x-show="hsSearch" @click="clearHsCode()"
                                class="absolute right-2 top-1/2 -translate-y-1/2 text-gray-300 hover:text-gray-500 text-xs">✕</button>
                    </div>
                    <input type="hidden" x-model="form.hs_code">

                    <div x-show="hsOpen" x-cloak
                         class="absolute z-20 mt-1 w-full bg-white border border-gray-200 rounded-lg shadow-lg max-h-64 overflow-y-auto">
                        <template x-if="hsSearch.trim().length < 2">
                            <p class="px-3 py-2 text-xs text-gray-400">Type at least 2 characters to search.</p>
                        </template>
                        <template x-if="hsSearch.trim().length >= 2 && hsLoading">
                            <p class="px-3 py-2 text-xs text-gray-400 flex items-center gap-2">
                                <span class="inline-block h-3 w-3 rounded-full border-2 border-indigo-300 border-t-transparent animate-spin"></span>
                                Searching FBR...
                            </p>
                        </template>
                        <template x-if="hsSearch.trim().length >= 2 && !hsLoading && hsResults.length === 0">
                            <p class="px-3 py-2 text-xs text-gray-400">No matches found.</p>
                        </template>
                        <template x-for="(row, i) in hsResults" :key="row.code">
                            <button type="button" @click="selectHsCode(row)" @mouseenter="hsHighlight = i"
                                    class="w-full text-left px-3 py-2 text-xs border-b border-gray-50 last:border-0"
                                    :class="i === hsHighlight ? 'bg-indigo-50' : 'hover:bg-gray-50'">
                                <span class="font-medium text-gray-700" x-text="row.code"></span>
                                <span class="text-gray-400 block truncate" x-text="row.desc"></span>
                            </button>
                        </template>
                    </div>
                    <p class="text-xs text-red-500 mt-1" x-show="errors.hs_code" x-text="errors.hs_code?.[0]"></p>
                </div>

                
                <div>
                    <label class="block text-xs font-medium text-gray-500 mb-1">UoM <span class="text-red-500">*</span></label>
                    <template x-if="!uomManualEntry">
                        <select x-model="form.uom" :disabled="!form.hs_code"
                                class="w-full rounded-lg border-gray-200 text-sm focus:border-indigo-400 focus:ring-indigo-400 disabled:bg-gray-50 disabled:text-gray-400"
                                :class="errors.uom && 'border-red-400'">
                            <option value=""><?php echo e('-- select --'); ?></option>
                            <template x-for="u in uomOptions" :key="u">
                                <option :value="u" x-text="u"></option>
                            </template>
                        </select>
                    </template>
                    <template x-if="uomManualEntry">
                        <input type="text" x-model="form.uom" placeholder="Enter UoM manually"
                               class="w-full rounded-lg border-gray-200 text-sm focus:border-indigo-400 focus:ring-indigo-400"
                               :class="errors.uom && 'border-red-400'">
                    </template>

                    <p class="text-xs text-gray-400 mt-1" x-show="!form.hs_code">Select an HS code first.</p>
                    <p class="text-xs text-gray-400 mt-1" x-show="uomLoading">Fetching applicable UoMs...</p>
                    <p class="text-xs text-amber-600 mt-1" x-show="form.hs_code && !uomLoading && uomOptions.length === 0 && !uomManualEntry">
                        FBR returned no UoM for this HS code —
                        <button type="button" class="underline" @click="uomManualEntry = true">enter it manually</button>.
                    </p>
                    <button type="button" x-show="uomManualEntry" class="text-xs text-indigo-600 underline mt-1"
                            @click="uomManualEntry = false; form.uom = ''">
                        Back to FBR list
                    </button>
                    <p class="text-xs text-red-500 mt-1" x-show="errors.uom" x-text="errors.uom?.[0]"></p>
                </div>

                
                <div>
                    <label class="block text-xs font-medium text-gray-500 mb-1">Transaction Type</label>
                    <select x-model="transTypeId" @change="fetchRates()"
                            class="w-full rounded-lg border-gray-200 text-sm focus:border-indigo-400 focus:ring-indigo-400">
                        <option value="">-- select --</option>
                        <template x-for="t in transTypes" :key="t.id">
                            <option :value="t.id" x-text="t.desc"></option>
                        </template>
                    </select>
                </div>

                
                <div>
                    <label class="block text-xs font-medium text-gray-500 mb-1">Rate As Of</label>
                    <input type="date" x-model="rateDate" @change="fetchRates()"
                           class="w-full rounded-lg border-gray-200 text-sm focus:border-indigo-400 focus:ring-indigo-400">
                </div>

                
                <div>
                    <label class="block text-xs font-medium text-gray-500 mb-1">Default Rate <span class="text-red-500">*</span></label>
                    <select x-model="selectedRateId" @change="applyRate()" :disabled="!transTypeId"
                            class="w-full rounded-lg border-gray-200 text-sm focus:border-indigo-400 focus:ring-indigo-400 disabled:bg-gray-50 disabled:text-gray-400"
                            :class="errors.default_rate && 'border-red-400'">
                        <option value=""><?php echo e('-- select transaction type first --'); ?></option>
                        <template x-for="r in rateOptions" :key="r.id">
                            <option :value="r.id" x-text="r.desc"></option>
                        </template>
                    </select>
                    <p class="text-xs text-gray-400 mt-1" x-show="ratesLoading">Fetching rates from FBR...</p>
                    <p class="text-xs text-gray-400 mt-1" x-show="transTypeId && !ratesLoading && rateOptions.length === 0">
                        No rates found for this transaction type / date.
                    </p>
                    <p class="text-xs text-red-500 mt-1" x-show="errors.default_rate" x-text="errors.default_rate?.[0]"></p>
                </div>

                <div>
                    <label class="block text-xs font-medium text-gray-500 mb-1">Default Price (Excl. ST) <span class="text-red-500">*</span></label>
                    <input type="number" step="0.01" x-model="form.default_price_excl_st"
                           class="w-full rounded-lg border-gray-200 text-sm focus:border-indigo-400 focus:ring-indigo-400"
                           :class="errors.default_price_excl_st && 'border-red-400'">
                    <p class="text-xs text-red-500 mt-1" x-show="errors.default_price_excl_st" x-text="errors.default_price_excl_st?.[0]"></p>
                </div>

                
                <div class="sm:col-span-2 bg-gray-50/60 rounded-lg p-3 space-y-3">
                    <div class="flex items-center justify-between">
                        <p class="text-xs font-medium text-gray-500">SRO Schedule (only if this rate requires one)</p>
                        <button type="button" @click="fetchSroSchedules()" :disabled="!selectedRateId"
                                class="text-xs text-indigo-600 font-medium hover:text-indigo-700 disabled:opacity-40 disabled:cursor-not-allowed">
                            Fetch SRO Schedules
                        </button>
                    </div>
                    <div class="grid sm:grid-cols-2 gap-3">
                        <div>
                            <select x-model="form.sro_schedule_no"
                                    class="w-full rounded-lg border-gray-200 text-sm focus:border-indigo-400 focus:ring-indigo-400">
                                <option value="">-- none --</option>
                                <template x-for="s in sroOptions" :key="s.no">
                                    <option :value="s.no" x-text="s.desc"></option>
                                </template>
                            </select>
                        </div>
                        <div>
                            <input type="text" x-model="form.sro_item_serial_no" placeholder="SRO Item Serial No"
                                   :disabled="!form.sro_schedule_no"
                                   class="w-full rounded-lg border-gray-200 text-sm focus:border-indigo-400 focus:ring-indigo-400 disabled:bg-gray-50 disabled:text-gray-400">
                        </div>
                    </div>
                    <p class="text-xs text-gray-400" x-show="sroLoading">Fetching SRO schedules...</p>
                    <p class="text-xs text-gray-400" x-show="!sroLoading && selectedRateId && sroOptions.length === 0 && sroFetched">
                        No SRO schedule required for this rate.
                    </p>
                </div>

                <div class="flex items-center gap-2 pt-2">
                    <input type="checkbox" x-model="form.is_active" id="is_active"
                           class="rounded border-gray-300 text-indigo-600 focus:ring-indigo-400">
                    <label for="is_active" class="text-sm text-gray-600">Active</label>
                </div>
            </div>

            <div class="flex items-center gap-3 pt-2 border-t border-gray-100">
                <button type="submit" :disabled="saving"
                        class="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-indigo-600 text-white text-sm font-medium hover:bg-indigo-700 disabled:opacity-50 transition">
                    <span x-text="saving ? 'Saving...' : 'Save Item'"></span>
                </button>
                <a href="<?php echo e(route('items.index')); ?>" class="text-sm text-gray-500 hover:text-gray-700">Cancel</a>
            </div>
        </form>
    </div>

    <script>
        function itemForm() {
            return {
                saving: false,
                errors: {},
                form: {
                    name: '', sku: '', hs_code: '', uom: '', default_rate: '',
                    default_sale_type: '', default_price_excl_st: '',
                    sro_schedule_no: '', sro_item_serial_no: '', is_active: true,
                },

                // HS code typeahead
                hsSearch: '', hsResults: [], hsOpen: false, hsLoading: false, hsHighlight: 0,

                // UoM
                uomOptions: [], uomLoading: false, uomManualEntry: false,

                // Transaction type + rate
                transTypes: [], transTypeId: '', rateDate: new Date().toISOString().slice(0, 10),
                rateOptions: [], selectedRateId: '', ratesLoading: false,

                // SRO
                sroOptions: [], sroLoading: false, sroFetched: false,

                // Any FBR reference endpoint returns {success, data}. apiFetch may or
                // may not unwrap that envelope, so normalize defensively either way.
                unwrap(res) {
                    const payload = res && typeof res === 'object' && 'data' in res ? res.data : res;
                    return Array.isArray(payload) ? payload : [];
                },

                async init() {
                    try {
                        const res = await apiFetch('/fbr/transaction-types');
                        this.transTypes = this.unwrap(res).map(t => ({
                            id: t.transactioN_TYPE_ID ?? t.trans_type_id ?? t.id,
                            desc: t.transactioN_DESC ?? t.description ?? t.desc ?? `Type ${t.id ?? ''}`,
                        }));
                    } catch (e) { /* toast already shown */ }
                },

                async searchHsCode() {
                    this.hsHighlight = 0;
                    if (this.hsSearch.trim().length < 2) { this.hsResults = []; this.hsOpen = true; return; }
                    this.hsLoading = true;
                    this.hsOpen = true;
                    try {
                        const res = await apiFetch(`/fbr/item-codes?search=${encodeURIComponent(this.hsSearch.trim())}`);
                        this.hsResults = this.unwrap(res).map(r => ({
                            code: r.hS_CODE ?? r.HS_CODE ?? r.code ?? r.hsCode ?? '',
                            desc: r.hS_DESC ?? r.HS_DESC ?? r.description ?? r.desc ?? '',
                        }));
                    } catch (e) {
                        this.hsResults = [];
                    } finally {
                        this.hsLoading = false;
                    }
                },

                moveHsHighlight(dir) {
                    if (!this.hsResults.length) return;
                    this.hsHighlight = (this.hsHighlight + dir + this.hsResults.length) % this.hsResults.length;
                },

                selectHsCode(row) {
                    this.form.hs_code = row.code;
                    this.hsSearch = `${row.code} — ${row.desc}`;
                    this.hsOpen = false;
                    this.uomManualEntry = false;
                    this.form.uom = '';
                    this.fetchUom(row.code);
                },

                clearHsCode() {
                    this.hsSearch = '';
                    this.form.hs_code = '';
                    this.hsResults = [];
                    this.uomOptions = [];
                    this.form.uom = '';
                    this.uomManualEntry = false;
                },

                async fetchUom(hsCode) {
                    this.uomLoading = true;
                    this.uomOptions = [];
                    try {
                        const res = await apiFetch(`/fbr/hs-uom?hs_code=${encodeURIComponent(hsCode)}&annexure_id=3`);
                        this.uomOptions = this.unwrap(res)
                            .map(u => u.description ?? u.uoM ?? u.uom ?? u.desc)
                            .filter(Boolean);
                        if (this.uomOptions.length === 1) this.form.uom = this.uomOptions[0];
                        if (this.uomOptions.length === 0) this.uomManualEntry = true;
                    } catch (e) {
                        this.uomManualEntry = true;
                    } finally {
                        this.uomLoading = false;
                    }
                },

                async fetchRates() {
                    this.rateOptions = [];
                    this.selectedRateId = '';
                    if (!this.transTypeId || !this.rateDate) return;
                    this.ratesLoading = true;
                    try {
                        const res = await apiFetch(`/fbr/sale-type-to-rate?date=${this.rateDate}&trans_type_id=${this.transTypeId}&origination_supplier=1`);
                        this.rateOptions = this.unwrap(res).map(r => ({
                            id: r.ratE_ID ?? r.rate_id ?? r.id,
                            desc: r.ratE_DESC ?? r.description ?? r.desc ?? `${r.ratE_VALUE ?? ''}%`,
                        }));
                    } catch (e) {
                        // toast shown
                    } finally {
                        this.ratesLoading = false;
                    }
                },

                applyRate() {
                    this.sroOptions = [];
                    this.sroFetched = false;
                    this.form.sro_schedule_no = '';
                    this.form.sro_item_serial_no = '';
                    const rate = this.rateOptions.find(r => String(r.id) === String(this.selectedRateId));
                    if (!rate) return;
                    this.form.default_rate = rate.desc;
                    const type = this.transTypes.find(t => String(t.id) === String(this.transTypeId));
                    this.form.default_sale_type = type ? type.desc : '';
                },

                async fetchSroSchedules() {
                    if (!this.selectedRateId) return;
                    this.sroLoading = true;
                    this.sroOptions = [];
                    try {
                        const res = await apiFetch(`/fbr/sro-schedule?rate_id=${this.selectedRateId}&date=${this.rateDate}`);
                        this.sroOptions = this.unwrap(res).map(s => ({
                            no: s.srO_ID ?? s.sro_id ?? s.no,
                            desc: s.srO_DESC ?? s.description ?? s.desc ?? `SRO ${s.no ?? ''}`,
                        }));
                    } catch (e) {
                        // toast shown
                    } finally {
                        this.sroLoading = false;
                        this.sroFetched = true;
                    }
                },

                async submit() {
                    this.errors = {};
                    this.saving = true;
                    try {
                        await apiFetch('<?php echo e(route('items.store')); ?>', { method: 'POST', body: this.form });
                        flashAndRedirect('Item created.', 'success', '<?php echo e(route('items.index')); ?>');
                    } catch (e) {
                        if (e.status === 422) this.errors = e.errors;
                    } finally {
                        this.saving = false;
                    }
                },
            };
        }
    </script>
 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $attributes = $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $component = $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?><?php /**PATH /www/wwwroot/an.shiningerp.com/resources/views/items/create.blade.php ENDPATH**/ ?>