@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 Booking Fields</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);">Service Booking Fields</a></li>
                    <li class="breadcrumb-item active">{{ (!empty($eventtype->id)) ? 'Create Booking Fields' : 'Create Booking Fields' }}</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">
            <!-- Hidden input to pass service attributes to the frontend -->
            <input type="hidden" id="service-attributes" value="{{ json_encode($categoryatributes) }}" />
            <input type="hidden" id="attribute-values" value="{{ json_encode($attributeValues) }}" />

            <form class="tablelist-form {{ !empty($category->id) ? 'edit-form' : '' }}" autocomplete="off" name="serviceForm" id="serviceForm" method="post" novalidate enctype="multipart/form-data" action="{{ route('admin.categories.formfieldsstore', ['id' => $category->id]) }}">
                @csrf
                <input type="hidden" name="id" id="id" value="{{ old('id', $category->id ?? '') }}" />

                <!-- Custom Booking Form Fields Section -->
                <div id="booking-fields-section" class="mb-4">
                    <label class="form-label fw-bold">Custom Booking Form Fields</label>
                    <div id="booking-fields-container">
                        <!-- Existing fields (if any) will be loaded here -->
                        @if (!empty($category_fields))
                            @foreach ($category_fields as $index => $field)
                                <div class="row mb-3 booking-field-row align-items-end" data-field-id="{{ $field['field_id'] ?? '' }}">
                                <input type="hidden" name="category_fields[{{ $index }}][field_id]" value="{{ $field['field_id'] ?? '' }}" />
                                <input type="hidden" name="category_fields[{{ $index }}][existing_field_id]" value="{{ $field['id'] ?? '' }}" />
                                    <div class="col-lg-3">
                                        <label class="form-label">Field Type</label>
                                        <select name="category_fields[{{ $index }}][type]" class="form-select field-type">
                                            <option value="text" {{ $field['type'] == 'text' ? 'selected' : '' }}>Text</option>
                                            <option value="textarea" {{ $field['type'] == 'textarea' ? 'selected' : '' }}>Textarea</option>
                                            <option value="numeric" {{ $field['type'] == 'numeric' ? 'selected' : '' }}>Numeric</option>
                                            <option value="radio" {{ $field['type'] == 'radio' ? 'selected' : '' }}>Radio</option>
                                            <option value="mobile" {{ $field['type'] == 'mobile' ? 'selected' : '' }}>Mobile</option>
                                            <option value="make" {{ $field['type'] == 'make' ? 'selected' : '' }}>Make</option>
                                            <option value="model" {{ $field['type'] == 'model' ? 'selected' : '' }}>Model</option>
                                            <option value="amenities" {{ $field['type'] == 'amenities' ? 'selected' : '' }}>Amenities</option>
                                            <option value="checkbox" {{ $field['type'] == 'checkbox' ? 'selected' : '' }}>Checkbox</option>
                                            <option value="select" {{ $field['type'] == 'select' ? 'selected' : '' }}>Dropdown</option>
                                            <option value="file" {{ $field['type'] == 'file' ? 'selected' : '' }}>File Upload</option>
                                            <option value="files" {{ $field['type'] == 'files' ? 'selected' : '' }}>Files Upload</option>
                                        </select>
                                    </div>
                                    <div class="col-lg-3">
                                        <label class="form-label">Field Label</label>
                                        <input type="text" name="category_fields[{{ $index }}][label]" class="form-control" placeholder="Field Label" value="{{ $field['label'] }}" required />
                                    </div>
                                    <div class="col-lg-3">
                                        <label class="form-label">Field Label (Arabic)</label>
                                        <input type="text" name="category_fields[{{ $index }}][label_ar]" dir="rtl" class="form-control" placeholder="Field Label (Arabic)" value="{{ $field['label_ar'] }}" required />
                                    </div>
                                    <div class="col-lg-3">
                                        <label class="form-label">Field Name</label>
                                        <input type="text" name="category_fields[{{ $index }}][name]" class="form-control" placeholder="Field Name" value="{{ $field['name'] }}" required />
                                    </div>
                                    <div class="col-lg-3">
                                        <label class="form-label">Field Name (Arabic)</label>
                                        <input type="text" name="category_fields[{{ $index }}][name_ar]" dir="rtl" class="form-control" placeholder="Field Name (Arabic)" value="{{ $field['name_ar'] }}" required />
                                    </div>
                                    <div class="col-lg-3 field-options-container" style="{{ !in_array($field['type'], ['radio', 'checkbox']) ? 'display: none;' : '' }}">
                                        <label class="form-label">Options (if applicable)</label>
                                        <input type="text" name="category_fields[{{ $index }}][options]" class="form-control field-options" placeholder="Comma-separated options" value="{{ isset($field['options']) ? $field['options'] : '' }}" />
                                    </div>
                                    <div class="col-lg-3 service-attributes-container" style="{{ $field['type'] != 'select' ? 'display: none;' : '' }}">
                                        <label class="form-label">Select Attribute</label>
                                        <select name="category_fields[{{ $index }}][attribute_id]" class="form-select service-attribute-select">
                                            <option value="">Select Attribute</option>
                                            @foreach ($categoryatributes as $attribute)
                                                <option value="{{ $attribute->id }}" {{ isset($field['attribute_id']) && $field['attribute_id'] == $attribute->id ? 'selected' : '' }}>{{ $attribute->name }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-lg-3 file-types-container" style="{{ $field['type'] != 'file' ? 'display: none;' : '' }}">
                                        <label class="form-label">Allowed File Types</label>
                                        <input type="text" name="category_fields[{{ $index }}][file_types]" class="form-control" placeholder="e.g., .pdf, .jpg" value="{{ $field['file_types'] ?? '' }}" />
                                    </div>
                                    <div class="col-lg-3">
                                        <label class="form-label">Required</label>
                                        <input type="checkbox" name="category_fields[{{ $index }}][required]" class="form-check-input" style="display: block;" value="1" @if($field['required'] == 1) checked @endif />
                                    </div>
                                    <div class="col-lg-3">
                                        <label class="form-label">Section</label>
                                        <select name="category_fields[{{ $index }}][section]" class="form-select">
                                            <option value="basic" {{ $field['section'] == 'basic' ? 'selected' : '' }}>Basic</option>
                                            <option value="advance" {{ $field['section'] == 'advance' ? 'selected' : '' }}>Advance</option>
                                        </select>
                                    </div>
                                    <button type="button" class="btn-remove-fields remove-booking-field" style="margin-top: 30px;">x</button>
                                    <input type="hidden" name="category_fields[{{$index}}][order]" class="section-order-field" value="{{$index}}">
                                </div>
                            @endforeach
                        @endif
                    </div>
                    <button type="button" id="add-booking-field" class="btn btn-primary mt-3">Add Field</button>
                </div>

                <!-- Field Conditions Section -->
                <div id="conditions-section" class="mt-4">
                    <h5 class="fw-bold">Field Conditions</h5>
                    <div id="conditions-container">
                    @foreach($conditions_fields as $index => $condition)
                        <div class="row mb-3 condition-row align-items-end">
                            <div class="col-lg-3">
                                <label class="form-label">Select Attribute</label>
                                <select name="conditions[{{ $index }}][attribute_id]" class="form-select attribute-selector">
                                    <option value="">Select Attribute</option>
                                    @foreach($categoryatributes as $attr)
                                        <option value="{{ $attr->id }}" {{ $attr->id == $condition->attribute_id ? 'selected' : '' }}>
                                            {{ $attr->name }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <input type="hidden" name="conditions[{{ $index }}][target_field_id]" value="{{ $condition->target_field_id}}">
                            <div class="col-lg-3">
                                <label class="form-label">Condition</label>
                                <select name="conditions[{{ $index }}][operator]" class="form-select">
                                    <option value="equals" {{ $condition->operator === 'equals' ? 'selected' : '' }}>Equals</option>
                                </select>
                            </div>
                            
                            <div class="col-lg-3">
                                <label class="form-label">Select Value</label>
                                <select name="conditions[{{ $index }}][value]" class="form-select value-selector">
                                    <option value="">Select Value</option>
                                    <!-- Assuming you have the attributeValues JavaScript object populated -->
                                    @foreach($attributeValues[$condition->attribute_id] as $value)
                                        <option value="{{ $value->id }}" {{ $value->id == $condition->value ? 'selected' : '' }}>
                                            {{ $value->name }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-lg-3">
                                <label class="form-label">Field to Show/Hide</label>
                                <select name="conditions[{{ $index }}][field_id]" class="form-select">
                                    <option value="">Select Field</option>
                                    @foreach($category_fields as $field)
                                        <option value="{{ $field->field_id }}" {{ $field->field_id == $condition->field_id ? 'selected' : '' }}>
                                            {{ $field->label }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-lg-1">
                                <button type="button" class="btn btn-danger remove-condition" style="margin-top: 30px;">Remove</button>
                            </div>
                        </div>
                    @endforeach
                    </div>
                    <button type="button" id="add-condition" class="btn btn-secondary mt-3">Add Condition</button>
                </div>

                <!-- Submit Buttons -->
                <div class="hstack gap-2 justify-content-between mt-4">
                    <a href="{{ route('admin.categories') }}" class="btn btn-success">Back</a>
                    <button type="submit" class="btn btn-success">{{ (!empty($category->id)) ? 'Add  Form Fields' : 'Add  Form Fields' }}</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 () {
            $.validator.addMethod("greaterThan", function (value, element, param) {
                return parseFloat(value) > parseFloat($(param).val());
            }, "Price (To) should be greater than Price (From).");
            // Initialize form validation
            $("#serviceForm").validate({
                rules: {
                    // Apply validation dynamically to all booking fields
                    "category_fields[][type]": { required: true },
                    "category_fields[][label]": { required: true },
                    "category_fields[][name]": { required: true },
                    "category_fields[][label_ar]": { required: true },
                    "category_fields[][name_ar]": { required: true },
                    // Additional dynamic validation for options (radio/checkbox)
                    "category_fields[][options]": {
                        required: function(element) {
                            // Make "options" required if the field type is "radio" or "checkbox"
                            var fieldType = $(element).closest('.booking-field-row').find('[name*="type"]').val();
                            return fieldType === 'radio' || fieldType === 'checkbox';
                        }
                    },

                    // Additional dynamic validation for file types (if the type is file)
                    "category_fields[][file_types]": {
                        required: function(element) {
                            var fieldType = $(element).closest('.booking-field-row').find('[name*="type"]').val();
                            return fieldType === 'file';
                        }
                    },

                    // Additional validation for select attributes (if the type is select)
                    "category_fields[][attribute_id]": {
                        required: function(element) {
                            var fieldType = $(element).closest('.booking-field-row').find('[name*="type"]').val();
                            return fieldType === 'select';
                        }
                    }
                },

                messages: {
                    "category_fields[][type]": { required: "Please select the field type." },
                    "category_fields[][label]": { required: "Please enter the field label." },
                    "category_fields[][name]": { required: "Please enter the field name." },
                    "category_fields[][options]": { required: "Please enter options for radio/checkbox fields." },
                    "category_fields[][file_types]": { required: "Please enter allowed file types." },
                    "category_fields[][attribute_id]": { required: "Please select an attribute for select fields." }
                },

                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);
                    if ($(".booking-field-row").length === 0) {
                        
                        Swal.fire({
                            text: "Please add at least one booking field.",
                            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 form submission
                    }

                    // 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) {
                            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.categories') }}";
                            });
                        },

                        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");
                                    field.after(`<label class="error">${value[0]}</label>`);
                                });
                            } 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
                },

                invalidHandler: function (event, validator) {
                    var firstInvalidField = $(validator.errorList[0].element);
                    $('html, body').animate({
                        scrollTop: firstInvalidField.offset().top - 100
                    }, 500);
                }
            });

        });

            </script>

<script>
    function previewImage(event, previewId) {
        const input = event.target;
        const preview = document.getElementById(previewId);

        if (input.files && input.files[0]) {
            const reader = new FileReader();
            reader.onload = function (e) {
                preview.src = e.target.result;
                preview.style.display = 'block';  // Show the preview image
            };
            reader.readAsDataURL(input.files[0]);
        } else {
            preview.src = '#';
            preview.style.display = 'none';  // Hide the preview image if no file is selected
        }
    }
</script>

<script>
$(document).ready(function () {
    const container = $('#booking-fields-container');
    const addButton = $('#add-booking-field');
    const conditionsContainer = $('#conditions-container');
    const categoryAttributes = JSON.parse($('#service-attributes').val());
    const attributeValues = JSON.parse($('#attribute-values').val());

    // Add a new field row
    addButton.on('click', function () {
        const index = container.find('.booking-field-row').length;
        const newFieldRow = `
            <div class="row mb-3 booking-field-row align-items-end" data-field-id="${index}">
                 <input type="hidden" name="category_fields[${index}][field_id]" value="${index}" />
                <div class="col-lg-3">
                    <label class="form-label">Field Type</label>
                    <select name="category_fields[${index}][type]" class="form-select field-type">
                        <option value="text">Text</option>
                        <option value="textarea">Textarea</option>
                        <option value="numeric">Numeric</option>
                        <option value="radio">Radio</option>
                        <option value="mobile">Mobile</option>
                        <option value="make">Make</option>
                        <option value="model">Model</option>
                        <option value="amenities">Amenities</option>
                        <option value="checkbox">Checkbox</option>
                        <option value="select">Dropdown</option>
                        <option value="file">File Upload</option>
                    </select>
                </div>
                <div class="col-lg-3">
                    <label class="form-label">Field Label</label>
                    <input type="text" name="category_fields[${index}][label]" class="form-control" placeholder="Field Label" required />
                </div>
                <div class="col-lg-3">
                    <label class="form-label">Field Label (Arabic)</label>
                    <input type="text" dir="rtl" name="category_fields[${index}][label_ar]" class="form-control" placeholder="Field Label" required />
                </div>
                <div class="col-lg-3">
                    <label class="form-label">Field Name</label>
                    <input type="text" name="category_fields[${index}][name]" class="form-control" placeholder="Field Name" required />
                </div>
                <div class="col-lg-3">
                    <label class="form-label">Field Name (Arabic)</label>
                    <input type="text" dir="rtl" name="category_fields[${index}][name_ar]" class="form-control" placeholder="Field Name" required />
                </div>
                <div class="col-lg-3 field-options-container" style="display: none;">
                    <label class="form-label">Options (if applicable)</label>
                    <input type="text" name="category_fields[${index}][options]" class="form-control field-options" placeholder="Comma-separated options" />
                </div>
                <div class="col-lg-3 service-attributes-container" style="display: none;">
                    <label class="form-label">Select Attribute</label>
                    <select name="category_fields[${index}][attribute_id]" class="form-select service-attribute-select">
                        <option value="">Select Attribute</option>
                        ${categoryAttributes.map(attr => `<option value="${attr.id}">${attr.name}</option>`).join('')}
                    </select>
                </div>
                <div class="col-lg-3 file-types-container" style="display: none;">
                    <label class="form-label">Allowed File Types</label>
                    <input type="text" name="category_fields[${index}][file_types]" class="form-control" placeholder="e.g., .pdf, .jpg" />
                </div>
                <div class="col-lg-3">
                    <label class="form-label">Required</label>
                    <input type="checkbox" name="category_fields[${index}][required]" class="form-check-input" style="display: block;" value="1" />
                </div>
                <div class="col-lg-3">
                    <label class="form-label">Section</label>
                    <select name="category_fields[${index}][section]" class="form-select">
                        <option value="basic">Basic</option>
                        <option value="advance">Advance</option>
                    </select>
                </div>
                <button type="button" class="btn-remove-fields remove-booking-field" style="margin-top: 30px;">x</button>
                <input type="hidden" name="category_fields[${index}][order]" class="section-order-field" value="${index}">
            </div>
        `;
        container.append(newFieldRow);
    });

    // Remove a field row
    container.on('click', '.remove-booking-field', function () {
        $(this).closest('.booking-field-row').remove();
    });
    container.on('change', '.field-type', function () {
        const row = $(this).closest('.booking-field-row');
        const fieldType = $(this).val();
        const optionsContainer = row.find('.field-options-container');
        const attributesContainer = row.find('.service-attributes-container');
        const fileTypesContainer = row.find('.file-types-container');

        if (fieldType === 'radio' || fieldType === 'checkbox') {
            optionsContainer.show();
            attributesContainer.hide();
            fileTypesContainer.hide();
        } else if (fieldType === 'select') {
            optionsContainer.hide();
            attributesContainer.show();
            fileTypesContainer.hide();
        } else if (fieldType === 'file') {
            optionsContainer.hide();
            attributesContainer.hide();
            fileTypesContainer.show();
        } else {
            optionsContainer.hide();
            attributesContainer.hide();
            fileTypesContainer.hide();
        }
    });

    // Add a new condition
    $('#add-condition').on('click', function () {
        const conditionIndex = conditionsContainer.find('.condition-row').length;
        const newConditionRow = `
            <div class="row mb-3 condition-row align-items-end">
                <div class="col-lg-3">
                    <label class="form-label">Select Attribute</label>
                    <select name="conditions[${conditionIndex}][attribute_id]" class="form-select attribute-selector">
                        <option value="">Select Attribute</option>
                        ${categoryAttributes.map(attr => `<option value="${attr.id}">${attr.name}</option>`).join('')}
                    </select>
                </div>
                <div class="col-lg-3">
                    <label class="form-label">Condition</label>
                    <select name="conditions[${conditionIndex}][operator]" class="form-select">
                        <option value="equals">Equals</option>
                    </select>
                </div>
                <div class="col-lg-3">
                    <label class="form-label">Select Value</label>
                    <select name="conditions[${conditionIndex}][value]" class="form-select value-selector">
                        <option value="">Select Value</option>
                    </select>
                </div>
                <div class="col-lg-3">
                    <label class="form-label">Field to Show/Hide</label>
                    <select name="conditions[${conditionIndex}][field_id]" class="form-select">
                        <option value="">Select Field</option>
                        ${container.find('.booking-field-row').map(function () {
                            const fieldName = $(this).find('input[name$="[name]"]').val();
                            const fieldId = $(this).data('field-id');
                            const fieldLabel = $(this).find('input[name$="[label]"]').val();
                            return `<option value="${fieldId}">${fieldName}</option>`;
                        }).get().join('')}
                    </select>
                </div>
                <!-- Hidden input for target_field_id -->
                <input type="hidden" name="conditions[${conditionIndex}][target_field_id]" class="target-field-id" value="">
                <div class="col-lg-1">
                    <button type="button" class="btn btn-danger remove-condition" style="margin-top: 30px;">Remove</button>
                </div>
            </div>
        `;
        conditionsContainer.append(newConditionRow);
    });



    // Remove a condition row
    conditionsContainer.on('click', '.remove-condition', function () {
        $(this).closest('.condition-row').remove();
    });

    // Handle changes in the attribute selector and populate values
    conditionsContainer.on('change', '.attribute-selector', function () {
        const attributeId = $(this).val();
        const valueSelector = $(this).closest('.condition-row').find('.value-selector');
        const targetFieldInput = $(this).closest('.condition-row').find('.target-field-id');  // Hidden input for target field ID
        
        valueSelector.empty(); // Clear current options

        if (attributeId) {
            // Get the name of the selected attribute from the categoryAttributes list
            const selectedAttribute = categoryAttributes.find(attr => attr.id == attributeId);
            const attributeName = selectedAttribute ? selectedAttribute.name : '';
            console.log("Selected Attribute Name: ", attributeName);

            // Now, find the field_id based on the attribute's name in the input fields
            let selectedFieldId = null;
            container.find('.booking-field-row').each(function() {
                const fieldLabel = $(this).find('input[name$="[label]"]').val(); // Get the label of the input field
                const fieldId = $(this).data('field-id'); // Get the field ID

                if (fieldLabel.trim().toLowerCase() === attributeName.trim().toLowerCase()) {  // Check if field label matches the attribute name
                    selectedFieldId = fieldId;
                    return false; // Exit the loop once the matching field is found
                }
            });

            //alert('Selected Field ID: ' + selectedFieldId); // Display the selected field ID

            // Now, update the hidden input with the selected field ID
            targetFieldInput.val(selectedFieldId);
            
            // Populate values for the selected attribute
            const values = attributeValues[attributeId] || [];
            
            valueSelector.append('<option value="">Select Value</option>');
            values.forEach(value => {
                valueSelector.append(`<option value="${value.id}">${value.name}</option>`);
            });
        }
    });

    //implement sortable items logic
    $("#booking-fields-container").sortable({
        update: function (event, ui) {
            $(this).find('.booking-field-row').each(function (index) {
                $(this).find('.section-order-field').val(index);
            });
        }
    });
    

});


</script>

    
@endsection
