@extends('layouts.app')

@section('title', 'Barcode Creation Form Edit')

@section('content')
    <div class="card content-card">
        <div class="card-body">
            <div class="d-flex justify-content-between align-items-center">
                <h5 class="fw-bold">Barcode Creation Form Edit</h5>
                <a href="{{ route('barcode_list') }}" class="badge rounded-pill bg-primary px-3 py-2 text-decoration-none"
                    style="cursor:pointer;">
                    Barcode Creation List
                </a>
            </div>
            {{-- <h5 class="text-center fw-bold">Barcode Creation Form</h5> --}}

            <div class="line"> </div>

            {{-- @if ($errors->any())
                <div style="color:red">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif --}}
            {{-- <p>check = {{ $check }}</p> --}}

            @if (!empty($message))
                <script>
                    window.addEventListener('load', function() {
                        Swal.fire({
                            title: `{!! $flag ?? false
                                ? '<i class="bi bi-check2-circle text-success fs-1"></i>'
                                : '<i class="bi bi-x-circle text-danger fs-1"></i>' !!}`,
                            text: @json($message),
                            width: 330,
                            timer: @json($flag ?? false ? 1500 : null),
                            showConfirmButton: @json(!($flag ?? false)),
                            customClass: {
                                confirmButton: 'px-2 py-1'
                            }
                        });
                    });
                </script>
            @endif

            <form method="POST" action="{{ route('barcode_update', $records->id) }}" enctype="multipart/form-data"
                id="barcode-edit-form" data-ajax-form="true">
                @csrf
                <input class="form-control" type="hidden" name="id" value="{{ $records->id }}">

                <h6 class="text-primary fw-bold">Core Attributes</h6>
                <div class="row">
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label text-dark">Code <span class="text-danger">*</span></label>
                        <input class="form-control" type="text" name="code" value="{{ old('code', $records->code) }}"
                            autofocus>
                        <small class="text-danger error-text" data-error="code"></small>
                    </div>
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label
                         text-dark">Brand Name <span
                                class="text-danger">*</span></label>
                        <input class="form-control" type="text" name="brand_name"
                            value="{{ old('brand_name', $records->brand_name) }}" autofocus>
                        <small class="text-danger error-text" data-error="brand_name"></small>
                    </div>
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label text-dark">Product Name <span class="text-danger">*</span></label>
                        <input class="form-control" type="text" name="product_name"
                            value="{{ old('product_name', $records->product_name) }}">
                        <small class="text-danger error-text" data-error="product_name"></small>
                    </div>
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label text-dark">Category <span class="text-danger">*</span></label>
                        <select class="form-select" name="category_id" id="category_id"
                            data-selected="{{ old('category_id', $records->category_id) }}">
                            <option value="">-- Select Category --</option>
                        </select>
                        <small class="text-danger error-text" data-error="category_id"></small>
                    </div>
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label text-dark">Subcategory <span class="text-danger">*</span></label>
                        <select class="form-select" name="subcategory_id" id="subcategory_id"
                            data-selected="{{ old('subcategory_id', $records->subcategory_id) }}">
                            <option value="">-- Select Subcategory --</option>
                        </select>
                        <small class="text-danger error-text" data-error="subcategory_id"></small>
                    </div>
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label text-dark">Marketing Information <span class="text-danger">*</span></label>
                        <input class="form-control" type="text" name="marketing_information"
                            value="{{ old('marketing_information', $records->marketing_information) }}">
                        <small class="text-danger error-text" data-error="marketing_information"></small>
                    </div>
                    <div class="col-lg-12 col-md-12 col-sm-12 mt-2">
                        <label class="form-label text-dark">Product Description <span class="text-danger">*</span></label>
                        <textarea class="form-control" rows="3" name="product_description">{{ old('product_description', $records->product_description) }}</textarea>
                        <small class="text-danger error-text" data-error="product_description"></small>
                    </div>
                </div>

                <hr class="hr-line mt-3">
                <h6 class="text-primary fw-bold">Images Details</h6>
                <div class="row">
                    <div class="col-lg-6 col-md-12 col-sm-12 mt-2">
                        <label class="form-label text-dark">Product Image <span class="text-danger">*</span></label>
                        <input class="form-control" type="file" name="product_image" id="product_image"
                            value="{{ old('product_image', $records->product_image) }}" accept=".jpg,.jpeg,.png">
                        @if (!empty($records->product_image))
                            <div class="mt-2">
                                <img src="{{ asset($records->product_image) }}" alt="Product Image"
                                    style="max-height:80px;">
                            </div>
                        @endif
                        <small class="text-danger error-text" data-error="product_image"></small>
                    </div>
                    <div class="col-lg-6 col-md-12 col-sm-12 mt-2">
                        <label class="form-label text-dark">Art Work Image <span class="text-danger">*</span></label>
                        <input class="form-control" type="file" name="art_work_image" id="art_work_image"
                            value="{{ old('art_work_image', $records->art_work_image) }}" accept=".jpg,.jpeg,.png">
                        @if (!empty($records->art_work_image))
                            <div class="mt-2">
                                <img src="{{ asset($records->art_work_image) }}" alt="Art Work Image"
                                    style="max-height:80px;">
                            </div>
                        @endif
                        <small class="text-danger error-text" data-error="art_work_image"></small>
                    </div>
                </div>

                <hr class="hr-line mt-3">
                <h6 class="text-primary fw-bold">Weights & Measures Details</h6>
                <div class="row">
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label text-dark">Net Content Unit <span class="text-danger">*</span></label>
                        <select class="form-select" name="net_content_unit" id="net_content_unit">
                            <option value="">-- Select Net Content Unit --</option>
                            <option value="Milligrams (mg)"
                                {{ old('net_content_unit', $records->net_content_unit) == 'Milligrams (mg)' ? 'selected' : '' }}>
                                Milligrams (mg)</option>
                            <option value="Millimeter (MM)"
                                {{ old('net_content_unit', $records->net_content_unit) == 'Millimeter (MM)' ? 'selected' : '' }}>
                                Millimeter (MM)</option>
                            <option value="Pounds (lbs)"
                                {{ old('net_content_unit', $records->net_content_unit) == 'Pounds (lbs)' ? 'selected' : '' }}>
                                Pounds
                                (lbs)</option>
                            <option value="Grams (Gms)"
                                {{ old('net_content_unit', $records->net_content_unit) == 'Grams (Gms)' ? 'selected' : '' }}>
                                Grams (Gms)
                            </option>
                            <option value="Kilograms (Kg)"
                                {{ old('net_content_unit', $records->net_content_unit) == 'Kilograms (Kg)' ? 'selected' : '' }}>
                                Kilograms (Kg)</option>
                            <option value="Milliliters (Ml)"
                                {{ old('net_content_unit', $records->net_content_unit) == 'Milliliters (Ml)' ? 'selected' : '' }}>
                                Milliliters (Ml)</option>
                        </select>
                        <small class="text-danger error-text" data-error="net_content_unit"></small>
                    </div>
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label text-dark">Mass Unit <span class="text-danger">*</span></label>
                        <select class="form-select" name="mass_unit" id="mass_unit">
                            <option value="">-- Select Mass Unit --</option>
                            <option value="Grams (Gms)"
                                {{ old('mass_unit', $records->mass_unit) == 'Grams (Gms)' ? 'selected' : '' }}>Grams (Gms)
                            </option>
                            <option value="Kilograms (Kg)"
                                {{ old('mass_unit', $records->mass_unit) == 'Kilograms (Kg)' ? 'selected' : '' }}>
                                Kilograms (Kg)</option>
                        </select>
                        <small class="text-danger error-text" data-error="mass_unit"></small>
                    </div>
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label text-dark">Net Weight <span class="text-danger">*</span></label>
                        <input class="form-control" type="text" name="net_weight"
                            value="{{ old('net_weight', $records->net_weight) }}" maxlength="10"
                            oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0,10)">
                        <small class="text-danger error-text" data-error="net_weight"></small>
                    </div>
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label text-dark">Net Content <span class="text-danger">*</span></label>
                        <input class="form-control" type="text" name="net_content"
                            value="{{ old('net_content', $records->net_content) }}" maxlength="10"
                            oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0,10)">
                        <small class="text-danger error-text" data-error="net_content"></small>
                    </div>
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label text-dark">Gross Weight <span class="text-danger">*</span></label>
                        <input class="form-control" type="text" name="gross_weight"
                            value="{{ old('gross_weight', $records->gross_weight) }}" maxlength="10"
                            oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0,10)">
                        <small class="text-danger error-text" data-error="gross_weight"></small>
                    </div>
                </div>

                <hr class="hr-line mt-3">
                <h6 class="text-primary fw-bold">MRP Details</h6>
                <div class="row">
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label text-dark">MRP Activation Date <span class="text-danger">*</span></label>
                        <input class="form-control" type="date" name="mrp_activation_date"
                            value="{{ old('mrp_activation_date', $records->mrp_activation_date) }}">
                        <small class="text-danger error-text" data-error="mrp_activation_date"></small>
                    </div>
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label text-dark">Location <span class="text-danger">*</span></label>
                        <input class="form-control" type="text" name="location"
                            value="{{ old('location', $records->location) }}">
                        <small class="text-danger error-text" data-error="location"></small>
                    </div>
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label text-dark">MRP <span class="text-danger">*</span></label>
                        <input class="form-control" type="text" name="mrp"
                            value="{{ old('mrp', $records->mrp) }}" maxlength="10"
                            oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0,10)">
                        <small class="text-danger error-text" data-error="mrp"></small>
                    </div>
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label text-dark">HSN <span class="text-danger">*</span></label>
                        <input class="form-control" type="text" name="hsn"
                            value="{{ old('hsn', $records->hsn) }}" maxlength="8"
                            oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0,8)">
                        <small class="text-danger error-text" data-error="hsn"></small>
                    </div>
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label text-dark">GST <span class="text-danger">*</span></label>
                        <input class="form-control" type="text" name="gst"
                            value="{{ old('gst', $records->gst) }}">
                        <small class="text-danger error-text" data-error="gst"></small>
                    </div>
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label text-dark">FSSAI License Number <span
                                class="text-danger">*</span></label>
                        <input class="form-control" type="text" name="fssai_no"
                            value="{{ old('fssai_no', $records->fssai_no) }}">
                        <small class="text-danger error-text" data-error="fssai_no"></small>
                    </div>
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label text-dark">Food Type <span class="text-danger">*</span></label>
                        <input class="form-control" type="text" name="food_type"
                            value="{{ old('food_type', $records->food_type) }}">
                        <small class="text-danger error-text" data-error="food_type"></small>
                    </div>
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label text-dark">Shelf life-value <span class="text-danger">*</span></label>
                        <input class="form-control" type="text" name="shelf_life_value"
                            value="{{ old('shelf_life_value', $records->shelf_life_value) }}" maxlength="10"
                            oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0,10)">
                        <small class="text-danger error-text" data-error="shelf_life_value"></small>
                    </div>
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label text-dark">Shelf life-Unit <span class="text-danger">*</span></label>
                        <select class="form-select" name="shelf_life_unit" id="shelf_life_unit">
                            <option value="">-- Select Shelf Life-Unit --</option>
                            <option value="Days"
                                {{ old('shelf_life_unit', $records->shelf_life_unit) == 'Days' ? 'selected' : '' }}>Days
                            </option>
                            <option value="Months"
                                {{ old('shelf_life_unit', $records->shelf_life_unit) == 'Months' ? 'selected' : '' }}>
                                Months</option>
                            <option value="Years"
                                {{ old('shelf_life_unit', $records->shelf_life_unit) == 'Years' ? 'selected' : '' }}>
                                Years
                            </option>
                        </select>
                        <small class="text-danger error-text" data-error="shelf_life_unit"></small>
                    </div>
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label text-dark">Shelf life-Based on <span class="text-danger">*</span></label>
                        <input class="form-control" type="text" name="shelf_life_based_on"
                            value="{{ old('shelf_life_based_on', $records->shelf_life_based_on) }}">
                        <small class="text-danger error-text" data-error="shelf_life_based_on"></small>
                    </div>
                </div>

                <div class="row mt-2">
                    <div class="col-lg-12 col-md-12 col-sm-12 text-center">
                        <button type="submit" name="status" value="Drafted"
                            class="badge rounded-pill bg-primary px-3 py-2 mt-2 border-0" style="cursor:pointer;">
                            Save Draft
                        </button>
                        <button type="submit" name="status" value="Applied"
                            class="badge rounded-pill bg-success px-3 py-2 mt-2 border-0" style="cursor:pointer;">
                            Update & Submit
                        </button>
                        <a href="{{ route('barcode_list') }}"
                            class="badge rounded-pill bg-secondary px-3 py-2 mt-2 text-decoration-none"
                            style="cursor:pointer;">
                            Back
                        </a>
                    </div>
                </div>
            </form>
        </div>
    </div>
@endsection


@push('scripts')
    <script>
        $(document).ready(function() {
            const categorySelect = $('#category_id');
            const subcategorySelect = $('#subcategory_id');
            // console.log("categorySelect = ", categorySelect);
            // console.log("subcategorySelect = ", subcategorySelect);

            const selectedCategoryId = categorySelect.data('selected') || '';
            const selectedSubcategoryId = subcategorySelect.data('selected') || '';
            // console.log("selectedCategoryId = ", selectedCategoryId);
            // console.log("selectedSubcategoryId = ", selectedSubcategoryId);

            let allSubcategories = [];

            function renderSubcategories(categoryId, selectedId = '') {
                let options = '<option value="">-- Select Sub Category --</option>';

                if (categoryId) {
                    const filtered = allSubcategories.filter(function(row) {
                        return String(row.category_id) === String(categoryId);
                    });

                    $.each(filtered, function(index, row) {
                        const selected = String(selectedId) === String(row.id) ? 'selected' : '';
                        options += `<option value="${row.id}" ${selected}>${row.name}</option>`;
                    });
                }

                subcategorySelect.html(options);
            }

            $.ajax({
                url: "{{ route('category_options') }}",
                type: "GET",
                dataType: "json",
                success: function(data) {
                    let records = data.records || [];
                    let options = '<option value="">-- Select Category --</option>';

                    $.each(records, function(index, row) {
                        const selected = String(selectedCategoryId) === String(row.id) ?
                            'selected' : '';
                        options += `<option value="${row.id}" ${selected}>${row.name}</option>`;
                    });

                    categorySelect.html(options);
                }
            });

            $.ajax({
                url: "{{ route('subcategory_options') }}",
                type: "GET",
                dataType: "json",
                success: function(data) {
                    allSubcategories = data.records || [];
                    renderSubcategories(selectedCategoryId, selectedSubcategoryId);
                }
            });

            categorySelect.on('change', function() {
                renderSubcategories($(this).val());
            });
        });

        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('barcode-edit-form');
            const loader = document.getElementById('page-loader');
            const tokenMeta = document.querySelector('meta[name="csrf-token"]');
            if (!form) return;

            function clearBarcodeErrors() {
                document.querySelectorAll('#barcode-edit-form .error-text').forEach(function(el) {
                    el.textContent = '';
                });
            }

            function setBarcodeErrors(errors) {
                Object.keys(errors).forEach(function(field) {
                    const el = document.querySelector(
                        `#barcode-edit-form .error-text[data-error="${field}"]`);
                    if (el) el.textContent = errors[field][0];
                });
            }

            form.addEventListener('submit', async function(e) {
                e.preventDefault();
                clearBarcodeErrors();

                const submitter = e.submitter;
                const submitType = submitter ? submitter.value : '';
                const formData = new FormData(form);

                if (submitter && submitter.name) {
                    formData.append(submitter.name, submitter.value);
                }
                console.log("formData = ", formData);

                const result = await Swal.fire({
                    title: '<i class="bi bi-exclamation-circle text-warning fs-1"></i>',
                    text: submitType === 'Drafted' ?
                        'Save these Barcode Creation Details as draft?' :
                        'Update & Submit these Barcode Creation Details?',
                    width: 330,
                    showCancelButton: true,
                    confirmButtonText: 'Yes',
                    cancelButtonText: 'No',
                    customClass: {
                        confirmButton: 'px-2 py-1',
                        cancelButton: 'px-2 py-1'
                    }
                });

                if (!result.isConfirmed) return;

                if (loader) loader.classList.remove('hidden');

                try {
                    const response = await fetch(form.action, {
                        method: 'POST',
                        headers: {
                            'X-CSRF-TOKEN': tokenMeta ? tokenMeta.getAttribute('content') : '',
                            'Accept': 'application/json'
                        },
                        body: formData
                    });

                    const data = await response.json();

                    if (loader) loader.classList.add('hidden');

                    if (response.ok && data.flag) {
                        Swal.fire({
                            title: '<i class="bi bi-check2-circle text-success fs-1"></i>',
                            text: data.message || 'Barcode Creation details updated.',
                            width: 330,
                            timer: 1500,
                            showConfirmButton: false
                        }).then(() => {
                            window.location.href = "{{ route('barcode_list') }}";
                        });
                        return;
                    }

                    if (data.errors) {
                        setBarcodeErrors(data.errors);
                    }

                    Swal.fire({
                        title: '<i class="bi bi-x-circle text-danger fs-1"></i>',
                        text: data.message || 'Update failed.',
                        width: 330,
                        customClass: {
                            confirmButton: 'px-2 py-1'
                        }
                    });
                } catch (error) {
                    if (loader) loader.classList.add('hidden');

                    Swal.fire({
                        title: '<i class="bi bi-x-circle text-danger fs-1"></i>',
                        text: 'Something went wrong.',
                        width: 330,
                        customClass: {
                            confirmButton: 'px-2 py-1'
                        }
                    });
                }
            });
        });
    </script>
@endpush
