@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 Badge</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);">Badge</a></li>
                    <li class="breadcrumb-item active">{{ (!empty($badge->id)) ? 'Update Badge' : 'Create Badge'  }}</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($badge->id) ? 'edit-form' : '' }}" autocomplete="off" name="cityForm" id="cityForm" method="post" novalidate enctype="multipart/form-data" action="{{ route('admin.badges.store') }}">
                <input type="hidden" name="id" id="id" value="{{ (!empty($badge->id)) ? $badge->id : '' }}" />
                    <div class="row">
                        <div class="col-lg-4 mb-3">
                            <label for="customername-field" class="form-label">Badge Name</label>
                            <input type="text" id="name" name="name" class="form-control" placeholder="Enter Badge Name" required value="{{ (!empty($badge->name)) ? $badge->name : '' }}" />
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="customername-field" class="form-label">Badge Name (Arabic)</label>
                            <input type="text" id="name_ar" name="name_ar" dir="rtl" class="form-control" placeholder="Enter Badge Name" required value="{{ (!empty($badge->name_ar)) ? $badge->name_ar : '' }}" />
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="customername-field" class="form-label">Type</label> 
                            <select class="form-select js-example-basic-single status-select"  id="type" name="type">
                                <option value="upgrade" {{ (!empty($badge->id) && $badge->type == "upgrade") ? 'selected' : '' }}>Upgrade</option>
                                <option value="verification" {{ (!empty($badge->id) && $badge->type == "verification") ? 'selected' : '' }}>Verification</option>
                            </select>
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="customername-field" class="form-label">Status</label> 
                            <select class="form-select js-example-basic-single status-select"  id="status" name="status">
                                <option value=""></option>
                                <option value="1" {{ (!empty($badge->id) && $badge->status == 1) ? 'selected' : '' }}>Active</option>
                                <option value="0" {{ (!empty($badge->id) && $badge->status == 0) ? 'selected' : '' }}>Inactive</option>
                            </select>
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="description" class="form-label">Description</label>
                            <textarea class="form-control" id="description" placeholder="Enter Description" rows="3" name="description">{{ (!empty($badge->description)) ? $badge->description : '' }}</textarea>
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="description" class="form-label">Description (Arabic)</label>
                            <textarea class="form-control" id="description_ar" placeholder="Enter Description" rows="3" name="description_ar">{{ (!empty($badge->description_ar)) ? $badge->description_ar : '' }}</textarea>
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="profile_image" class="form-label">Icon</label>
                            <input type="file" id="icon" name="icon"  class="form-control icon-image-field" accept="image/jpeg, image/jpg, image/png" />
                        </div>
                        <div class="col-lg-4 mb-3">
                            <img src="{{ !empty($badge->icon) ? $badge->icon : asset('assets/images/camera_placeholder.png') }}" class="img-fluid icon-image-preview" alt="profile image" style="height: 100px; width: 100px;">
                        </div>
                    </div>

                    <div class="hstack gap-2 justify-content-between"> 
                       <a href="{{ route('admin.badges') }}" class="btn btn-success">Back</a>
                        <button type="submit" class="btn btn-success" id="submitBtn">{{ (!empty($badge->id)) ? 'Update Badge' : 'Create Badge'  }}</button>
                        <!-- <button type="button" class="btn btn-success" id="edit-btn">Update</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 () {
        $('.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', '#icon', function () {
                $('#submitBtn').prop('disabled', false);
            });
       
        $("#cityForm").validate({
            rules: {
                name: {
                    required: true,
                    minlength: 3,
                },
                name_ar: {
                    required: true,
                    minlength: 3,
                },
                description: {
                    required: true,
                },
                description_ar: {
                    required: true,
                },
                status: {
                    required: true,
                },
            },
            messages: {
                name: {
                    required: "Please enter the Badge name.",
                    minlength: "Badge name must be at least 3 characters.",
                },
                status: {
                    required: "Please select the status.",
                },
            },
            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 {
                    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.badges') }}"; // 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>
    
@endsection
