@extends('layouts.app')

@section('title', 'Category Create')

@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">Category Create</h5>
                <a href="{{ route('category_list') }}" class="badge rounded-pill bg-primary px-3 py-2 text-decoration-none"
                    style="cursor:pointer;">
                    Category 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 (!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('category_store') }}" id="category-create-form" data-ajax-form="true">
                @csrf
                <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') }}" 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">Name <span class="text-danger">*</span></label>
                        <input class="form-control" type="text" name="name" value="{{ old('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', 'Active') == 'Active' ? 'selected' : '' }}>Active
                            </option>
                            <option value="Inactive" {{ old('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;">
                            Save
                        </button>
                        <a href="{{ route('category_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


<script>
    document.addEventListener('DOMContentLoaded', function() {
        const form = document.getElementById('category-create-form');
        const loader = document.getElementById('page-loader');
        const tokenMeta = document.querySelector('meta[name="csrf-token"]');

        if (!form) return;

        function clearCategoryErrors() {
            document.querySelectorAll('#category-create-form .error-text').forEach(function(el) {
                el.textContent = '';
            });
        }

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

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

            clearCategoryErrors();

            const result = await Swal.fire({
                title: '<i class="bi bi-exclamation-circle text-warning fs-1"></i>',
                text: 'Save this Category?',
                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) {
                    form.reset();
                    const statusField = form.querySelector('[name="status"]');
                    if (statusField) {
                        statusField.value = 'Active';
                    }

                    Swal.fire({
                        title: '<i class="bi bi-check2-circle text-success fs-1"></i>',
                        text: data.message || 'Category details saved.',
                        width: 330,
                        timer: 1500,
                        showConfirmButton: false
                    });
                    return;
                }

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

                Swal.fire({
                    title: '<i class="bi bi-x-circle text-danger fs-1"></i>',
                    text: data.message || 'Save 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>
