<?php

use yii\helpers\{ArrayHelper, Html};
use yii\widgets\ActiveForm;
use kartik\date\DatePicker;
use common\widgets\DynamicInput;
use modules\activities\models\Servicebaysbe;
$this->title = 'Life Jacket Serivce';
/* @var $this yii\web\View */
/* @var $model backend\models\Serviceljbe */
/* @var $form yii\widgets\ActiveForm */

$verlayout = '<div class="row"><div class="col-11">{label}</div><div class="col-1">{input}</div></div>';

global $row;
$row = 1;

$activityitem = $model->activityitem;
if ($activityitem && ($product = $activityitem->productl)) {
    $model->type = empty($model->type) == false && is_array($activityitem) ? $model->type : $activityitem->product;
    $model->email = empty($model->email) == false ? $model->email : $activityitem->activity->email;
}
if ($activityitem && $activityitem->activity && $activityitem->activity->clientsl && $activityitem->activity->clientsl[0]) {
    if (($client = $activityitem->activity->clientsl[0] ? $activityitem->activity->clientsl[0] : null)) {
        $model->client_fullname = empty($model->client_fullname) == false ? $model->client_fullname : $client->fullname;
        $model->mobile = empty($model->mobile) == false ? $model->mobile : $client->adv->mobileno;
        $model->phone = empty($model->phone) == false ? $model->phone : $client->adv->phoneno;
    }
} elseif ($activityitem && $activityitem->activity && empty($activityitem->activity?->agentname) == false) {
    //$model->activity->clientname;
    $model->email = $model->email == null ? $activityitem->activity->agentl->email : $model->email;
    $model->mobile = $model->mobile == null ? $activityitem->activity->agentl->useradv->mobileno : $model->mobile;
    $model->phone = $model->phone == null ? $activityitem->activity->agentl->useradv->phoneno : $model->phone;
    $model->agent = $model->agent == null ? $activityitem->activity->agentname : $model->agent;
}

$techs = Yii::$app->cache->getorset('raft-techs', function() {
    return ArrayHelper::map(\backend\models\User::find()->where(['like', 'groups', 'Servicing'])->orderby(['username' => SORT_ASC])->all(), 'id', 'fullname');
}, 3600);
$products = \modules\custom\models\Products::getProductbytype('LifeJacket');
$si = new \modules\forms\models\sub\ServiceItem();
$parts = $si->parts;
$locationsa = ArrayHelper::map(
    Servicebaysbe::find()
        ->where(
            [
                'or', 
                ['is', 'occupied', null], 
                ['!=', 'occupied', 1]
            ]
        )
        ->andwhere(['in', 'location', ['LR', 'F']])
        ->orderby('sequence')
        ->all(),
        'id', 
        'name', 
        'location'
    );
$locationsb = ArrayHelper::map(
    Servicebaysbe::find()
    ->andwhere(['not',['in', 'location', ['LR', 'F']]])
    ->orderby('sequence')    
    ->all(),
    'id', 
    'name', 
    'location'
);
$locations = array_merge($locationsa, $locationsb);
arsort($locations);
$statuss = \backend\models\Attributesvalues::formArray('status');

?>
<style>
    
    .buttons{
        z-index:10000;
        position: fixed;
        left:0;
        bottom: 10vh;
        max-width: 50px;
    }
    .buttons .nav-link{
        width: 45px;
    }
    .serviceljbe-form{
        margin-left: 35px;
    }
    .admin .fa.fa-eye{
        cursor: pointer;
        color:#fff;
    }
</style>
<div class="serviceljbe-form">
    <?php $form = \yii\widgets\ActiveForm::Begin();?>
        <?= yii\grid\GridView::widget([
                    'dataProvider' => new \yii\data\ArrayDataProvider(['allModels' => $model->subforms, 'pagination' => false]),
                    'summary'=> false,
                    'pager' => false, 
                    'tableOptions'=> ['class' => 'table table-bordered'],
                    'options' => [],
                    'afterRow' => function($dataModel, $key, $index, $grid) use ($form, $model, $verlayout, $parts){
                        $dataid = $key;
                        $out = '<tr class="d-none" data-rowid="'.$key.'" id="rowchecks-'.$key.'">';
                        $out .= '<td></td>';
                        $out .= '<td colspan="2">';
                        $out .=  DynamicInput::widget(['form' => $form, 'model' => $dataModel, 'name' => "[$dataid]verification1", 'width' => 'd-inline', 'format' => $verlayout]);
                        $out .=  DynamicInput::widget(['form' => $form, 'model' => $dataModel, 'name' => "[$dataid]verification2", 'width' => 'd-inline', 'format' => $verlayout]);
                        $out .=  DynamicInput::widget(['form' => $form, 'model' => $dataModel, 'name' => "[$dataid]verification3", 'width' => 'd-inline', 'format' => $verlayout]);
                        //$out .=  DynamicInput::widget(['form' => $form, 'model' => $dataModel, 'name' => "[$dataid]verification4", 'width' => 'd-inline', 'format' => $verlayout]);
                        $out .= '</td>';
                        $out .= '<td colspan="2">';
                        $out .=  DynamicInput::widget(['form' => $form, 'model' => $dataModel, 'name' => "[$dataid]verification4", 'width' => 'd-inline', 'format' => $verlayout]);
                        //$out .=  DynamicInput::widget(['form' => $form, 'model' => $dataModel, 'name' => "[$dataid]verification5", 'width' => 'd-inline', 'format' => $verlayout]);
                        $out .=  DynamicInput::widget(['form' => $form, 'model' => $dataModel, 'name' => "[$dataid]verification6", 'width' => 'd-inline', 'format' => $verlayout]);
                        $out .=  DynamicInput::widget(['form' => $form, 'model' => $dataModel, 'name' => "[$dataid]verification7", 'width' => 'd-inline', 'format' => $verlayout]);
                        $out .= '</td>';
                        $out .= '<td colspan="2">';
                        $out .=  DynamicInput::widget(['form' => $form, 'model' => $dataModel, 'name' => "[$dataid]verification8", 'width' => 'd-inline', 'format' => $verlayout]);
                        $out .=  DynamicInput::widget(['form' => $form, 'model' => $dataModel, 'name' => "[$dataid]verification9", 'width' => 'd-inline', 'format' => $verlayout]);
                        $out .=  DynamicInput::widget(['form' => $form, 'model' => $dataModel, 'name' => "[$dataid]verification10", 'width' => 'd-inline', 'format' => $verlayout]);
                        $out .= '</td>';
                        $out .= '</tr>';
                        $out .= '<tr class="d-none" id="rowNotes-'.$key.'">';
                            $out .= '<td colspan="" class="text-right">Remarks</td>';
                            $out .= '<td colspan="7" class="text-right">';
                            $out .= $form->field($dataModel, "[$dataid]remarks")->textArea(['rows' => 3, 'class' => 'form-control'])->label(false);
                            $out .= '</td>';
                        $out .= '</tr>';
                        $out .= '<tr class="d-none" id="rowParts-'.$key.'">';
                        $out .= '<td colspan="" class="text-right">Parts</td>';
                        $out .= '<td colspan="7" class="p-0">';
                            $out .= '<table class="table table-borderless table-condensed" id="veritems-'.$key.'">';
                                $out .= '<thead>';
                                    $out .= '<tr>';
                                        $out .= '<td>'.HTML::tag('span', '', ['data-id' => $key, 'class' => 'fa fa-plus addBulkRow']).'</td>';
                                        $out .= '<th>Verification</th>';
                                        $out .= '<th>Qty</th>';
                                        $out .= '<th>Exp Date</th>';
                                        $out .= '<th>Replace</th>';
                                        $out .= '<th>Exp Date</th>';
                                        $out .= '<th>Hidden</th>';
                                    $out .= '</tr>';
                                $out .= '</thead>';
                                $out .= '<tbody>';
                                    foreach ($dataModel->items as $key1 => $item) {   
                                        $out .= $this->render('_item_bulk', ['form' => $form, 'key' => $key1, 'id' => $key, 'model' => $item, 'parts' => $parts]);
                                    }
                                $out .= '</tbody>';
                            $out .= '</table>';
                        $out .= '</td>';
                        $out .= '</tr>';

                        $out .= '</td></tr>';
                        return $out;
                    },
                    'columns' => [
                        [
                            'format' => 'raw',
                            'label'=> 'Jacket | Parts | Notes',
                            'contentOptions' => ['class' => 'text-center'],
                            'value' => function($dataModel, $key) use ($row, $model){
                                global $row;
                                $out = '';
                                $out .= $row++ . ' | ';
                                $out .= Html::tag('span', '', ['class' => 'fa-regular fa-eye showParts', 'data-id' => $key, 'style' => 'cursor:pointer' ]);
                                $out .= ' | '.Html::tag('span', '', ['class' => 'fa-regular fa-comments showNotes', 'data-id' => $key, 'style' => 'cursor:pointer' ]);
                                //$out .= ' | '. $dataModel->activityitem?->status;
                                $out .= Html::A(Html::tag('span', '', ['class' => 'fa-solid fa-camera']), ['/camera/create', 'relatedid' => $model->id, 'relatedto' => $model->form, 'subfolder' => $dataModel->serial_number], ['class' => 'p-2', 'target' => '_blank']);
                                return $out;
                            }
                        ],
                        [
                            'format' => 'raw',
                            'attribute' => 'type',
                            'contentOptions' => ['class' => 'p-0 text-center'],
                            'value' => function($dataModel, $key) use ($form, $row, $products){
                                return $form->field($dataModel, "[$key]type")->dropdownlist($products, ['prompt' => Yii::t('app', 'Please Select'), 'class' => 'd-inline form-control'])->label(false);
                            }
                        ],
                        [
                            'format' => 'raw',
                            'attribute' => 'serial_number',
                            'contentOptions' => ['class' => 'p-0 text-center'],
                            'value' => function($dataModel, $key) use ($form, $row){
                                
                                return DynamicInput::widget(['form' => $form, 'model' => $dataModel, 'name' => "[$key]serial_number", 'format' => false, 'width' => 'd-inline', 'label' => false]);
                            }
                        ],
                        [
                            'format' => 'raw',
                            'label' => 'Life Jacket Date of Manufacture',
                            'attribute' => 'date_of_manufacturer',
                            'contentOptions' => ['class' => 'p-0 text-center'],
                            'value' => function($dataModel, $key) use ($form){
                                return DynamicInput::widget(['form' => $form, 'model' => $dataModel, 'name' => "[$key]date_of_manufacturer", 'format' => false, 'width' => 'd-inline', 'label' => false]);
                            }
                        ],
                        [
                            'format' => 'raw',
                            'label' => 'CO2 Cylinder Gross Weight (g)',
                            'attribute' => 'grossweight',
                            'contentOptions' => ['class' => 'p-0 text-center'],
                            'value' => function($dataModel, $key) use ($form){
                                return DynamicInput::widget(['form' => $form, 'model' => $dataModel, 'name' => "[$key]grossweight", 'format' => false, 'width' => 'd-inline', 'label' => false]);
                            }
                        ],
                        [
                            'format' => 'raw',
                            'label' => 'CO2 Cylinder Actual Weight (g)',
                            'attribute' => 'actualweight',
                            'contentOptions' => ['class' => 'p-0 text-center'],
                            'value' => function($dataModel, $key) use ($form){
                                return DynamicInput::widget(['form' => $form, 'model' => $dataModel, 'name' => "[$key]actualweight", 'format' => false, 'width' => 'd-inline', 'label' => false]);
                            }
                        ],
                        [
                            'format' => 'raw',
                            'attribute' => 'allchecks',
                            'contentOptions' => ['class' => 'p-0 text-center'],
                            'value' => function($dataModel, $key) use ($form){
                                return $form->field($dataModel, "[$key]allchecks")->checkbox(['class' => 'd-inline allChecks','label'=> false, 'data-id' => $key])->label(false)
                                . '<div class="d-none">'.$form->field($dataModel, "[$key]id")->hiddenInput(['value' => $key])->label(false).'</div>';
                            }
                        ],
                        [
                            'format' => 'raw',
                            'label' => 'Status',
                            'value' => function($dataModel) use ($form, $statuss){
                                $act = $dataModel->activityitem;
                                $out = '';
                                if($act){
                                    $id = $act->id;
                                    $out .= $form->field($act, "[$id]status")->dropdownlist($statuss, ['prompt' => 'Please Select'])->label(false);
                                    //return $act->status;
								} 
                                return $out;
                            }
                        ],
                        [
                            'format' => 'raw',
                            'label' => 'Location',
                            'value' => function($dataModel) use ($form, $locations){
                                $act = $dataModel->activityitem;
                                if($act){
                                $id = $act->id;
                                //return $act->location;
                                return $form->field($act, "[$id]locationid")->dropdownlist($locations, ['prompt' => 'Please Select'])->label(false);
									} else {
return false;
								}
                            }
                        ],
                    ],
                    ]);
                ?>
        <div class="card">
            <div class="card-body">
        
                <div class="row mt-3">
                    <div class="col-md-4">
                        <?= $form->field($model, 'date_of_service')->widget(Datepicker::class, ['type' => 1, 'options' => ['convertFormat' => true,], 'pluginOptions' => ['format' => 'dd/mm/yyyy','todayHighlight' => true,'todayBtn' => true]]); ?>
                        <?= $form->field($model, 'date_of_next_service')->widget(Datepicker::class, ['type' => 1, 'options' => ['convertFormat' => true,], 'pluginOptions' => ['format' => 'dd/mm/yyyy','todayHighlight' => true,'todayBtn' => true]]); ?>
                    </div>
                    <div class="col-md-4">
                        <?= $form->field($model, 'technician')->dropdownlist($techs, ['prompt' => 'Please Select']); ?>
                        <?= $form->field($model, 'certno')->textInput(['readonly' => true]); ?>
                        <?= $form->field($model, 'invoiceno')->textInput(['readonly' => true]); ?>
                    </div>
                    <div class="col-md-4">
                        <?php $canvasid = Html::getInputId($model, 'signature').'_canvas'; ?>
                        <?= $form->field($model, 'signature', ['template' => '{label}<br/>{input}'])
                            ->widget(\common\widgets\SignatureInput::class, [ 'name' => 'signature', 'button' => false])
                            ->label('Signature '. Html::tag('span','', ['onClick' => "clearcanvas('$canvasid');", 'class' => 'fa fa-times text-danger h4'])); ?>
                    </div>
                </div>
                
                <?=$form->errorSummary($model,
            [
                'header' => '<div class="card"><div class="card-header bg-danger">Errors</div><div class="card-body m-0">',
                'footer' => '</div></div>',
            ]);?>
            </div>
        </div>
    <?php \yii\widgets\ActiveForm::End();?>
</div>
<div class="buttons">
    <ul class="nav nav-pills nav-stacked mt-2">    
        <li class="nav-item">
            <?=Html::Button(Html::tag('span', '', ['class' => 'fa-regular fa-floppy-disk']), ['class' => 'nav-link bg-success btn-save text-white p-2'])?>
        </li>
        <li class="nav-item">
            <?=Html::A(Html::tag('span', '', ['class' => 'fa-solid fa-briefcase']), ['/activities/update', 'id' => $model->relatedid], ['class' => 'nav-link bg-info text-white p-2', 'target' => '_blank'])?>
        </li>
        <li class="nav-item">
            <?=Html::Button(Html::tag('span', '', ['class' => 'fa-solid fa-folder-open']), ['class' => 'nav-link bg-info text-white p-2'])?>
        </li>
        <li class="nav-item">
            <?=Html::A(Html::tag('span', '', ['class' => 'fa-solid fa-camera']), ['/camera/create', 'relatedid' => $model->id, 'relatedto' => $model->form], ['class' => 'nav-link bg-info text-white p-2', 'target' => '_blank'])?>
        </li>
    </ul>
</div>
<?php if (yii::$app->controller->action->id == 'update'){ ?>
    <?php if ($model->solas == true) { ?>
        <script>
        $('.solas').toggleClass('d-none');
        </script>
    <?php } ?>
<?php } ?>


<script>
    function addrow(id) {
        
        var count = $('.Service_Item').last().attr('data-id') + 1;
        $.ajax({
                type: "get",
                url: "/NGauge/forms/additem",
                data: {
                    id: id,
                    form: 'ServiceLifeJacket',
                    count: count,
                },
            })
            .done(function(result) {
                if(result){
                    $('.Service_Items').append(result);
                }
            });
    }
    function deleteRow(id){
        $('#row-' + id).remove();
    }
$('.showParts').on('click', function(){
    id = $(this).data('id');
    $('#rowParts-' + id).toggleClass('d-none');
})
$('.showNotes').on('click', function(){
    id = $(this).data('id');
    $('#rowNotes-' + id).toggleClass('d-none');
})
$('.addBulkRow').on('click', function() {
    id = $(this).data('id');
    $.ajax({
        url: '/NGauge/forms/addbulkitem', 
        data: {
            id: id,
            form: 'ServiceLifeJacket',
        },
        success :  function(result) {
            row = $(result).find('tr');
            $('#veritems-' + id +' > tbody').append(row);
        }
    });
})
$('.allChecks').on('change', function() {
    id = $(this).data('id');
    $('#rowchecks-' + id).toggleClass('d-none');
    /*
    if ($(this).is(':checked')) {
        
    } else {
        $('#rowchecks-' + id).toggleClass('d-none');  
    }*/
})
$('#serviceljbe-solas').on('change', function() {
    $('.solas').toggleClass('d-none');
})

$('#lj-type').on('change', function() {
    console.log('Found');
    if ($('#lj-type option:selected').text() == 'Seago Other') {
        console.log('Found');
        $('#ljtypediv').toggleClass('d-none');

    }
})

$(function(){
    if($(window).width() <= 992){
        $('.md-accordion').removeClass('show');
    } else if($(window).width() > 992){
        $('.md-accordion').addClass('show');
    }
});

$(window).resize(function(){
    if($(window).width() <= 992){
        $('.md-accordion').removeClass('show');
    } else if($(window).width() > 992){
        $('.md-accordion').addClass('show');
    }

})
$('.btn-save').on('click', function(){
    $('form').submit();
})
</script>
