@extends('layouts.app')

@section('title', 'Subcategory 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">Subcategory Edit</h5>
                <a href="{{ route('subcategory_list') }}" class="badge rounded-pill bg-primary px-3 py-2 text-decoration-none"
                    style="cursor:pointer;">
                    Subcategory List
                </a>
            </div>

            <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 }}</p> --}}

            @if (!$flag && !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('subcategory_update') }}" id="subcategory-edit-form" data-ajax-form="true">
                @csrf
                <input class="form-control" type="hidden" name="id" value="{{ $records->id }}">
                <div class="row">
                    <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 ?? '') }}" autofocus>
                            <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">Code <span class="text-danger">*</span></label>
                        <input class="form-control" type="text" name="code" value="{{ old('code', $records->code) }}">
                        <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">Name <span class="text-danger">*</span></label>
                        <input class="form-control" type="text" name="name" value="{{ old('name', $records->name) }}">
                        <small class="text-danger error-text" data-error="name"></small>
                    </div>
                    <div class="col-lg-4 col-md-6 col-sm-12 mt-2">
                        <label class="form-label text-dark">Status <span class="text-danger">*</span></label>
                        <select class="form-select" name="status">
                            <option value="Active" {{ old('status', $records->status) == 'Active' ? 'selected' : '' }}>
                                Active
                            </option>
                            <option value="Inactive" {{ old('status', $records->status) == 'Inactive' ? 'selected' : '' }}>
                                Inactive</option>
                        </select>
                        <small class="text-danger error-text" data-error="status"></small>
                    </div>
                </div>

                <div class="row mt-3">
                    <div class="col-lg-12 col-md-12 col-sm-12 text-center">
                        <button type="submit" class="badge rounded-pill bg-success px-3 py-2 mt-2 border-0"
                            style="cursor:pointer;">
                            Update
                        </button>
                        <a href="{{ route('subcategory_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() {
            console.log("category_options called");

            const select = $('#category_id');
            const selectedId = select.data('selected');

            $.ajax({
                url: "{{ route('category_options') }}",
                type: "GET",
                dataType: "json",
                success: function(data) {
                    // console.log("data = ", data);
                    let records = data.records;

                    let options = '<option value="">-- Select Category --</option>';

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

                    select.html(options);
                },
                error: function(xhr, status, error) {
                    console.log('Category load error:', error);
                }
            });
        });

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

            if (!form) return;

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

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

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

                clearSubcategoryErrors();

                const result = await Swal.fire({
                    title: '<i class="bi bi-exclamation-circle text-warning fs-1"></i>',
                    text: 'Update this Subcategory?',
                    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: new FormData(form)
                    });

                    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 || 'Subcategory details updated.',
                            width: 330,
                            timer: 1500,
                            showConfirmButton: false
                        }).then(() => {
                            window.location.href = "{{ route('subcategory_list') }}";
                        });
                        return;
                    }

                    if (data.errors) {
                        setSubcategoryErrors(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
