'use strict';

/*
|--------------------------------------------------------------------------
| HR Biometric Platform Enterprise
|--------------------------------------------------------------------------
| Dynamic Form Builder V3
|--------------------------------------------------------------------------
*/

const Designer = {

    formId: window.formDesigner?.formId ?? 0,

    selectedField: null,

    choiceTypes: [
        'select',
        'radio',
        'checkbox'
    ],

    init() {

    this.cache();

    this.bindToolbox();

    this.bindEditModal();
    
    this.bindEditSection();
    
    this.bindDeleteSection();

    this.bindDeleteField();

    this.bindChoiceOptions();

    this.bindEditChoiceOptions();

    this.initSortable();

        console.log('Designer V3 Loaded');

    },

    cache() {

        this.toolbox = document.querySelectorAll('.toolbox-item');

        this.sections = document.querySelectorAll('.sortable-fields');

        this.canvas = document.getElementById('sortableSections');

    },

    showModal(id) {

        const modal = document.getElementById(id);

        if (!modal) {
            return;
        }

        bootstrap.Modal
            .getOrCreateInstance(modal)
            .show();

    },

    hidePanels(ids) {

        ids.forEach(function(id){

            document
                .getElementById(id)
                ?.classList.add('d-none');

        });

    }

};

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

    Designer.init();

});
Designer.bindToolbox = function () {

    this.toolbox.forEach((button) => {

        button.addEventListener('click', () => {

            const type = button.dataset.fieldType;

            document.getElementById('addFieldType').value = type;

            document.getElementById('addFieldTypeLabel').innerHTML =
                button.dataset.fieldTypeLabel;

            Designer.hidePanels([
                'numberSettings',
                'dateSettings',
                'timeSettings',
                'fileSettings',
                'addChoiceOptions'
            ]);

            switch (type) {

                case 'number':
                    document.getElementById('numberSettings')
                        ?.classList.remove('d-none');
                    break;

                case 'date':
                    document.getElementById('dateSettings')
                        ?.classList.remove('d-none');
                    break;

                case 'time':
                    document.getElementById('timeSettings')
                        ?.classList.remove('d-none');
                    break;

                case 'file':
                    document.getElementById('fileSettings')
                        ?.classList.remove('d-none');
                    break;

                case 'select':
                case 'radio':
                case 'checkbox':
                    document.getElementById('addChoiceOptions')
                        ?.classList.remove('d-none');
                    break;

            }

            Designer.showModal('addFieldModal');

        });

    });

};

Designer.bindEditModal = function () {

    document.addEventListener('click', function (e) {

        console.log('CLICK');

        const button = e.target.closest('.edit-field-btn');

        if (!button) {
            console.log('NOT EDIT BUTTON');
            return;
        }

        console.log('FOUND BUTTON');

        try {

            console.log('Populate...');
            Designer.populateEditModal(button);

            console.log('Show modal...');
            Designer.showModal('editFieldModal');

            console.log('DONE');

        } catch (err) {

            console.error(err);

        }

    });

};
Designer.bindDeleteSection = function () {

    document.addEventListener('submit', function (e) {

        console.log('SECTION DELETE EVENT');

        const form = e.target.closest('.delete-section-form');

        if (!form) {
            return;
        }

        console.log(form);

        e.preventDefault();

        if (confirm('Remove this section?')) {
            form.submit();
        }

    });

};
Designer.populateEditModal = function (button) {

    const fieldId = button.dataset.id || '';
    const fieldType = button.dataset.fieldType || '';

    document.getElementById('editFieldId').value = fieldId;
    document.getElementById('editFieldLabel').value = button.dataset.label || '';
    document.getElementById('editFieldPlaceholder').value = button.dataset.placeholder || '';
    document.getElementById('editFieldHelpText').value = button.dataset.helpText || '';
    document.getElementById('editFieldDefaultValue').value = button.dataset.defaultValue || '';
    document.getElementById('editFieldColumnWidth').value = button.dataset.columnWidth || '12';

    document.getElementById('editFieldRequired').checked =
        button.dataset.required === '1';

    let validation = {};

    try {

        validation = JSON.parse(
            button.dataset.validationRules || '{}'
        );

    } catch (e) {

        validation = {};

    }

    Designer.hidePanels([
        'editNumberSettings',
        'editDateSettings',
        'editTimeSettings',
        'editFileSettings',
        'editChoiceOptions'
    ]);

    Designer.populateValidation(fieldType, validation);

    Designer.populateChoiceOptions(fieldId, fieldType);

};

Designer.populateValidation = function (type, rules) {

    switch (type) {

        case 'number':

            document.getElementById('editNumberSettings')
                ?.classList.remove('d-none');

            document.getElementById('editNumberMin').value =
                rules.min ?? '';

            document.getElementById('editNumberMax').value =
                rules.max ?? '';

            document.getElementById('editNumberStep').value =
                rules.step ?? '';

            break;

        case 'date':

            document.getElementById('editDateSettings')
                ?.classList.remove('d-none');

            document.getElementById('editDateMin').value =
                rules.min_date ?? '';

            document.getElementById('editDateMax').value =
                rules.max_date ?? '';

            break;

        case 'time':

            document.getElementById('editTimeSettings')
                ?.classList.remove('d-none');

            document.getElementById('editTimeMin').value =
                rules.min_time ?? '';

            document.getElementById('editTimeMax').value =
                rules.max_time ?? '';

            break;

        case 'file':

            document.getElementById('editFileSettings')
                ?.classList.remove('d-none');

            document.getElementById('editMaxFileSize').value =
                rules.max_size ?? '';

            document.getElementById('editMultipleUpload').checked =
                rules.multiple === true;

            break;

    }

};
Designer.populateChoiceOptions = function (fieldId, type) {

    if (!Designer.choiceTypes.includes(type)) {
        return;
    }

    document.getElementById('editChoiceOptions')
        ?.classList.remove('d-none');

    const rows =
        document.getElementById('editOptionRows');

    rows.innerHTML = '';

    const options =
        window.dynamicFieldOptions?.[fieldId] || [];

    if (options.length === 0) {

        Designer.addEditOptionRow('');

        return;

    }

    options.forEach(function(option){

        Designer.addEditOptionRow(
            option.option_label
        );

    });

};
Designer.addEditOptionRow = function (value = '') {

    const container =
        document.getElementById('editOptionRows');

    if (!container) {
        return;
    }

    const row = document.createElement('div');

    row.className = 'input-group mb-2 option-row';

    row.innerHTML = `
        <span class="input-group-text"></span>

        <input
            type="text"
            name="options[]"
            class="form-control"
            value="${value}"
            placeholder="Option label">

        <button
            type="button"
            class="btn btn-outline-danger remove-option">

            <i class="bi bi-trash"></i>

        </button>
    `;

    container.appendChild(row);

    Designer.renumberOptions(container);

};
Designer.renumberOptions = function (container) {

    container
        .querySelectorAll('.option-row')
        .forEach(function(row,index){

            const badge =
                row.querySelector('.input-group-text');

            if(badge){

                badge.textContent = index + 1;

            }

        });

};
Designer.bindChoiceOptions = function () {

    const container =
        document.getElementById('optionRows');

    const addButton =
        document.getElementById('addOptionRow');

    if(!container || !addButton){
        return;
    }

    addButton.addEventListener('click',function(){

        const row=document.createElement('div');

        row.className='input-group mb-2 option-row';

        row.innerHTML=`
            <span class="input-group-text"></span>

            <input
                type="text"
                name="options[]"
                class="form-control"
                placeholder="Option label">

            <button
                type="button"
                class="btn btn-outline-danger remove-option">

                <i class="bi bi-trash"></i>

            </button>
        `;

        container.appendChild(row);

        Designer.renumberOptions(container);

    });

    container.addEventListener('click',function(e){

        const button=e.target.closest('.remove-option');

        if(!button){
            return;
        }

        if(container.querySelectorAll('.option-row').length<=1){
            return;
        }

        button.closest('.option-row').remove();

        Designer.renumberOptions(container);

    });

    Designer.renumberOptions(container);

};
Designer.bindEditChoiceOptions = function () {

    const container =
        document.getElementById('editOptionRows');

    const addButton =
        document.getElementById('editAddOptionRow');

    if(!container || !addButton){
        return;
    }

    addButton.addEventListener('click',function(){

        Designer.addEditOptionRow('');

    });

    container.addEventListener('click',function(e){

        const button=e.target.closest('.remove-option');

        if(!button){
            return;
        }

        if(container.querySelectorAll('.option-row').length<=1){
            return;
        }

        button.closest('.option-row').remove();

        Designer.renumberOptions(container);

    });

};
Designer.bindEditSection = function () {

    document.addEventListener('click', function (e) {

        const button = e.target.closest('.edit-section-btn');

        if (!button) {
            return;
        }

        document.getElementById('editSectionId').value =
            button.dataset.sectionId || '';

        document.getElementById('editSectionTitle').value =
            button.dataset.title || '';

        document.getElementById('editSectionDescription').value =
            button.dataset.description || '';

        Designer.showModal('editSectionModal');

    });

};
Designer.bindDeleteField = function () {

    document.addEventListener('submit', function (e) {

        console.log('DELETE EVENT');

        const form = e.target.closest('.delete-field-form');

        if (!form) {
            return;
        }

        console.log(form);

        e.preventDefault();

if (confirm('Remove this field?')) {
    form.submit();
}

    });

};
Designer.initSortable = function () {

    document
        .querySelectorAll('.sortable-fields')
        .forEach(function(container){

            new Sortable(container,{

                group:'dynamic-fields',

                animation:200,

                draggable:'.sortable-field',

                handle:'.field-card-toolbar',

                ghostClass:'sortable-ghost',

                chosenClass:'sortable-chosen',

                dragClass:'sortable-drag',

                onEnd:function(evt){



    console.log(evt);

    Designer.saveFieldOrder(evt);

}

            });

        });

};
const sectionContainer = document.getElementById('sortableSections');

if (sectionContainer) {

    new Sortable(sectionContainer, {

        animation: 200,

        draggable: '.sortable-section',

        handle: '.section-toolbar',

        onEnd: function (evt) {

            Designer.saveSectionOrder(evt);

        }

    });

}
Designer.saveFieldOrder = function (evt) {

    const sectionId = evt.to.dataset.sectionId;

    if (!sectionId) {
        return;
    }

    const formData = new FormData();

    evt.to.querySelectorAll('.sortable-field').forEach(function(field, index){

        formData.append('field_id[]', field.dataset.fieldId);
        formData.append('section_id[]', sectionId);
        formData.append('sort_order[]', index + 1);

    });
console.log('Sending request...');
    fetch('/public/dynamic-forms/fields/reorder', {

        method: 'POST',

        body: formData

    })
    .then(r => r.json())
    .then(console.log)
    .catch(console.error);

};
Designer.clearContainer=function(id){

    const el=document.getElementById(id);

    if(el){

        el.innerHTML='';

    }

};

Designer.resetValidationPanels=function(){

    Designer.hidePanels([

        'numberSettings',
        'dateSettings',
        'timeSettings',
        'fileSettings',
        'addChoiceOptions',

        'editNumberSettings',
        'editDateSettings',
        'editTimeSettings',
        'editFileSettings',
        'editChoiceOptions'

    ]);

};


