<?php 

use yii\helpers\{Html, ArrayHelper};
use common\widgets\TinyMce;
use yii\widgets\Pjax;
use backend\models\{Accounts,Attributesvalues, User};
use kartik\select2\Select2;
use yii\db\Expression;


$employees = yii::$app->cache->getorset('Employees', function(){ return ArrayHelper::map(User::find()
    ->select(['groups', 'adv', 'id'])
    ->where(['like', 'groups', 'Staff'])
    ->orderby(new Expression("json_value(`sys_user`.`adv`, '$.firstname') ASC") )
    ->all(), 'id', 'fullname');
},3600);
$department = Attributesvalues::formarrayids('Department');
$types = Attributesvalues::formarray('Activity Types');
$status = Attributesvalues::formarray('Status');
$transport = Attributesvalues::formarray('transport');
$urgency = Attributesvalues::formarraytt('urgency');
asort($transport);

$agentsQuery =  Accounts::find()
    ->where(['type' => 'Agent'])
    ->orderby('name')
    ->all();
    
$addresses = [];
$dcaddresses = [];
$clientid = [];
$client  = [];
if(($client = $model->client)){
    foreach($client->alladdresses as $key => $address){
        $addresses[$address->id] = $address->getFulladdress(', ');
        $dcaddresses[$address->id] = $address->getFulladdress(', ');
    }
    $addresses['new'] = 'Add New Address';
    $clientid[$model->clientid] = $client->fullname; 
} else {
    $clientid = [];
}
foreach($agentsQuery as $key => $agent){
    foreach($agent->alladdresses as $key => $address){
        $dcaddresses[$address->id] = $agent->name.' -- '.$address->getFulladdress(', ');
    }
}



?>
<style>
    .btn {
        border-radius: 0;
    }
    .bg-info, .bg-info a{
        color: #fff !important;
    }
</style>
    <div class="row">
        <div class="col-lg-4 order-2 order-lg-1">
            <div class="card">
                <div class="card-header bg-info h5">
                    Job Details
                </div>
                <div class="card-body">
                    <?=$form->field($model, 'type')->dropdownlist($types, ['prompt' => 'Please Select'])->label()?>
                    <?=$form->field($model, 'status')->dropdownlist($status, ['prompt' => 'Please Select'])->label()?>
                    <?=$form->field($model, 'urgency')->dropdownlist($urgency, ['prompt' => 'Please Select'])->label()?>
                    <?=$form->field($model, 'engineer')->dropdownlist($employees, ['prompt' => 'Please Select'])->label('Employee')?>
                    <?=$form->field($model, 'duetime')->widget(kartik\date\DatePicker::class, [
                        'type' => 1,
                        'pluginOptions' => [
                            'showMeridian' => false,
                            'format' => 'dd/mm/yyyy',
                        ],
                        ])->label('Due Date')?>
                    <?=$form->field($model, 'title')->textInput()->label('Title')?>
                    <?=$form->field($model, 'description')->widget(TinyMce::class, [])->label();?>
                </div>
            </div>
        </div>
        <div class="col-lg-4 order-1 order-lg-2">
            <div class="card">
                <div class="card-header bg-info h5">
                    Client Details
                </div>
                <div class="card-body">
                    <?php Pjax::begin(['id' => 'contacts', 'class' => 'btn-group'])?>
                        <?= $form->field($model, 'clientid')->widget(Select2::class, [
                            'class' => 'form-control btn-group',
                            'value' => $model->clientid,
                            'data' => $clientid,
                            'maintainOrder' => true,
                            'options' => [
                                'id' => 'clients',
                                'placeholder' => 'Select Client...', 
                                'multiple' => false,
                            ],
                            'pluginOptions' => [
                                'allowClear' => true,
                                'minimumInputLength' => 9,
                                'ajax' => [
                                    'url' => "/NGauge/activities/getclients",
                                    'dataType' => 'json',
                                    'data' => new yii\web\JsExpression('function(params) { return {q:params.term, page: params.page}; }'),
                                ],
                                'escapeMarkup' => new yii\web\JsExpression('function (markup) { return markup; }'),
                                'templateResult' => new yii\web\JsExpression('function(city) { return city.text; }'),
                                'templateSelection' => new yii\web\JsExpression('function (city) { return city.text }'),
                            ],
                            'pluginEvents' => [
                                "select2:select" => "function(data) {
                                    $.ajax({
                                        type:'get',
                                        url:'/NGauge/activities/serviceableitems',
                                        data:{id:'$model->id', userid: data.params.data.id},
                                        success:function(html){
                                            $('#useritems').html(html);
                                        }
                                    });
                                }",
                                //    "select2:unselect" => "function(data) {console.log(data); welderdel(data.params.data.text); }"

                            ],
                            'addon' => [
                                'prepend' => [
                                    'content' => Html::checkbox('Activities[unknownclientname]', empty($model->clientid) ? true : false, [
                                        'id' => 'unknownclientname',
                                        'class' => 'btn btn-secondary',
                                        'data-label' => "Unknown",
                                    ]),
                                    'asButton' => false,
                                    ],
                                'append' => [
                                    'content' => Html::button('Add Client', [
                                        'class' => 'btn btn-secondary mbutton',
                                        'id' => 'CreateClient',
                                        'data-label' => "Add Client",
                                    ]),
                                    'asButton' => true,
                                ],
                            ],

                        ])
                        ->label('End User')
                        ?>
                        <p>
                        <?php if($client) { ?>
                            <?php $out = $client->fullname;
                                $out .= !empty($client->id) ? ' ' . html::tag('span', '', ['class' => "fa-regular fa-eye", 'onclick' => "detailmodal('$client->id', 'view')"]) : '';
                                $out .= !empty($client->id) ? ' ' . html::tag('span', '', ['class' => "fa-solid fa-pencil-alt", 'onclick' => "detailmodal('$client->id', 'update')"])  : ''; 
                                $out .= !empty($client->adv->phoneno) ? ' '. html::A(html::tag('span', '', ['class' => "fa-solid fa-phone"]), 'tel:'.$client->adv->phoneno, ['data-toggle'=>"tooltip", 'title'=>$client->adv->phoneno]): ''; 
                                $out .= !empty($client->email) ? ' '. html::A(html::tag('span', '', ['class' => "fa-regular fa-envelope"]), 'mailto:'.$client->email, ['data-toggle'=>"tooltip", 'title'=>$client->email]): ''; 
                                $out .= '<br/>';
                            echo $out;
                            ?>
                            </p>
                        <?php } else {?> 
                            <?= $form->field($model, 'clientname')->textInput(['id' => 'clientname', 'placeholder' => 'Name', 'class' => strlen($model->clientname) > 0 ? 'form-control d-block': 'form-control d-none'])->label(false); ?>
                            <?= $form->field($model, 'email')->textInput(['id' => 'clientemail', 'placeholder' => 'email'])->label(false); ?>
                        <?php } ?> 
                    <?php Pjax::end();?>
                
                    <?=$form->field($model, 'clientpo')->textInput();?>
                    <?=$form->field($model, 'clientref')->textInput();?>
                </div>
            </div>
            <div class="card">
                <div class="card-header bg-info h5">
                    Agent Details     
                    <span class="float-right">
                        <?= Html::Checkbox('agent', !empty($model->agentid) ? true : false, ['class' => 'toggleaddress', 'data-target' => '#agent_details']);?>
                    </span>
                </div>
                <div class="card-body <?= empty($model->agentid) ? 'd-none' : '' ?>" id="agent_details" >
                    <?php Pjax::begin(['id' => 'agentsPjax', 'class' => 'btn-group'])?>
                        
                        <?php $agents = ArrayHelper::map($agentsQuery, 'id', 'name'); ?>
                            <?=$form->field(
                                $model,
                                'agentid',
                                [
                                    'template' => '
                                        {label}
                                        <div class="input-group">
                                            {input}
                                            <div class="input-group-append agentModal">
                                                <label class="input-group-text bg-secondary text-white" id="basic-addon2">
                                                    Add Agent
                                                </label>
                                            </div>
                                            {hint}{error}
                                        </div>',
                                ]
                            )->dropdownlist(
                                $agents,
                                [
                                    'prompt' => 'Please Select',
                                ]
                            )
                            ->label()
                            ?>
                        <?= $form->field($model, 'agent_contact')->textInput(); ?>
                        <?= $form->field($model, 'agent_contact_email')->textInput(); ?>
                        <span class="importeddata">
                                <?=$model->imp_agentname ? $model->imp_agentname : null;?>
                        </span>
                    <?php Pjax::end(); ?>
                </div>
            </div>
        </div>
        <div class="col-lg-4  order-3 order-lg-3">
            <div class="card">
                <div class="card-header bg-info h5">
                    Billing Details
                    <?php $billingaddress = false; ?>
                    <?php if(!empty($model->fulladdresses) && array_key_exists('billing', $model->fulladdresses) == true && !empty(($address = $model->fulladdresses['billing']->fulladdress))){ ?>
                        <?php $billingaddress = true; ?>
                        <span class="float-right">
                            <span class="fa-solid fa-copy btn-copy mr-2"  data-from="billing" data-to="collection"></span>
                            <?= Html::Checkbox('billingaddress', $billingaddress, ['class' => 'toggleaddress', 'data-target' => '#billing-address']);?>
                        </span>
                    <?php } else { ?>
                        <span class="float-right">
                            <span class="fa-solid fa-copy btn-copy"  data-from="billing" data-to="collection"></span>
                        </span>
                    <?php } ?> 
                </div>
                <div class="card-body">
                    <div class="card-text">
                        <div class="row">
                            <div class="col-md-6">
                                <?=$form->field($model, 'invoiceno')->textInput();?>
                                <?=$form->field($model, 'creditno')->textInput();?>
                                <?=$form->field($model, 'paymentstatus')->dropdownlist(['unpaid' => 'Unpaid', 'paid' => 'Paid'], ['prompt' => 'Please Select']);?>
                                <?=$form->field($model, 'jobno')->textInput(['disabled' => true]); ?>
                            </div>
                            <div class="col-md-6">
                                <?php if($billingaddress){ ?>
                                    <p>
                                        <?= $address ?>
                                    </p>
                                <?php } ?> 
                                
                            </div>
                        </div>
                        <?php $fullAddrresses = $model->fulladdresses['billing']; ?>
                        <?php if(count($addresses) >= 1){ ?>
                            <?= $form->field($fullAddrresses, "[billing]id")->dropDownlist($addresses, [
                                'value' => !empty($fullAddrresses['id']) ? $fullAddrresses['id'] : null,
                                'prompt' => 'Please Select', 
                                'class' => 'form-control address_dd', 
                                'data-target' => '#billing_address_form'
                                ])->label('Billing Address') ?>
                        <?php }  ?>

                        <div id='billing-address'>
                            <div id="billing_address_form"  class="<?= count($addresses) >= 1 ? 'd-none' : '' ?>">
                                <?= $form->field($fullAddrresses, "[billing]type")->hiddenInput(['value' => 'billing'])->label(false); ?>
                                <?= $form->field($fullAddrresses, "[billing]address1")->textInput(); ?>
                                <?= $form->field($fullAddrresses, "[billing]address2")->textInput(); ?>
                                <?= $form->field($fullAddrresses, "[billing]address3")->textInput(); ?>
                                <?= $form->field($fullAddrresses, "[billing]town")->textInput(); ?>
                                <?= $form->field($fullAddrresses, "[billing]county")->textInput(); ?>
                                <?= $form->field($fullAddrresses, "[billing]country")->textInput(); ?>
                                <?= $form->field($fullAddrresses, "[billing]postcode")->textInput(); ?>
                                <?= $form->field($fullAddrresses, "[billing]saveaddress")->checkbox(['label' => '<chk></chk> Save Address'])->label(false); ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="card">
                <div class="card-header bg-info h5">
                    Collection Details
                    
                    <?php $collectionaddress = false; ?>
                    <?php if(!empty($model->fulladdresses) && array_key_exists('collection', $model->fulladdresses) == true && !empty(($address = $model->fulladdresses['collection']->fulladdress))){ ?>
                        <?php $collectionaddress = true; ?>
                        <span class="float-right">
                            <span class="fa-solid fa-copy btn-copy mr-2" data-from="collection" data-to="return"></span>
                            <?= Html::Checkbox('collectionaddress', $collectionaddress, ['class' => 'toggleaddress', 'data-target' => '#collection-address']);?>
                        </span>
                    <?php } else { ?> 
                        <span class="float-right">
                            <span class="fa-solid fa-copy btn-copy" data-from="collection" data-to="return"></span>
                        </span>
                    <?php } ?> 
                        
                </div>
                <div class="card-body">
                    <div class="card-text">
                        <div class="row">
                            <div class="col-md-6">
                                <?= $form->field($model, 'collectiondate')
                                    ->widget(
                                        kartik\date\DatePicker::class, 
                                        [
                                            'type' => 1,
                                            'pluginOptions' => [
                                                'showMeridian' => false,
                                                'format' => 'dd/mm/yyyy',
                                            ],
                                        ]
                                    )
                                    ->label()?>
                                <?=$form->field($model, 'transportmethod', ['template' => '{label}<div class="input-group">
                                            {input}
                                            <div class="input-group-append">
                                                <label class="input-group-text" id="basic-addon2"><i class="fa fa-plus"></i></label>
                                            </div>
                                            {hint}{error}
                                    </div>',
                                    ])->dropdownlist($transport, ['prompt' => 'Please Select'])->label()?>
                                <?=$form->field($model, 'collectionref')->textInput();?>
                            </div>
                            <div class="col-md-6">
                                <?php if($collectionaddress){ ?>
                                    <p>
                                        <?= $address ?>
                                    </p>
                                <?php } ?> 
                            </div>
                        </div>
                        <?php $fullAddrresses = $model->fulladdresses['collection']; ?>
                        
                        <?php if(count($dcaddresses) >= 1){ ?>
                            <?= $form->field($fullAddrresses, "[collection]id")->dropDownlist($dcaddresses, [
                                'value' => !empty($fullAddrresses['id']) ? $fullAddrresses['id'] : null,
                                'prompt' => 'Please Select', 
                                'class' => 'form-control address_dd', 
                                'data-target' => '#collection_address_form'
                                ])->label('Collection Address') ?>
                        <?php }  ?>

                        <div id='collection-address'>
                            <div id="collection_address_form" class="<?= count($dcaddresses) >= 1 ? 'd-none' : '' ?>">
                                <?= $form->field($fullAddrresses, "[collection]type")->hiddenInput(['value' => 'collection'])->label(false); ?>
                                <?= $form->field($fullAddrresses, "[collection]address1")->textInput(); ?>
                                <?= $form->field($fullAddrresses, "[collection]address2")->textInput(); ?>
                                <?= $form->field($fullAddrresses, "[collection]address3")->textInput(); ?>
                                <?= $form->field($fullAddrresses, "[collection]town")->textInput(); ?>
                                <?= $form->field($fullAddrresses, "[collection]county")->textInput(); ?>
                                <?= $form->field($fullAddrresses, "[collection]country")->textInput(); ?>
                                <?= $form->field($fullAddrresses, "[collection]postcode")->textInput(); ?>
                                <?= $form->field($fullAddrresses, "[collection]saveaddress")->checkbox(['label' => '<chk></chk> Save Address'])->label(false); ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="card">
                <div class="card-header bg-info h5">
                    Return Details
                    <?php $returnaddress = false; ?>
                    <?php if(!empty($model->fulladdresses) && array_key_exists('return', $model->fulladdresses) == true && !empty(($address = $model->fulladdresses['return']->fulladdress))){ ?>
                        <?php $returnaddress = true; ?>
                        <span class="float-right">
                            <?= Html::Checkbox('returnaddress', $returnaddress, ['class' => 'toggleaddress', 'data-target' => '#return-address']);?>
                        </span>
                    <?php } ?> 
                        
                </div>
                <div class="card-body">
                    <div class="card-text">
                        <div class="row">
                            <div class="col-md-6">
                            <?=$form->field($model, 'return_transportmethod', ['template' => '{label}<div class="input-group">
                                    {input}
                                    <div class="input-group-append">
                                        <label class="input-group-text" id="basic-addon2"><i class="fa fa-plus"></i></label>
                                    </div>
                                    {hint}{error}
                            </div>',
                            ])->dropdownlist($transport, ['prompt' => 'Please Select'])->label()?>
                        <?=$form->field($model, 'return_date')->textInput();?>
                        <?=$form->field($model, 'returnref')->textInput();?>
                            </div>  
                            <div class="col-md-6">
                                <?php if($returnaddress){ ?>
                                    <p>
                                        <?= $address ?>
                                    </p>
                                <?php } ?> 
                            </div>  
                        </div>  
                        
                        <?php $fullAddrresses = $model->fulladdresses['return']; ?>
                        <?php if(count($dcaddresses) >= 1){ ?>
                            <?= $form->field($fullAddrresses, "[return]id")->dropDownlist($dcaddresses, [
                                'value' => !empty($fullAddrresses['id']) ? $fullAddrresses['id'] : null,
                                'prompt' => 'Please Select', 
                                'class' => 'form-control address_dd', 
                                'data-target' => '#return_address_form'
                                ])->label('Return Address') ?>
                        <?php }  ?>

                        <div id='return-address'>
                            <div id="return_address_form"  class="<?= count($dcaddresses) >= 1 ? 'd-none' : '' ?>">
                                <?= $form->field($fullAddrresses, "[return]type")->hiddenInput(['value' => 'return'])->label(false); ?>
                                <?= $form->field($fullAddrresses, "[return]address1")->textInput(); ?>
                                <?= $form->field($fullAddrresses, "[return]address2")->textInput(); ?>
                                <?= $form->field($fullAddrresses, "[return]address3")->textInput(); ?>
                                <?= $form->field($fullAddrresses, "[return]town")->textInput(); ?>
                                <?= $form->field($fullAddrresses, "[return]county")->textInput(); ?>
                                <?= $form->field($fullAddrresses, "[return]country")->textInput(); ?>
                                <?= $form->field($fullAddrresses, "[return]postcode")->textInput(); ?>
                                <?= $form->field($fullAddrresses, "[return]saveaddress")->checkbox(['label' => '<chk></chk> Save Address'])->label(false); ?>
                            </div>
                        </div>
                       
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        $('.address_dd').on('change', function(){
            if($(this).val() == 'new'){
                $($(this).data('target')).toggleClass('d-none');
            } else if (
                $($(this).data('target')).hasClass('d-none') == false
            ) {
                $($(this).data('target')).toggleClass('d-none');
            }
        });

    $('.btn-copy').on('click', function(){
        from = $(this).data('from');
        to = $(this).data('to');
        $('#address-'+to+'-address1').val($('#address-' + from + '-address1').val());
        $('#address-'+to+'-address2').val($('#address-' + from + '-address2').val());
        $('#address-'+to+'-address3').val($('#address-' + from + '-address3').val());
        $('#address-'+to+'-town').val($('#address-' + from + '-town').val());
        $('#address-'+to+'-county').val($('#address-' + from + '-county').val());
        $('#address-'+to+'-country').val($('#address-' + from + '-country').val());
        $('#address-'+to+'-postcode').val($('#address-' + from + '-postcode').val());
    })
    $('.toggleaddress').on('change', function(){
        $($(this).data('target')).toggleClass('d-none');
    })
    $('#CreateClient').on('click', function(){
        $.ajax({
            type: 'get',
            url: '/NGauge/user/create?type=CC170835-61E0-40E5-973E-E08B112A2322',
            success:function(result){
                $('#LGmodal .modal-body').html(result.body);
                $('#LGmodal').modal();
            }            
        })
    })
    $('.agentModal').on('click', function(){
        $.ajax({
            type: 'get',
            url: '/NGauge/accounts/create',
            success:function(result){
                $('#LGmodal .modal-title').html(result.modal_header);
                $('#LGmodal .modal-body').html(result.modal_body);
                $('#LGmodal .modal-footer').html(result.modal_footer);
                $('#LGmodal').modal();
            }            
        })
    })

    $('#unknownclientname').on('change', function(){
        if($(this).is(':checked') == true){
            $('#clientname').removeClass('d-none');
            $('#clientname').addClass('d-block');
            $('#contacts .select2-search__field').prop('disabled',true);
        } else {
            $('#contacts .select2-search__field').prop('disabled',false);
            $('#clientname').removeClass('d-block');
            $('#clientname').addClass('d-none');
        }
    })
   

    function postSubmit(data){
        if(data.type == 'CC170835-61E0-40E5-973E-E08B112A2322'){

            var client = $("#clients");
            var newOption = new Option(data.clientname, data.id, false, false);
            client.append(newOption).trigger('change');
            client.val(data.id).trigger("change");
            $('#clientname').val(data.client_name).attr('readonly', true);
            $('#clientemail').val(data.email).attr('readonly', true);
        } else if(data.type == '71EB4F5A-83E7-4C1A-A456-6688437F68AD') {
            var client = $("#activities-agentid");
            var newOption = new Option(data.clientname, data.id, false, false);
            client.append(newOption);
            client.val(data.id);
        }
        $('#LGmodal .modal-body').html('');
        $('#LGmodal').modal('hide');
    }

    function detailmodal(id) {
        $.ajax({
                type: "GET",
                url: "/NGauge/account/details",
                data: {
                    id: id
                },
            })
            .done(function(result) {
                $('#LGmodal .modal-header .title').html('User Account');
                $('#LGmodal .modal-body').html(result);
				$('#LGmodal .modal-footer').html('<div class="float-right"><button type="button" class="btn btn-secondary mr-3" data-dismiss="modal">Close</button></div>');
            });
        $('#LGmodal').modal();
    }
    $('#activities-agent').on('change', function(){
        if($(this).is(':checked') == true){
            $('#agent_details').removeClass('d-none');
            $('#agent_details').addClass('d-block');
        } else {
            $('#agent_details').removeClass('d-block');
            $('#agent_details').addClass('d-none');
        }
    })
    $(document).on('click', '#request-button',  function(){
        data = $('#request-service-form').find('input').serializeArray();
        $.ajax({
            url: '/NGauge/activities/addtoservice?id=<?= $model->id ?>',
            type:'post',
            data:data,
            success:function(result, statusCode, jqXHR){
                $('#actitems').html(result);
                $.pjax({container:'#useritems', async:true, timeout:3000});
            }
        })
    })
</script>