<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use kartik\select2\Select2;
use kartik\rating\StarRating;
use app\components\Utilities;

$this->title = 'Form Render';

// Display intro alert to catch admin's eye about the node that the data will be submitted to
if(Yii::$app->user->can('Admin') && Yii::$app->controller->action->id == 'render-form'){
    $this->registerJs(Utilities::introAlertScriptForAdmin());
}

?>

<div dir="<?= $direction ?>" style="text-align: <?= ($direction == 'rtl' ? 'right' : 'left') ?>">

    <h1><?= Utilities::getFormName($form_id) ?></h1>

    <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

    <?php

        foreach($form_fields as $field){
            $field->field->form = $form;
            $is_disabled = (isset($read_only_fields) && in_array($field->name, $read_only_fields)) || $field->is_disabled;

            if($field instanceof \app\components\TextField){
                echo $field->field->textInput(['type' => $field->type, 'value' => $field->value, 'disabled' => $is_disabled])->label($field->label);
            }
            elseif($field instanceof \app\components\NumberField){
                echo $field->field->textInput(['type' => 'number', 'value' => $field->value, 'disabled' => $is_disabled, 'step' => ($field->type == 'decimal' ? '0.0001' : '1')])->label($field->label);
            }
            elseif($field instanceof \app\components\CheckboxGroupField){
                echo $field->field->checkboxList(ArrayHelper::map($field->items, 'value', 'label'), [
                    'value' => $field->value ?? $field->selected,
                    'separator' => $field->separator,
                    'template' => $field->template,
                    'itemOptions' => [
                        'disabled' => $is_disabled,
                    ]
                ])->label($field->label);
            }
            elseif($field instanceof \app\components\RadioGroupField){
                echo $field->field->radioList(ArrayHelper::map($field->items, 'value', 'label'), [
                    'value' => $field->value ?? $field->selected,
                    'separator' => $field->separator,
                    'template' => $field->template,
                    'itemOptions' => [
                        'disabled' => $is_disabled,
                    ]
                ])->label($field->label);
            }
            elseif($field instanceof \app\components\SelectField){
                if($field->multiple){
                    unset($field->items[0]);
                    echo $field->field->widget(Select2::class, [
                        'data' => ArrayHelper::map($field->items, 'value', 'label'),
                        'options' => [
                            'value' => $field->value ?? $field->selected,
                            'multiple' => true,
                            'disabled' => $is_disabled,
                        ]
                    ])->label($field->label);
                }
                else{
                    echo $field->field->dropDownList(ArrayHelper::map($field->items, 'value', 'label'), [
                        'value' => $field->value ?? $field->selected,
                        'disabled' => $is_disabled,
                    ])->label($field->label);
                }
            }
            elseif($field instanceof \app\components\TextareaField){
                echo $field->field->textArea(['style' => 'resize: none;', 'rows' => 5, 'value' => $field->value, 'disabled' => $is_disabled])->label($field->label);
            }
            elseif($field instanceof \app\components\StarRatingField){
                echo $field->field->widget(StarRating::class, [
                    'options' => [
                        'value' => $field->value,
                    ],
                    'pluginOptions' => [
                        'step' => 0.1,
                        'showClear' => false,
                        'showCaption' => false,
                        'displayOnly' => $is_disabled
                    ]
                ])->label($field->label);
            }
            elseif($field instanceof \app\components\LookupField){
                echo $field->field->widget(Select2::class, [
                    'options' => [
                        'value' => $field->value,
                        'placeholder' => 'Select ' . $field->label,
                        'disabled' => $is_disabled
                    ],
                    'pluginOptions' => $field->plugin_options,
                ])->label($field->label);

                // In case of adding child record, lookup namd & value will be passed to render function as parameters in URL,
                // and the lookup will be disabled, so we add a hidden input to hold lookup value
                if(isset($_GET['lookup_name']) && $_GET['lookup_name'] == $field->name && isset($_GET['lookup_value']) && $is_disabled){
                    echo Html::hiddenInput('DynamicModel[' . $field->name . ']', $_GET['lookup_value']);
                }
            }
        }

        foreach($other_fields as $other_field){
            if($other_field['type'] == 'calculated'){
                echo Html::hiddenInput('DynamicModel[' . $other_field['name'] . ']');
            }
            elseif($other_field['type'] == 'header'){
                $subtype = $other_field['subtype'];
                echo '<' . $subtype . '>' . $other_field['label'] . '</' . $subtype . '>';
            }
            elseif($other_field['type'] == 'paragraph'){
                echo '<p>' . $other_field['label'] . '</p>';
            }
            elseif($other_field['type'] == 'logo'){
                echo '<div style="text-align: ' . $other_field['alignment'] . '">';
                echo Html::img($other_field['path'], 
                    ['style' => 'width: 50%; height: 200px;', 'class' => 'img-thumbnail']);
                echo '</div>';
            }
            elseif($other_field['type'] == 'matrix' && ! $other_field['deactivate']){
                echo $this->render('_render-matrix-field', [
                    'field' => $other_field,
                    'direction' => $direction,
                    'matrices_results' => $matrices_results ?? null,
                    'read_only_fields' => $read_only_fields ?? null,
                ]);
            }
        }
    ?>

    <?php if(Yii::$app->controller->action->id == 'complete-record'): ?>
        <div class="alert alert-info">
            <p><span class="glyphicon glyphicon-info-sign"></span> <?= "By clicking on 'Save & Complete' button, the record will be marked as completed and will not appear anymore in 'Uncompleted Data' page." ?></p>
            <?= "If you want to back again to this record and complete filling-out the fields, you must click on 'Save' button." ?>
        </div>
        <?= Html::submitButton('Save & Complete', ['class' => 'btn btn-success btn-expanded', 'name' => 'save-and-complete']) ?>
        <?= Html::submitButton('Save', ['class' => 'btn btn-purple btn-expanded', 'name' => 'save']) ?>
    <?php else: ?>
        <?= Html::submitButton('Save', ['class' => 'btn btn-success btn-expanded', 'name' => 'save']) ?>
        <?= Html::submitButton('Save & New', ['class' => 'btn btn-purple btn-expanded', 'name' => 'save-and-new']) ?>
    <?php endif; ?>

    <?php ActiveForm::end() ?>
</div>

<script>
    var listValues   = <?= $list_values ?? 0 ?>;
    var showIfFields = <?= $show_if_fields ?? 0 ?>;
    if(listValues || showIfFields){
        $(document).ready(function(){
            for(list in listValues){
                var options = '<option value="">Select a value</option>';
                for(item in listValues[list]['items']){
                    options+= '<option value="' + item + '">' + listValues[list]['items'][item] + '</option>';
                }

                $('select[name="DynamicModel[' + list + ']"').empty();
                $('select[name="DynamicModel[' + list + ']"').append(options);
                $('select[name="DynamicModel[' + list + ']"').val(listValues[list]['selected_value']);
            }

            for(var i = 0; i < showIfFields.length; i++){
                if(showIfFields[i]['related_field_type'] == 'select'){
                    var value = $('#dynamicmodel-' + showIfFields[i]['related_field_name']).val();
                    if(value == showIfFields[i]['related_field_value']){
                        $('#dynamicmodel-' + showIfFields[i]['field_name']).closest('div').show();
                    }
                }
                else if(showIfFields[i]['related_field_type'] == 'radio_group'){
                    var value = $('input[name="DynamicModel[' + showIfFields[i]['related_field_name'] + ']"]:checked').val();
                    if(value == showIfFields[i]['related_field_value']){
                        $('#dynamicmodel-' + showIfFields[i]['field_name']).closest('div').show();
                    }
                }
                else if(showIfFields[i]['related_field_type'] == 'checkbox_group'){
                    var values = $('input[name="DynamicModel[' + showIfFields[i]['related_field_name'] + '][]"]:checked');
                    if(values.length){
                        for(var j = 0; j < values.length; j++){
                            if($(values[j]).val() == showIfFields[i]['related_field_value']){
                                $('#dynamicmodel-' + showIfFields[i]['field_name']).closest('div').show();
                            }
                        }
                    }
                }
            }
        });
    }
</script>