@extends('backend.layouts.app')
@section('content')
<style>
.input-group-append {
    height: 37px;  /* Ensure the height matches the input field */
    display: flex;
    align-items: center;  /* Align the icon vertically */
}
</style>
    <div class="row page-titles">
        <div class="col-md-5 align-self-center">
            <h4 class="text-themecolor">Edit Salesman</h4>
        </div>
        <div class="col-md-7 align-self-center text-right">
            <div class="d-flex justify-content-end align-items-center">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
                    <li class="breadcrumb-item "><a href="{{ route('subadmin') }}">Salesman</a></li>
                    <li class="breadcrumb-item active">Edit Salesman</li>
                </ol>
            </div>
        </div>
    </div>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <!-- general form elements -->
                <div class="card card-primary">
                    <form id="adminForm" method="POST" action="{{ route('subadmin.update', $saleMan->id) }}"
                        enctype="multipart/form-data">
                        @csrf
                        @method('PUT') <!-- Add this for update request -->
                        <div class="card-body">
                            <div class="row">
                                <div class="col-sm-6">
                                    <div class="form-group">
                                        <label for="name">Name<span style="color: red;font-size:18px;"><b>*</b></span></label>
                                        <input type="text" id="name" name="name" placeholder="Enter Name" class="form-control"
                                            value="{{ old('name', $saleMan->name) }}" required>
                                    </div>
                                </div>

                                <div class="col-sm-6">
                                    <div class="form-group">
                                        <label for="email">Email<span style="color: red;font-size:18px;"><b>*</b></span></label>
                                        <input type="email" id="email" name="email" placeholder="Enter Email" class="form-control"
                                            value="{{ old('email', $saleMan->email) }}" required>
                                    </div>
                                </div>

                                <div class="col-sm-6">
                                    <div class="form-group">
                                        <label for="mobile">Mobile Number<span style="color: red;font-size:18px;"><b>*</b></span></label>
                                        <input type="text" id="mobile"
                                            oninput="this.value = this.value.replace(/[^0-9]/g, '');" placeholder="Enter Mobile" name="mobile"
                                            class="form-control" value="{{ old('mobile', $saleMan->mobile) }}" required>
                                    </div>
                                </div>

                                <div class="col-sm-6">
                                    <div class="form-group">
                                        <label for="alternate_mobile">Alternate Mobile Number<span style="color: red;font-size:18px;"></span></label>
                                        <input type="text" id="alternate_mobile"
                                            oninput="this.value = this.value.replace(/[^0-9]/g, '');" name="alternate_mobile" placeholder="Enter Alternate Mobile Number"
                                            class="form-control" value="{{ old('alternate_mobile', $saleMan->alternate_mobile) }}">
                                    </div>
                                </div>

                                <div class="col-sm-6">
                                    <div class="form-group">
                                        <label for="password">Password</label>
                                        <div class="input-group">
                                            <input type="password" id="password" placeholder="Enter Password" name="password" class="form-control password-toggle">
                                            {{-- <div class="input-group-append">
                                                <span class="input-group-text toggle-password" style="cursor: pointer; display: flex; align-items: center;">
                                                    <i class="fa fa-eye-slash"></i>
                                                </span>
                                            </div> --}}
                                        </div>
                                        <small>Leave blank if you don't want to change the password</small>
                                        <div class="invalid-feedback"></div>
                                    </div>
                                </div>


                                <div class="col-sm-6">
                                    <div class="form-group">
                                        <label for="dob">DOB<span style="color: red;font-size:18px;"><b>*</b></span></label>
                                        <input type="date" id="dob" name="dob" class="form-control" value="{{ old('dob', $saleMan->dob) }}" max="{{ date('Y-m-d') }}" required>
                                    </div>
                                </div>

                                <div class="col-sm-6">
                                    <div class="form-group">
                                        <label for="address">Address<span style="color: red;font-size:18px;"><b>*</b></span></label>
                                        <input type="text" id="address" placeholder="Enter Address" name="address" class="form-control" value="{{ old('address', $saleMan->address) }}" required>
                                    </div>
                                </div>

                                <div class="col-sm-6">
                                    <div class="form-group">
                                        <label for="address_line_two">Address Line Two</label>
                                        <input type="text" id="address_line_two" placeholder="Address Line Two" name="address_line_two"
                                            class="form-control" value="{{ old('address_line_two', $saleMan->address_line_two) }}">
                                    </div>
                                </div>

                                <div class="col-sm-6">
                                    <div class="form-group">
                                        <label for="post_code">Post Code<span style="color: red;font-size:18px;"><b>*</b></span></label>
                                        <input type="text" id="post_code" placeholder="Enter Post Code" name="post_code" class="form-control" value="{{ old('post_code', $saleMan->post_code) }}">
                                    </div>
                                </div>

                                <div class="col-sm-6">
                                    <div class="form-group">
                                        <label for="role">Role<span style="color: red;font-size:18px;"><b>*</b></span></label>
                                        <select id="role" name="role_id" class="form-control" required>
                                            <option value="">Select Role</option>
                                            @foreach ($roles as $role)
                                                <option value="{{ $role->id }}" {{ $saleMan->role_id == $role->id ? 'selected' : '' }}>
                                                    {{ $role->name }}
                                                </option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>

                                <div class="col-sm-6">
                                    <div class="form-group">
                                        <label for="profile_image">Profile Image</label>
                                        <input type="file" name="profile_image" id="profile_image" class="form-control" onchange="previewImage(event)">
                                        @error('profile_image')
                                            <p style="color:red;">{{ $message }}</p>
                                        @enderror
                                    </div>
                                    @if($saleMan->profile_image)
                                    <div class="form-group">
                                        <a target="_blank" href="{{ asset('/backend/images/profile/' . $saleMan->profile_image) }}">
                                        <img id="image-preview" src="{{ asset('/backend/images/profile/' . $saleMan->profile_image) }}" alt="Image Preview" style="display: block; width: 200px; height: 200px;">
                                        </a>
                                    </div>
                                    @endif
                                </div>
                            </div>


                                <div id="comment_box">
                                    <div class="col-sm-12">
                                        <div class="form-group">
                                            <label class="comment-label"><b>Comments</b></label>
                                        </div>
                                    </div>
                                    {{-- @dd(count($comments)) --}}
                                    @if(count($comments) > 0)
                                        @foreach ($comments as $key => $comment)
                                            <div class="row comment-row">
                                                <div class="col-sm-6">
                                                    <div class="form-group">
                                                        <input type="text" name="comment[]" value="{{$comment->comment}}" class="form-control"
                                                            placeholder="Enter Comment" value="{{ old('comment[]') }}">
                                                    </div>
                                                </div>
                                            </div>
                                        @endforeach
                                    @else
                                    <div class="row comment-row">
                                        <div class="col-sm-6">
                                            <div class="form-group">
                                                <input type="text" name="comment[]" class="form-control"
                                                    placeholder="Enter Comment" value="{{ old('comment[]') }}">
                                            </div>
                                        </div>
                                    </div>
                                    @endif
                                </div>

                                    <div class="col-sm-12 d-flex justify-content-end">
                                        <a href="#!" for="director_post_code" style="font-size: 15px;"
                                            id="add_more_comment"><b>Add More +</b></a>
                                    </div>


                                    <div class="col-sm-12">
                                        <div class="form-group">
                                            <label for="role">Additional Information</label>
                                                <textarea name="additional_information" placeholder="Additional Information" class="form-control">{{$saleMan->additional_information?? ""}}</textarea>
                                        </div>
                                    </div>

                                <div class="col-sm-12">
                                    <div class="form-group">
                                        <div class="custom-control custom-checkbox mr-sm-2 m-b-15">
                                            <input type="checkbox" class="custom-control-input" name="status"
                                                id="checkbox0" value="1" {{ $saleMan->status == 1 ? 'checked' : '' }}>
                                            <label class="custom-control-label" for="checkbox0">Is Active</label>
                                        </div>
                                    </div>
                                </div>

                            </div>
                        </div>

                        <div class="card-body">
                            <button type="submit" id="submitButton" class="btn btn-primary">Submit</button>
                            <a href="{{ route('subadmin') }}" class="btn btn-secondary">Back</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        function previewImage(event) {
            var input = event.target;
            var reader = new FileReader();
            reader.onload = function() {
                var dataURL = reader.result;
                var output = document.getElementById('image-preview');
                output.src = dataURL;
                output.style.display = 'block';
            };
            reader.readAsDataURL(input.files[0]);
        }


        document.addEventListener('DOMContentLoaded', function() {

$("#add_more_comment").click(function() {


    var newRow = $(".comment-row:first").clone(); //first row clone
    newRow.find("input").val(""); // clear all input fields
    // newRow.find(".director-label").html("<b>Director Details " + count + "</b>");

    newRow.append(
        '<div class="col-sm-1 d-flex justify-content-center align-items-center"><a href="#!" class="remove-comment-btn">❌</a></div>'
    )


    $("#comment_box").append(newRow); // add new row
});

$(document).on("click", ".remove-comment-btn", function() {
    if ($(".comment-row").length > 1) {
        $(this).closest(".comment-row").remove();
    } else {
        alert("At least one row is required!");
    }
});

const form = document.getElementById('adminForm');
const submitButton = document.getElementById('submitButton');
const tabInputs = document.querySelectorAll('.tab-content input');

// Track if there were changes made
let isInputChanged = false;

// Listen for input changes to set the flag
tabInputs.forEach(input => {
    input.addEventListener('input', function() {
        isInputChanged = true;
    });
});

$(document).ready(function() {
    // Custom regex validation method
    $.validator.addMethod("regex", function(value, element, regexp) {
        var re = new RegExp(regexp);
        return this.optional(element) || re.test(value);
    }, "Please check your input.");

    // Custom decimal validation method
    $.validator.addMethod("decimal", function(value, element) {
        return this.optional(element) || /^-?\d+(\.\d+)?$/.test(value);
    }, "Please enter a valid decimal number.");


    $.validator.addMethod("validateFile", function(value, element) {
    // Allowed file extensions for images
                    var fileExtension = ['jpg', 'jpeg', 'png'];

                    // Check if a file is selected
                    if (element.files && element.files.length > 0) {
                        // Extract the file extension from the selected file
                        var file = element.files[0];
                        var extension = file.name.split('.').pop().toLowerCase(); // Get the file extension

                        // Check if the extension is in the allowed list
                        return ($.inArray(extension, fileExtension) != -1);
                    }
                    return true; // If no file is selected, allow it (optional)
                }, "Please select a valid image file (JPG, JPEG, or PNG are allowed)");


    $.validator.addMethod("strongPassword", function(value, element) {
            return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/
                .test(value);
        },
        "Password must contain at least one uppercase letter, one lowercase letter, one numeric digit, one special character, and be at least 8 characters long."
        );

    // Custom range validation method
    $.validator.addMethod("range", function(value, element, range) {
        var val = parseFloat(value);
        return this.optional(element) || (val >= range[0] && val <= range[1]);
    }, "Please enter a value between {0} and {1}.");

    $("#adminForm").validate({
        rules: {
            name: {
                required: true,
                minlength: 3,
                maxlength: 50,
                noOnlySpaces: true
            },
            email: {
                required: true,
                noOnlySpaces: true,
                validEmail: true,
                email: true,
                remote: {
    url: "{{ route('subadmin.checkEmail') }}", // Make sure this route is correct
    type: "get",
    data: {
        email: function() {
            return $("#email").val(); // Get the email value from the input
        },
        id: function() {
            return '{{$saleMan->id}}'; // Get the admin ID (ensure it's passed as a hidden field)
        }
    }
}
            },
            mobile: {
                required: true,
                digits: true,
                noOnlySpaces: true,
                minlength: 11,
                maxlength: 11
            },
            alternate_mobile: {
                digits: true,
                // noOnlySpaces: true,
                minlength: 11,
                maxlength: 11
            },
            dob: {
                required: true,
                date: true
            },
            address: {
                required: true,
                minlength: 5,
                maxlength: 150,
            },
            post_code: {
                required: true,
                minlength: 6,
                maxlength: 8,
            },
            profile_image: {
                validateFile: true
            },
            password: {
                noOnlySpaces:function(element) {
                    return $(element).val() !== ""; // Apply validation only if password is not empty
                },
                strongPassword:function(element) {
                    return $(element).val() !== ""; // Apply validation only if password is not empty
                },

            },
            // profile_image: {
            //     url: true
            // },
            role_id: {
                required: true
            },
            
            additional_information:{
                maxlength: 500,
            },
            // status: {
            //     required: true
            // }
        },
        messages: {
            email: {
                remote: "This email is already taken."
            },
            mobile: {
                required: "Mobile number is required.",
                noOnlySpaces: "Mobile number cannot be empty or consist only of spaces.",
                digits: "Please enter a valid mobile number (digits only).",
                minlength: "Mobile number must be at least 11 digits long.",
                maxlength: "Mobile number cannot exceed 11 digits."
            },
            alternate_mobile: {
                // noOnlySpaces: "Alternate Mobile number cannot be empty or consist only of spaces.",
                digits: "Please enter a valid Alternate mobile number (digits only).",
                minlength: "Alternate Mobile number must be at least 11 digits long.",
                maxlength: "Alternate Mobile number cannot exceed 11 digits."
            },
            address: {
                required: "Please enter your address",
                minlength: "Address must be at least 5 characters long"
            },
        },
        errorClass: "error",

        highlight: function(element) {
            $(element).addClass('is-invalid').removeClass('is-valid');
        },
        unhighlight: function(element) {
            $(element).removeClass('is-invalid');
            // .addClass('is-valid');
        },
        submitHandler: function(form) {
            // Validate all comment fields before submitting
            var isValid = true;
            $('input[name="comment[]"]').each(function() {
                var value = $(this).val().trim();
                var $field = $(this);
                
                // Remove previous error messages
                $field.siblings('.error').remove();
                $field.removeClass('is-invalid');
                
                // Check if field is empty
                // if (value === '') {
                //     $field.addClass('is-invalid');
                //     $field.after('<div class="error">Comment is required.</div>');
                //     isValid = false;
                // }
                // // Check if field has only spaces
                // else if (value === '') {
                //     $field.addClass('is-invalid');
                //     $field.after('<div class="error">Comment cannot be empty or consist only of spaces.</div>');
                //     isValid = false;
                // }
                // // Check max length
                // else 
                if (value.length > 75) {
                    $field.addClass('is-invalid');
                    $field.after('<div class="error">Comment cannot exceed 75 characters.</div>');
                    isValid = false;
                }
            });
            
            if (!isValid) {
                return false;
            }
            
            // Disable the submit button to prevent multiple submissions
            $(form).find('button[type="submit"]').attr("disabled", true);

            // Submit the form
            form.submit();
        }
    });


    $('.toggle-password').click(function() {
    var passwordInput = $(this).closest('.input-group').find('.password-toggle'); // Find the password input
    var passwordIcon = $(this).find('i'); // Find the icon inside the span

    // Toggle password visibility
    if (passwordInput.attr('type') === 'password') {
        passwordInput.attr('type', 'text');
        passwordIcon.removeClass('fa-eye-slash').addClass('fa-eye');
    } else {
        passwordInput.attr('type', 'password');
        passwordIcon.removeClass('fa-eye').addClass('fa-eye-slash');
    }
});
});

});
    </script>
@stop
