<?php

use yii\bootstrap4\{Modal, Tabs};
use yii\helpers\{Html, Url, ArrayHelper, Json};
use yii\widgets\ActiveForm;
use yii\db\Query;
use yii\web\JsExpression;

use kartik\select2\Select2;
use kartik\widgets\{DateTimePicker, DatePicker, DepDrop, FileInput};

use frontend\models\{Dtwps, Uploads};
use modules\custom\models\{Accounts, Contacts};

$users = \frontend\models\User::EmployeesU();

$modelname1 = $model->contact;
$modelname2 = $model->contact2;
$modelname3 = $model->contact3;
$modelname4 = $model->contact4;
$modelname5 = $model->contact5;

$this->registerJsFile('/js/moment.js', ['position' => \yii\web\View::POS_HEAD]);
$this->registerJsFile('/js/moment-duration-format.js', ['position' => \yii\web\View::POS_HEAD]);
$this->registerJsFile('/js/ActivitiesForm.js', ['position' => \yii\web\View::POS_END]);

?>
<style>
    #Attachments {
        width: 50%;
        height: auto;
    }
</style>

<script>
function handleJobTypeChange() {
    var jobType = $('#activities-type').val();
    var formData = $('#form').serialize();
    
    // Save form to preserve data
    $.ajax({
        type: 'POST',
        url: $('#form').attr('action'),
        data: formData,
        success: function(response) {
            // Reload the page to show the correct form variation
            location.reload();
        },
        error: function() {
            // If save fails, still reload to show correct form
            location.reload();
        }
    });
}
</script>

<div class="activities-form">
    <?php $form = ActiveForm::begin([
        'options' => [
            'id' => 'form',
            'enctype' => 'multipart/form-data',
        ]
    ]); ?>
    
    <div class="card mb-3">
        <div class="card-header">
            Job Details
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-12 col-md-2">
                    <?= $form->field($model, 'jobno', [
                        'template' => "{label}<div class='input-group'>{input}" . 
                            $form->field($model, 'visitno', [
                                'template' => '{input}',
                                'options' => ['tag' => false]
                            ])->textInput(['id' => 'visitno', 'tag' => false]) . 
                            "</div>{error}{hint}"
                    ])->textInput([
                        'onchange' => 'names()',
                        'id' => 'jobno'
                    ])->label('Job Number | Visit Number') ?>
                </div>
                
                <div class="col-12 col-md-2">
                    <?= $form->field($model, 'type')->dropdownlist($model->jobTypes(), [
                        'prompt' => 'Please Select...',
                        'onchange' => 'handleJobTypeChange()'
                    ])->label('Job Type') ?>
                </div>
                
                <div class="col-12 col-md-2">
                    <?= $form->field($model, 'postcode')->textInput([
                        'id' => 'postcode',
                        'onchange' => "getRoute($(this).val())"
                    ])->label('Post Code') ?>
                </div>
                
                <div class="col-12 col-md-3">
                    <?= $form->field($model, 'welder')->widget(Select2::class, [
                        'id' => 'welders',
                        'data' => $users,
                        'options' => [
                            'placeholder' => 'Select Operatives...',
                            'multiple' => true
                        ],
                        'pluginEvents' => [
                            "select2:select" => "function(data) {
                                welderadd(data.params.data.id, '$model->id');
                            }",
                            "select2:unselect" => "function(data) {
                                console.log(data);
                                welderdel(data.params.data.id);
                            }"
                        ]
                    ])->label('Operatives') ?>
                </div>
                
                <div class="col-12 col-md-3">
                    <?= $form->field($model, 'relatedid', [
                        'template' => "{label}<div class='input-group'>{input}<div class='input-group-append'>" .
                            "<button id='accountbutton' onclick='accountbuttonaction()' class='btn btn-primary'>Add Client</button>" .
                            "</div></div>"
                    ])->dropDownList(
                        ArrayHelper::map(
                            Accounts::find()->where(['status' => 'Active'])->orderby(['account_name' => SORT_ASC])->all(),
                            'id',
                            'account_name'
                        ),
                        ['id' => 'company', 'prompt' => 'Please Select...']
                    )->label('Company') ?>
                </div>
            </div>
        </div>
    </div>
    
    <?php if ($this->context->action->id == 'update') { ?>
        <?= Tabs::widget([
            'navType' => 'nav nav-tabs nav-justified',
            'items' => [
                [
                    'label' => 'Details',
                    'content' => $this->render('formtabs/_details_tab', [
                        'model' => $model,
                        'users' => $users,
                        'form' => $form
                    ]),
                    'active' => true
                ],
                [
                    'label' => 'Contacts',
                    'content' => $this->render('formtabs/_contacts_tab', [
                        'model' => $model,
                        'users' => $users,
                        'form' => $form
                    ]),
                    'active' => false
                ],
                [
                    'label' => 'Operatives',
                    'content' => $this->render('formtabs/_times_tab', [
                        'model' => $model,
                        'form' => $form
                    ]),
                    'active' => false
                ],
                [
                    'label' => 'Attachments',
                    'content' => $this->render('formtabs/_attachments_tab', [
                        'model' => $model
                    ]),
                    'active' => false
                ],
                [
                    'label' => 'Notes',
                    'content' => $this->render('formtabs/_notes_tab', [
                        'model' => $model
                    ]),
                    'active' => false
                ],
                [
                    'label' => 'Fatigue',
                    'content' => $this->render('formtabs/_fatigue_tab', [
                        'model' => $model,
                        'form' => $form
                    ]),
                    'active' => false
                ],
            ]
        ]); ?>
    <?php } else { ?>
        <?= $this->render('formtabs/_details_tab', [
            'model' => $model,
            'users' => $users,
            'form' => $form
        ]); ?>
    <?php } ?>
    
    <div class="form-group">
        <?= Html::submitButton('Save', [
            'class' => 'btn btn-primary'
        ]) ?>
        <?= Html::a('Cancel', Yii::$app->request->referrer, [
            'class' => 'btn btn-info'
        ]) ?>
        <?= Html::a('Add Contact', '/contacts/create', [
            'class' => 'btn btn-secondary',
            'target' => '_blank'
        ]) ?>
        <?= Html::a('Add Account', '/accounts/create', [
            'class' => 'btn btn-secondary',
            'target' => '_blank'
        ]) ?>
    </div>
    
    <?php ActiveForm::end(); ?>
</div>
