@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">{{ !empty($user->id) ? 'Edit' : 'Create' }} User</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);">Users</a></li>
                    <li class="breadcrumb-item active"> {{ !empty($user->id) ? 'Edit' : 'Create' }} Female</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($user->id) ? 'edit-form' : '' }}" autocomplete="off" action="{{ route('admin.users.store') }}" method="post" enctype="multipart/form-data" novalidate name="userForm" id="userForm">
                    @csrf
                    <input hidden id="id" name="id" value="{{ !empty($user->id) ? $user->id : '' }}">
                    <div class="row">
                        <div class="mb-3 col-lg-4">
                            <label for="customername-field" class="form-label">Full Name</label>
                            <input type="text" id="name" name="name" value="{{ !empty($user->name) ? $user->name : '' }}" class="form-control" placeholder="Enter name" required />
                        </div>

                        <div class="mb-3 col-lg-4">
                            <label for="customername-field" class="form-label">Nick Name</label>
                            <input type="text" id="nick_name" name="nick_name" value="{{ !empty($user->nick_name) ? $user->nick_name : '' }}" class="form-control" placeholder="Enter name" required />
                        </div>

                        <div class="mb-3 col-lg-4">
                            <label for="orderId" class="form-label w-100">Phone number</label>
                            <div class="row">
                                <div class="col-4">
                                    <select class="form-select  js-example-basic-single" data-placeholder="Select Dial Code" name="dial_code" id="dial_code">
                                        <option></option>
                                        @foreach($countries as $country)
                                        <option value="{{$country->dial_code}}" {{ (!empty($user->dial_code) && $user->dial_code == $country->dial_code) ? 'selected' : '' }}>{{$country->dial_code}}</option>
                                        @endforeach
                                        
                                    </select>
                                </div>
                                <div class="col-8">
                                    <input type="number" id="phone" name="phone" value="{{ !empty($user->phone) ? $user->phone : '' }}" class="form-control w-100 number-only" placeholder="Enter Phone number" required />
                                </div>
                            </div>
                        </div>

                        <div class="mb-3 col-lg-4">
                            <label for="customername-field" class="form-label">Email</label>
                            <input type="text" id="email" name="email" value="{{ !empty($user->email) ? $user->email : '' }}" class="form-control" placeholder="Enter email" required />
                        </div>
                        <div class="mb-3 col-lg-4">
                            <label for="customername-field" class="form-label">DOB</label>
                            <input type="date" id="dob" name="dob" value="{{ !empty($user->dob) ? $user->dob : '' }}" class="form-control" placeholder="Select DOB" />
                        </div>
                        <input type="hidden" name="gender" value="Female" /> 
                        <div class="col-lg-4 mb-3">
                            <label for="customername-field" class="form-label">Nationality</label>
                            <select class="form-select js-example-basic-single country-select" data-placeholder="Select Country" name="country_id" id="country_id">
                                <option value="">Select Nationality</option>
                                @foreach($nationalities as $nationality)
                                <option value="{{$nationality->id}}" {{ (!empty($user->nationality_id) && $user->nationality_id == $nationality->id) ? 'selected' : '' }}>{{$nationality->name}}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="password" class="form-label">Password</label>
                            <input type="password" id="password" name="password"  class="form-control" placeholder="Enter Password" required />
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="password_confirmation" class="form-label">Confirm Password</label>
                            <input type="password" id="password_confirmation" name="password_confirmation"  class="form-control" placeholder="Enter Confirm Password" required />
                        </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" data-placeholder="Select Status" name="status" id="status">
                                <option value=""></option>
                                <option value="1" {{ (!empty($user->status) && $user->status == 1) ? 'selected' : '' }}>Active</option>
                                <option value="0" {{ (!empty($user->status) && $user->status == 0) ? 'selected' : '' }}>Inactive</option>
                            </select>
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="profile_image" class="form-label">Profile Image</label>
                            <input type="file" id="profile_image" name="profile_image"  class="form-control icon-image-field" accept="image/jpeg, image/jpg, image/png" />
                        </div>
                        <div class="col-lg-4 mb-3">
                            <img src="{{ !empty($user->profile_image_url) ? $user->profile_image_url : asset('assets/images/female-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.users.female') }}" class="btn btn-success">Back</a>
                        <button type="submit" class="btn btn-success" id="submitBtn">{{ (!empty($user->id)) ? 'Update User' : 'Create User' }}</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', '#profile_image', function () {
                $('#submitBtn').prop('disabled', false);
            });

            const dateInput = document.getElementById('dob');
            const today = new Date().toISOString().split('T')[0]; // Format as YYYY-MM-DD
            dateInput.setAttribute('max', today);


            $("#userForm").validate({
                rules: {
                    name: {
                        required: true,
                        minlength: 3,
                    },
                    nick_name: {
                        required: true,
                        minlength: 3,
                    },
                    phone: {
                        required: true,
                        minlength: 8,
                        maxlength: 15,
                    },
                    dial_code: {
                        required: true,
                    },  
                    email: {
                        required: true,
                        email: true,
                    },
                    password: {
                        required: $("#id").val()!=""?false:true,
                        minlength: 9,
                    },
                    password_confirmation: {
                        required: $("#id").val()!=""?false:true,
                        equalTo: "#password",
                    },
                    country_id: {
                        required: true, 
                    },
                    status: {
                        required: true,
                    },
                    profile_image: {
                        accept: "image/*",
                    },
                },
                messages: {
                    first_name: {
                        required: "Please enter the first name.",
                        minlength: "First name must be at least 3 characters.",
                    },
                    last_name: {
                        required: "Please enter the last name.",
                        minlength: "Last name must be at least 3 characters.",
                    },
                    phone: {
                        required: "Please enter a valid phone number.",
                        minlength: "Phone number must be at least 8 digits.",
                        maxlength: "Phone number cannot exceed 15 digits.",
                    },
                    dial_code: {
                        required: "Please enter the dial code.",
                    },
                    email: {
                        required: "Please enter the email address.",
                        email: "Please enter a valid email address.",
                    },
                    password: {
                        required: "Please enter the password.",
                        minlength: "Password must be at least 8 characters.",
                    },
                    password_confirmation: {
                        required: "Please confirm the password.",
                        equalTo: "Passwords do not match.",
                    },
                    country_id: {
                        required: "Please select the country.",
                    },
                    emirate_id: {
                        required: "Please select the emirate.",
                    },
                    city_id: {
                        required: "Please select the city.",
                    },
                    company_id: {
                        required: "Please select the company.",
                    },
                    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">`,
                                text: response.message,
                                confirmButtonText: "OK",
                                customClass: {
                                    confirmButton: 'custom-ok-button-class w-sm'
                                }
                            }).then(() => {
                                window.location.href = "{{ route('admin.users.female') }}"; // 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",
                                    customClass: {
                                        confirmButton: 'custom-ok-button-class w-sm'
                                    }
                                });
                            }
                        }
                    });

                    return false; // Prevent default form submission
                }
            });
        });
    </script>
    
@endsection
