@extends('layouts.admin')
@section('content')
<!-- start page title -->
<div class="row">
    <div class="col-12">
        <div class="page-title-box d-sm-flex align-items-center justify-content-between bg-galaxy-transparent">
            <h4 class="mb-sm-0">Create App Icons</h4>

            <div class="page-title-right">
                <ol class="breadcrumb m-0">
                    <li class="breadcrumb-item"><a href="javascript: void(0);">Home</a></li>
                    <li class="breadcrumb-item"><a href="javascript: void(0);">App Icons</a></li>
                    <li class="breadcrumb-item active">{{ (!empty($eventtype->id)) ? 'Update App Icons' : 'Create App Icons' }}</li>
                </ol>
            </div>
        </div>
    </div>
</div>
<!-- end page title -->

<div class="row">
    <div class="col-lg-12">
        <div class="card" id="orderList"> 
            <div class="card-body">
                <form class="tablelist-form {{ !empty($slider->id) ? 'edit-form' : '' }}" autocomplete="off" name="sliderForm" id="sliderForm" method="post" novalidate enctype="multipart/form-data" action="{{ route('admin.homelogos.store') }}">
                    @csrf
                    <input type="hidden" name="id" id="id" value="{{ (!empty($slider->id)) ? $slider->id : '' }}" />

                    <div class="row">
                        <!-- Slider Name -->
                        <div class="col-lg-4 mb-3">
                            <label for="name" class="form-label">Title</label>
                            <input type="text" id="name" name="name" class="form-control" placeholder="Enter Work Process Title" required value="{{ old('name', $slider->name ?? '') }}" />
                        </div>

                        <!-- Background Image -->
                        <div class="col-lg-4 mb-3">
                            <label for="image" class="form-label"> Image</label>
                            <input type="file" id="image_field" name="image" class="form-control icon-image-field" accept="image/*" />
                            <img id="imagePreview" class="img-thumbnail mt-2" style="display:none;" width="150">
                            @if(!empty($slider->image))
                             <div id="editimage">
                                <img src="{{ !empty($slider->image) ? $slider->image : asset('assets/images/camera_placeholder.png') }}" class="img-fluid icon-image-preview" alt="profile image" style="height: 100px; width: 100px;">
                             </div>
                            @endif
                        </div>

                        <!-- Status -->
                        <div class="col-lg-4 mb-3">
                            <label for="status" class="form-label">Status</label>
                            <select class="form-select js-example-basic-single status-select" data-placeholder="Select Status" name="status" id="status">
                                <option value=""></option>
                                <option value="1" {{ (!empty($slider->status) && $slider->status == 1) ? 'selected' : '' }}>Active</option>
                                <option value="0" {{ (!empty($slider->status) && $slider->status == 0) ? 'selected' : '' }}>Inactive</option>
                            </select>
                        </div>
                    </div>

                   

                

                    <!-- Submit Buttons -->
                    <div class="hstack gap-2 justify-content-between">
                        <a href="{{ route('admin.homelogos') }}" class="btn btn-success">Back</a>
                        <button type="submit" class="btn btn-success" id="submitBtn">{{ (!empty($slider->id)) ? 'Update App Logo' : 'Create App Logo' }}</button>
                    </div>
                </form>

            </div>
        </div>
    </div>
</div>

@endsection
@section('script')
    <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/jquery.validate.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/additional-methods.min.js"></script>
    <script type="text/javascript" language="javascript">
        $(document).ready(function () {
            $("#sliderForm").validate({
                rules: {
                    name: {
                        required: true,
                        minlength: 3,
                        maxlength: 100, // Max length for name
                    },
                    status: {
                        required: true,
                    },
                    image: {
                        required: function () {
                            return !$("#id").val(); // Require image only for new sliders
                        },
                        extension: "jpg|jpeg|png|gif", // Allowed file extensions
                    }
                    
                },
                messages: {
                    name: {
                        required: "Please enter the slider name.",
                        minlength: "Work Process title must be at least 3 characters.",
                        maxlength: "Work Process title cannot exceed 100 characters.",
                    },
                    status: {
                        required: "Please select the status.",
                    },
                    image: {
                        required: "Please upload  image.",
                        extension: "Only JPG, JPEG, PNG, and GIF files are allowed.",
                    }
                },
                onkeyup: function (element) {
                    $(element).valid(); // Real-time validation on keyup
                },
                onfocusout: function (element) {
                    $(element).valid(); // Validate when focus is lost
                },
                errorPlacement: function (error, element) {
                    if (element.is("select")) {
                        error.insertAfter(element.next('.select2'));
                    } else if (element.attr("name").includes("buttons")) {
                        // Place errors for dynamic button fields correctly
                        element.closest(".row").find(".col-lg-5").last().after(error);
                    } else {
                        error.insertAfter(element);
                    }
                },
                submitHandler: function (form) {
                    let formData = new FormData(form);

                    // AJAX submission
                    $.ajax({
                        url: form.action,
                        type: "POST",
                        data: formData,
                        processData: false,
                        contentType: false,
                        headers: {
                            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
                        },
                        success: function (response) {
                            // Show success message with Swal
                           
                            Swal.fire({
                                iconHtml: `<img src="{{ asset('assets/images/success-circle.svg') }}" class="img-fluid">`,
                               // title: "Success!",
                                text: response.message,
                                confirmButtonText: "OK",
                                customClass: {
                                    confirmButton: 'custom-ok-button-class w-sm' // Add your custom class here
                                }
                            }).then(() => {
                                window.location.href = "{{ route('admin.homelogos') }}"; // Redirect to company list
                            });
                        },
                        error: function (xhr) {
                            if (xhr.status === 422) {
                                let errors = xhr.responseJSON.errors;

                                // Display validation errors from the server
                                $.each(errors, function (key, value) {
                                    let field = $(`[name="${key}"]`);
                                    field.addClass("error"); // Add error class to the field
                                    field.after(`<label class="error">${value[0]}</label>`); // Add error message
                                });
                            } else {
                                Swal.fire({
                                    text: "Something went wrong. Please try later",
                                    iconHtml: `<img src="{{ asset('assets/images/error-circle.svg') }}" class="img-fluid">`,
                                    confirmButtonText: "OK", // Optional: Change the text of the button
                                    customClass: {
                                        confirmButton: 'custom-ok-button-class w-sm' // Add your custom class here
                                    }
                                });
                            }
                        }
                    });

                    return false; // Prevent default form submission
                },
                invalidHandler: function (event, validator) {
                    var firstInvalidField = $(validator.errorList[0].element);

                    $('html, body').animate({
                        scrollTop: firstInvalidField.offset().top - 100
                    }, 500);
                }
            });

        });
    </script>

    <script>
$(document).ready(function () {
    // Dynamic Button Fields
    let buttonCount = $("#dynamic-buttons .dynamic-button-row").length || 1;
    

    // Add button
    $(document).on("click", ".add-button", function () {
        const newRow = `
            <div class="row mb-2 dynamic-button-row">
                <div class="col-lg-5">
                    <input type="text" name="buttons[${buttonCount}][text]" class="form-control" placeholder="Enter Button Text">
                </div>
                <div class="col-lg-5">
                    <input type="url" name="buttons[${buttonCount}][link]" class="form-control" placeholder="Enter Button Link">
                </div>
                <div class="col-lg-2">
                    <button type="button" class="btn btn-danger remove-button">Remove</button>
                </div>
            </div>
        `;
        $("#dynamic-buttons").append(newRow);
        buttonCount++;
    });

    // Remove button
    $(document).on("click", ".remove-button", function () {
        $(this).closest(".dynamic-button-row").remove();
    });

    // // Image Preview
    // $("#image").on("change", function () {
    //     console.log(this.files);
    //     const [file] = this.files;
    //     if (file) {
    //         $("#imagePreview").attr("src", URL.createObjectURL(file)).show();
    //         $('#submitBtn').prop('disabled', false);
    //         $('#editimage').hide();
    //     }
    // });

    $('.icon-image-field').change(function() {
                var file = this.files[0];
                var fileType = file.type;
                var validImageTypes = ['image/png', 'image/jpeg', 'image/png'];

                if (validImageTypes.includes(fileType)) {
                    var reader = new FileReader();

                    reader.onload = function(event) {
                        $('.icon-image-preview').attr('src',event.target.result);
                    }

                    reader.readAsDataURL(file);
                }
            });
            $(document).on('change', '#image_field', function () {
                    $('#submitBtn').prop('disabled', false);
                });
});

</script>
    
@endsection
