<?php

use \yii\helpers\Html;
use \yii\helpers\ArrayHelper;

$is_required = isset($is_required) && $is_required;

echo '<div class="field-dynamicmodel-' . $field['name'] . '" style="display: ' . (isset($field['showIfLogicCheckbox']) && $field['showIfLogicCheckbox'] ? 'none' : 'block') . '">';
echo Html::label($field['label']);
$column_options = 'style="width: '. 95 / count($field['matrix_items']) . '%; text-align: ' . ($direction == 'rtl' ? 'right' : 'left') .'"';
echo '<table class="table table-striped table-bordered" id="matrix_' . $field['name'] . '" dir="' . $direction . '">';
echo '<thead style="background-color: #FFF;">';
foreach($field['matrix_items'] as $item){
    echo '<th ' . $column_options . '">' . ucfirst($item['label']) . '</th>';
}
echo '<th></th>';
echo '</thead>';

echo '<tr>';
foreach($field['matrix_items'] as $item){
    $field_name = $field['name'] . '[0][' . str_replace(' ', '_', str_replace('-', '_', $item['name'])) . ']';
    echo '<td style="vertical-align: middle;">'; 
    switch($item['type']){
        case 'text':
        case 'email':
        case 'url':
        case 'phone':
        case 'file':
        case 'date':
        case 'time': 
        case 'number': {
            echo Html::textInput($field_name, null, ['type' => $item['type'], 'class' => 'form-control', 'required' => $is_required]);
        }
        break;
        case 'decimal': {
            echo Html::textInput($field_name, null, ['type' => 'number', 'step' => '0.0001', 'class' => 'form-control', 'required' => $is_required]);
        }
        break;
        case 'radio-group': {
            echo Html::radioList($field_name, null, 
                ArrayHelper::map($item['options'], 'value', 'label'));
        }
        break;
        case 'checkbox-group': {
            echo Html::checkboxList($field_name, null, 
                ArrayHelper::map($item['options'], 'value', 'label'));
        }
        break;
        case 'select': {
            echo Html::dropdownList($field_name, null, 
                ArrayHelper::map($item['options'], 'value', 'label'), ['class' => 'form-control', 'required' => $is_required]
            );
        }
        break;
        case 'checkbox': {
            echo Html::checkbox($field_name, false, ['label' => $item['label']]);
        }
        break;
        case 'textarea': {
            echo Html::textarea($field_name, null, ['style' => 'resize: none;', 'rows' => 5, 'class' => 'form-control', 'required' => $is_required]);
        }
        break;
    }
    echo '</td>';
}
echo '<td style="vertical-align: middle;"></td>';
echo '</tr>';

echo '</table>';

echo '<div style="display: flex; justify-content: flex-end;">';
echo Html::button('Add new row', [
    'class' => 'btn btn-primary add-matrix-row-btn',
    'id' => 'matrix_' . $field['name'] . '_btn',
    (isset($field['maxRecordsCount']) ? ['data-max-count' => $field['maxRecordsCount']] : []),
]);
echo '</div>';
echo '</div>';

?>

<script>
    $('.add-matrix-row-btn').click(function(){
        var table_id = $(this).attr('id').replace('_btn', '');
        var current_rows = $('#' + table_id).find('tr');

        var maxRecordsCount = $(this).attr('data-max-count');
        if(typeof maxRecordsCount !== 'undefined' && current_rows.length - 1 == maxRecordsCount){
            return false;
        }

        var row = current_rows[1];
        var duplicated_row = $(row).clone();

        var columns = $(duplicated_row).find('td');
        var random_row_count = current_rows.length + Math.floor(Math.random() * 100);
        var row_exists = $('#' + table_id).find('input[name*="[' + random_row_count + ']"]');
        if(row_exists.length > 0){
            random_row_count = random_row_count * 10;
        }
        
        for(var i = 0; i < columns.length - 1; i++){
            var input = $(columns[i]).find('input');
            if(input.length > 0){
                var type = $(input).attr('type');
                if(type == 'radio' || type == 'checkbox'){
                    $(input).prop('checked', false);
                }
                else{
                    $(input).val('');
                }
                $(input).attr('name', $(input).attr('name').replace('[0]', '[' + random_row_count + ']'));
            }
            else{
                var select = $(columns[i]).find('select');
                if(select.length > 0){
                    $(select).val('');
                    $(select).attr('name', $(select).attr('name').replace('[0]', '[' + random_row_count + ']'));
                }
                else{
                    var textarea = $(columns[i]).find('textarea');
                    if(textarea.length > 0){
                        $(textarea).val('');
                        $(textarea).attr('name', $(textarea).attr('name').replace('[0]', '[' + random_row_count + ']'));
                    }
                }
            }
        }
        
        $(columns).last().append('<span style="color: #337AB7; cursor: pointer;" class="glyphicon glyphicon-trash" onClick="removeMatrixRow(this);"></span>');
        
        $('#' + table_id).append(duplicated_row);
    });

    function removeMatrixRow(e){
        $(e).closest('tr').remove();
    }

    var matricesResults = <?= $matrices_results ?? 0 ?>;
    if(matricesResults){
        for(matrix_name in matricesResults){
            var matrixFields = matricesResults[matrix_name];
            for(var i = 0; i < matrixFields.length; i++){
                var fieldsNames = Object.keys(matrixFields[i]);
                var fieldsValues = Object.values(matrixFields[i]);
                var row = [];
                if(i == 0){
                    // The first row already exists, no need to add it
                    row = $('#matrix_' + matrix_name).find('tbody').children()[0];
                }
                else{
                    $('#matrix_' + matrix_name + '_btn').trigger('click');
                    row = $('#matrix_' + matrix_name).find('tbody').children()[i];
                }
                
                for(var j = 0; j < fieldsNames.length; j++){
                    var input = $(row).find('[name*="' + fieldsNames[j] + '"]');
                    if(input.length){
                        var column = $(input).closest('td');
                        var inputField = $(column).find('input');
                        if(inputField.length){
                            var type = $(inputField).attr('type');
                            if(type == 'radio'){
                                var option = $(row).find('[name*="' + fieldsNames[j] + '"][value="' + fieldsValues[j] + '"]');
                                $(option).prop('checked', true);
                            }
                            else{
                                $(inputField).val(fieldsValues[j]);
                            }
                        }
                        else{
                            var selectField = $(column).find('select');
                            if(selectField.length){
                                $(selectField).val(fieldsValues[j]);
                            }
                            else{
                                var textAreaField = $(column).find('textarea');
                                $(textAreaField).val(fieldsValues[j]);
                            }
                        }
                    }
                }
            }
        }
    }

    // Handle show-if
    var showIfLogic = <?= json_encode($field['showIfLogicCheckbox']) ?? 0 ?>;
    if(showIfLogic){
        var matrixName       = <?= json_encode($field['name']) ?>;
        var showIfFieldName  = <?= isset($field['showIfFieldName'])  ? json_encode($field['showIfFieldName'])  : 0 ?>;
        var showIfFieldValue = <?= isset($field['showIfFieldValue']) ? json_encode($field['showIfFieldValue']) : 0 ?>;
        var showIfFieldType  = showIfFieldName.includes('select') ? 'select' : (showIfFieldName.includes('checkbox') ? 'checkbox' : 'radio');
        if(showIfFieldType == 'select' || showIfFieldType == 'radio'){
            $('[name="DynamicModel[' + showIfFieldName + ']"]').change(function(){
                var value = $('[name="DynamicModel[' + showIfFieldName + ']"]' + (showIfFieldType == 'radio' ? ':checked' : '')).val();
                if(value == showIfFieldValue){
                    $('div.field-dynamicmodel-' + matrixName).slideDown(250);
                }
                else{
                    $('div.field-dynamicmodel-' + matrixName).slideUp(250);
                }
            });

            // Trigger change event in order to display matrix if the related field has selected value
            $('[name="DynamicModel[' + showIfFieldName + ']"]').trigger('change');
        }
        else{
            $('[name="DynamicModel[' + showIfFieldName + '][]"]').change(function(){
                var values = $('[name="DynamicModel[' + showIfFieldName + '][]"]:checked');
                var valuesText = [];
                if(values){
                    for(var i = 0; i < values.length; i++){
                        valuesText.push($(values[i]).val());
                    }
                    if(valuesText.includes(showIfFieldValue)){
                        $('div.field-dynamicmodel-' + matrixName).slideDown(250);
                    }
                    else{
                        $('div.field-dynamicmodel-' + matrixName).slideUp(250);
                    }
                }
            });

            // Trigger change event in order to display matrix if the related field has selected value
            $('[name="DynamicModel[' + showIfFieldName + '][]"]').trigger('change');
        }
    }
</script>