<?php
use yii\helpers\Html;
use common\widgets\TinyMce;
use yii\helpers\{ArrayHelper, Url};
use kartik\typeahead\Typeahead;

$servicingstatus = \backend\models\Attributesvalues::formarray('Status');
$types = \backend\models\Attributesvalues::formarraytt('service_types');

?>
<style>
    .delete{
        cursor: pointer;
    }
    .action-buttons a, .action-buttons span{
        margin-left:5px;
    }
    .card-body span.fa{
        color: #fff;
        cursor:pointer;
    }
</style>  
    <?= yii\grid\GridView::widget([
        'dataProvider' => new \yii\data\ArrayDataProvider(['allModels' => $actitems, 'pagination' => false]),
        'tableOptions' => [
            'class' => 'table table-bordered',
        ],
        'options' => [
            'class' => 'table-responsive w-100',
        ],
        
        'headerRowOptions' => [
            'class' => 'bg-info',
        ],

        'summary' => false,
        'rowOptions' => function($dataModel){
            return [
                'id'=> "row-$dataModel->id",
            ];
        },
        'afterRow' => function($dataModel) use ($form){
            $out = '<tr><td colspan="9"  id="extended-cell_'. $dataModel->id .'" class="d-none p-0">';
            $out .= $form->field($dataModel, "[$dataModel->id]notes")->widget(TinyMce::class, ['height' => '100px'])->label(false);
            $out .= '</td></tr>';
            return $out;
        },
        'columns' => [
            [
                'label' => 'Actions',
                'format' => 'raw',
                'value' => function($dataModel){ 
                    if(!empty($dataModel->type) && $dataModel->servicesheet){
                        $servicesheetid = $dataModel->servicesheet?->id; 
                        $servicesheettype = $dataModel->servicesheet?->form; 
                        
                        $buttons =  '<span class="fa fa-arrow-down-long expand" title="Show Notes" data-id="'.$dataModel->id.'"></span> ';
                        $buttons .= ' ' . Html::Tag('span', '', ['class' => 'fa fa-trash delete', 'onClick' => "deleteItem('$dataModel->id')"]);
                        $buttons .= ' ' . HTML::A("<i class='fa fa-gears'></i>", ['/forms/update', 'id' => $servicesheetid, 'form' => $servicesheettype], ['title' => 'service']);
                        $buttons .= ' ' . HTML::A("<i class='fab fa-wpforms'></i>", ['/forms/view', 'id' => $servicesheetid, 'form' => $servicesheettype], ['title' => 'service']);
                        $buttons .= ' ' . Html::tag('span', '',['class' => 'fa fa-file-pdf modalpdf', 'data-url' => Url::to(['/forms/pdf', 'id' => $servicesheetid, 'form' => $servicesheettype])]);
                        return $dataModel->servicesheet ?  $buttons :  Html::Tag('span', '', ['class' => 'fa fa-trash delete', 'onClick' => "deleteItem('$dataModel->id')"]) .' '. html::tag('i', '',['class'=> 'fas fa-exclamation-triangle']);
                    }
                    
                },
            ],
            
            [
                'label' => 'Serial',
                'format' => 'raw',
                'value' => function($dataModel) use ($form, $servicingstatus){
                    $id = strtolower($dataModel->id);
                    $out = $form->field($dataModel, "[$dataModel->id]serial")
                    ->widget(Typeahead::class, [ 'options' => ['placeholder' => 'Filter as you type ...'],
                    'pluginOptions' => [
                        'highlight'=>true,
                        'minLength' => 3,
                    ],
                    'dataset' => [
                        [
                            'datumTokenizer' => "Bloodhound.tokenizers.obj.whitespace('value')",
                            'display' => 'text',
                            'remote' => [
                                'url' => Url::to(['/asset/find-asset']) . '?q=%QUERY',
                                'wildcard' => '%QUERY',
                                'limit' => 20
                            ]
                        ]
                            ],
                    'pluginEvents' => [
                        "typeahead:select" => "function(ev, suggestion) {
                            updateItem(suggestion, '$id');
                        }",

                    ]
                    ])
                    ->label(false);
                    $out .= $form->field($dataModel, "[$dataModel->id]assetid")->hiddenInput()->label(false);
                    return  $out;
                }
            ],

            
            [
                'attribute' => 'product',
                'label' => 'Product',
                'format' => 'raw',
                'value' => function($dataModel) use ($form, $types){
                    
                    $dataModel->type = $dataModel->type == 'lifejacketbulk' ? 'lifejacket' : $dataModel->type;
                    $out = $form->field($dataModel, "[$dataModel->id]type")
                    ->dropdownList(
                        $types,
                        [
                            'prompt' => 'Please Select', 
                            'class' => 'custom-select assettype',
                            'data' => [
                                'id' => $dataModel->id,
                            ]
                        ]
                    )
                    ->label(false);
                    $out .= $form->field($dataModel, "[$dataModel->id]product")
                        ->dropdownList(\modules\custom\models\Products::getProductbytype($dataModel->type), 
                            [
                                'data-id' => $dataModel->id,
                                'prompt' => 'Please Select',
                                'class' => 'custom-select productList',
                                'data' => [
                                    'id' => $dataModel->id,
                                ]
                            ]
                        )
                        ->label(false);
                    $display = $dataModel->productname !== 'Seago Other' ? 'd-none' : '';
                    $out .= "<div class='$display' id='typediv-$dataModel->id'>";
                    $out .= $form->field($dataModel, "[$dataModel->id]typea")->textInput(['id' => "otype-$dataModel->id"])->label('Other Type:');
                    $out .= "</div>";
                    $out .= $form->field($dataModel, "[$dataModel->id]productname")->hiddenInput(['id' => "productname-$dataModel->id"])->label(false);
                    return $out;
                }
            ],
            [
                'attribute' => 'servicetype',
                'label' => 'Service',
                'format' => 'raw',
                'value' => function($dataModel) use ($form, $model, $servicingstatus){
                    return 
                    '<div id="ServiceItems-'.strtolower($dataModel->id).'">'. $this->render('_serviceitem', ['model' => $dataModel, 'form' => $form]) .'</div>';
                    //return \modules\custom\widgets\ServiceInput::widget(['model' => $dataModel, 'form' => $form,  'productid' => $dataModel['product'] ,'assetid' => $dataModel['assetid']]);   
                }
            ],
            
            [
                'attribute' => 'locationid',
                'label' => 'Location',
                'format' => 'raw',
                'value' => function($dataModel) use ($form, $servicingstatus){
                    return $form->field($dataModel, "[$dataModel->id]locationid")
                        ->dropdownList($dataModel->freelocations($dataModel->id), ['prompt' => 'Please Select'])->label(false);
                }
            ],
            [
                'label' => 'Status',
                'format' => 'raw',
                'value' => function($dataModel) use ($form, $servicingstatus){
                    return $form->field($dataModel, "[$dataModel->id]status")
                        ->Dropdownlist($servicingstatus, [
                            'prompt' => 'Please Select...'
                        ])
                        ->label(false);
                }
            ],
        ]
    ]); ?>

  
<script>
$('.modalpdf').on('click', function(){
    url = $(this).attr('data-url');
	$.ajax({
		type: "get",
		url: url,
        success: function(result){
            $('#LGmodal-pdf #viewpdf').attr('src', result);
            $('#LGmodal-pdf').modal();
        }
    })    
})

$('.expand').on('click', function() {
    id = $(this).data('id');
    $(this).toggleClass('fa-arrow-down-long');
    $(this).toggleClass('fa-arrow-up-long');
    $('#extended-cell_' + id).toggleClass('d-none');    
})

$('.assettype').on('change', function(){
    var id = $(this).data('id');
    $.ajax({
        url:'/NGauge/products/getbytype',
        method:'GET',
        data: {type: $(this).val()},
        success: function(result){
            $('#activitiesitemsbe-'+id+'-product').empty();
            $('#activitiesitemsbe-'+id+'-product').append($('<option>', {
                    value: null,
                    text: 'Please Select',
                    selected: true,
                }));
            $.each(result, function(groupname, array){
                var group = $('<optgroup>', {
                    label: groupname
                });
                $.each(array, function( productid, name){              
                    group.append($('<option>', {
                    value: productid,
                    text: name
                }));
                $('#activitiesitemsbe-'+id+'-product').append(group);
                })
            })
        }
    });
});

$('.productList').on('change', function(){
    id = $(this).data('id');
    productid = $(this).val();
    assetid = $('#activitiesitemsbe-'+id+'-assetid').val();
	fieldid = '#typediv-' + id;
	if (productid == '52A6D417-2924-42B4-8479-F48B27DC1F14') {
        $(fieldid).removeClass('d-none');
    } else if($(fieldid).hasClass('d-none') == false) {
        $(fieldid).addClass('d-none');
    }
    getServiceItems(id, assetid, productid)
    
})

function updateItem(data, id){
    assettype = data.assettype;
    assetid = data.value;
    assetprod = data.productid;
    assettype.length > 0 ? $('#activitiesitemsbe-'+id+'-type').val(assettype).change() : false;
    assetprod.length > 0 ? $('#activitiesitemsbe-'+id+'-product').val(assetprod).change() : false;
    assetid.length > 0 ? $('#activitiesitemsbe-'+id+'-assetid').val(assetid) : false;
    assetid.length > 0 && assetprod.length > 0 ? getServiceItems(id, assetid, assetprod) : false;
    
}
function getServiceItems(id,assetid,productid){
    if(productid.length > 5){
        $.ajax({
            url:'/NGauge/activities/serviceitems',
            type:'get',
            data:{
                id:id,
                assetid: assetid,
                productid: productid,
            },
            success: function(result){
                idL = id.toLowerCase();
                $('#ServiceItems-'+ idL).html(result);
            }
        });
    }
}
</script>