<?php

use yii\web\View;
use yii\widgets\Pjax;
use app\base\Common;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\select2\Select2;
use wbraganca\dynamicform\DynamicFormWidget;
use yii\helpers\ArrayHelper;
use app\models\Labmaster;
use app\models\Specimenmaster;
use app\models\Labtestmapping;

/* @var $this yii\web\View */
/* @var $model app\models\Labsamplerequest */
/* @var $form yii\widgets\ActiveForm */

$Surveys = Common::getSurvey();
$Locations = Common::getLocations();
$PIDs = Common::getLabrequestPIDs();
$Depts = Common::getLabdepartments();
$LabsMaps = Labtestmapping::find()->innerJoinWith('tests T')->orderBy(["T.lab_test_name" => SORT_ASC])->one();
if($model->isNewRecord)
	$Labresults = Common::getLabresults();
else 
	$Labresults = Common::getLabresults($model->lab_smple_tst_id);
$Labs = ArrayHelper::map(Labmaster::find()->orderBy(["lab_test_name" => SORT_ASC])->all(), 'lab_test_code', 'lab_test_name');
$Specimens = ArrayHelper::map(Specimenmaster::find()->orderBy(["lab_spcmn_name" => SORT_ASC])->all(), 'lab_spcmn_code', 'lab_spcmn_name');
if(Yii::$app->params['SURVEY'] != '') {
	$Locations = Common::getSurlocations(Yii::$app->params['SURVEY']);
}
if(Yii::$app->params['SURVEY'] != '' && Yii::$app->params['LOCATION'] != '') {
	$Locations = Common::getSurlocations(Yii::$app->params['SURVEY']);
	$PIDs = Common::getLabrequestPIDs(Yii::$app->params['SURVEY'], Yii::$app->params['LOCATION']);
}

$js = '
    var datefmt = "'.strtolower(Yii::$app->formatter->dateFormat).'";
';
$this->registerJs($js, View::POS_HEAD);

$headJS = <<<JS
var response;
function survey_change(ctrl) {
	// console.log($(ctrl).val());
	jQuery(".dynamicform_wrapper .item").each(function(index) {
		$("#labsamplerequest-" + index + "-lab_smple_sur_id").val($(ctrl).val());
	});
}

function set_date(ctrl) {
	var index = $(ctrl).attr('id').match(/\d+/)[0];
	var today = new Date();
    var day = today.getDate();
    var month = today.getMonth() + 1;
    var year = today.getFullYear();
    day = checkTime(day);
    month = checkTime(month);
	
	if($(ctrl).val() != '') {
		var startDate = day + "-" + month + "-" + year;
		if($("#labsamplerequest-" + index + "-lab_smple_resultdate").val() == '')
			$("#labsamplerequest-" + index + "-lab_smple_resultdate").datepicker("update", startDate);
	} else {
		$("#labsamplerequest-" + index + "-lab_smple_resultdate").datepicker("update", "");
	}
}

function result_change(ctrl) {
	var index = $(ctrl).attr('id').match(/\d+/)[0];
	$("#labsamplerequest-" + index + "-lab_smple_result").val($(ctrl).val());
	set_date(ctrl);
}


function enable_result(ctrl) {
	var today = new Date();
    var day = today.getDate();
    var month = today.getMonth() + 1;
    var year = today.getFullYear();
    day = checkTime(day);
    month = checkTime(month);
    ctrl = $(ctrl).find('input[type=checkbox]')[0];

	var index = $(ctrl).attr('id').match(/\d+/)[0];
	$("#labsamplerequest-" + index + "-lab_smple_date").prop("disabled", !$(ctrl).prop("checked"));
	$("#labsamplerequest-" + index + "-lab_smple_result").prop("disabled", !$(ctrl).prop("checked"));
	$("#labsamplerequest-" + index + "-results").prop("disabled", !$(ctrl).prop("checked"));
	$("#labsamplerequest-" + index + "-lab_smple_resultdate").prop("disabled", !$(ctrl).prop("checked"));

	if($(ctrl).prop("checked")) {
		var startDate = day + "-" + month + "-" + year;
		$("#labsamplerequest-" + index + "-lab_smple_date").datepicker("update", startDate);
	} else {
		$("#labsamplerequest-" + index + "-lab_smple_date").val("");
		$("#labsamplerequest-" + index + "-lab_smple_result").val("");
		$("#labsamplerequest-" + index + "-results").val("");
		$("#labsamplerequest-" + index + "-lab_smple_resultdate").val("");
	}
}

function results() {
	jQuery(".dynamicform_wrapper .item").each(function(index) {
		if($("#labsamplerequest-" + index + "-isspot").val() == 1) {
			$(".form-group.field-labsamplerequest-" + index + "-lab_smple_result").addClass('hidden');
			$(".form-group.field-labsamplerequest-" + index + "-results").removeClass('hidden');
		} else {
			$(".form-group.field-labsamplerequest-" + index + "-lab_smple_result").removeClass('hidden');
			$(".form-group.field-labsamplerequest-" + index + "-results").addClass('hidden');
		}
	});
}

function tests(ctrl) {
	var checkedVals = new Array();
	var index = 0;
	$(ctrl).find(':checkbox').each(function () {
		if($(this).is(':checked')) {
			checkedVals[index] = $(this).val();
			index++;
		}
	});
	val = checkedVals.join(",");
	// console.log(val);
	callUrl = $(ctrl).data('href');
	$.ajax({
		type: "post",
		url: callUrl,
		data: 'id='+checkedVals.join("','"),
		success: function(result){
			response = result;
			$(".datepicker").datepicker("destroy");
			if(result.length != 0) {
				$(".dynamicform_wrapper").show();
				$(".dynamicform_wrapper tbody").html("");
				$.each(result, function(index, obj) {
					// console.log(obj);
					$('.add-item').trigger('click');
				});
				addPicker(datefmt);
			} else {
				$(".dynamicform_wrapper").hide();
			}
		}
	});
}
JS;
$this->registerJs($headJS, View::POS_HEAD);

$js = <<<JS
    
	 $('#labsamplerequest-departments-ICC2').parent('label').hide();
	 $('#labsamplerequest-departments-ICC7').parent('label').hide();
	
	$('#labsamplerequest-lab_smple_part_id').on('select2:select', function (evt) {
		$.ajax({
			type: 'post',
			url: 'depajax',
			data: 'id='+$(this)[0].value,
			success: function(result) {
				var registration = result.registration;
				var labsamples = result.labsamples;
				var iscohort = result.iscohort;
				var isidu = result.isidu;
				var vldone = result.vldone;

				$('#labsamplerequest-departments [type=checkbox]').each(function(){
					var _this = $(this);
					
					if(registration.corfrm_q12 != 1 && registration.corfrm_q12 != 9 && (_this[0].value == 'ICC5' || _this[0].value == 'ICC6'))
						$(this).parent('label').hide();
					else
						$(this).parent('label').show();

					$(labsamples).each(function(index){
						var dep = labsamples[index].tests.lab_dept_code;
						if(_this.is(":visible")) {
							if(dep == _this[0].value) {
								_this.parent('label').hide();
							} else {
								_this.parent('label').show();
							}
						}
					});
				});

				if(registration.corfrm_q12 != 1 && registration.corfrm_q12 != 9) {
					$('#nursevisit-nursefrm_q1-1, #nursevisit-nursefrm_q1-3, #nursevisit-nursefrm_q1-4').prop('checked', false).prop('disabled', true);
				} else {
					$('#nursevisit-nursefrm_q1-1, #nursevisit-nursefrm_q1-3, #nursevisit-nursefrm_q1-4').prop('disabled', false);
				}

				if(iscohort == null) {
					$('#labsamplerequest-departments-ICC9').parent('label').hide();
				} else {
					$('#labsamplerequest-departments-ICC9').parent('label').show();
				}
				
				if(isidu == 1) {
					$('#labsamplerequest-departments-ICC2').parent('label').show();
					$('#labsamplerequest-departments-ICC7').parent('label').show();		
				} else {					
					$('#labsamplerequest-departments-ICC2').parent('label').hide();
					$('#labsamplerequest-departments-ICC7').parent('label').hide();
					
				}
				
				if(vldone == null) {
					$('#labsamplerequest-departments-ICC6').prop('checked', false).prop('disabled', false);
				} else {
					$('#labsamplerequest-departments-ICC6').prop('checked', true).prop('disabled', true);
				}
			}
		});
	});

jQuery(".dynamicform_wrapper").on("afterInsert", function(e, item) {
	jQuery(".dynamicform_wrapper .item").each(function(index) {
		$(this).attr('data-index', index);
		if($("#labsamplerequest-" + index + "-lab_smple_sur_id").val() == "") {
			$("#labsamplerequest-" + index + "-lab_smple_sur_id").val($("#labsamplerequest-lab_smple_sur_id").val());
			jQuery(this).find(':input').each(function() {
				switch(this.type) {
					case 'password':
					case 'text':
					case 'textarea':
					case 'file':
					case 'select-one':
					case 'select-multiple':
					case 'date':
					case 'number':
					case 'tel':
					case 'email':
						jQuery(this).val('');
					break;
					case 'checkbox':
					case 'radio':
						this.checked = false;
					break;
				}
			});
			$("#labsamplerequest-" + index + "-lab_smple_tst_id").val(response[index].lab_mapng_testmstr_id);
			$("#labsamplerequest-" + index + "-lab_smple_spcmn_id").val(response[index].specimens.lab_spcmn_code);
			$("#labsamplerequest-" + index + "-lab_smple_tst_id").closest("td").find("span").html(response[index].tests.lab_test_name);
			$("#labsamplerequest-" + index + "-lab_smple_spcmn_id").closest("td").find("span").html(response[index].specimens.lab_spcmn_name);
	    	$("#labsamplerequest-" + index + "-isspot").val(response[index].tests.lab_spot_test);
	    	if(response[index].tests.lab_spot_test == 1) {
	    		// console.log(response[index].testresults);
	    		var results = [];
	    		$.each(response[index].testresults, function(key,val){
	    			results.push(val);
	    		});
    			$("#labsamplerequest-" + index + "-results option").each(function(index) {
    				if($(this).val() != "" && $.inArray($(this).val(), results) < 0) {
    					$(this).remove();
    				}
    			});
				$(".form-group.field-labsamplerequest-" + index + "-lab_smple_result").addClass('hidden');
				$(".form-group.field-labsamplerequest-" + index + "-results").removeClass('hidden');
	    	} else {
				$(".form-group.field-labsamplerequest-" + index + "-lab_smple_result").removeClass('hidden');
				$(".form-group.field-labsamplerequest-" + index + "-results").addClass('hidden');
	    	}
    	}
    });
});

jQuery(".dynamicform_wrapper").on("beforeDelete", function(e, item) {
	// console.log($(item).find(':input').first().val());
	$("#labsamplerequest-delrec").val($(item).find(':input').first().val() + "," + $("#labsamplerequest-delrec").val());
});

jQuery(".dynamicform_wrapper").on("afterDelete", function(e) {
	// console.log(e);
    jQuery(".dynamicform_wrapper .panel-title-address").each(function(index) {
        jQuery(this).html("Address: " + (index + 1))
    });
});

JS;
$this->registerJs($js);
$this->registerJs("$('.datepicker').datepicker({autoclose: true, startDate: '01-01-1900', endDate: '0', format: '".strtolower(Yii::$app->formatter->dateFormat)."'});");
if($model->isNewRecord)
	$this->registerJs('$(".dynamicform_wrapper").hide()');
else
	$this->registerJs('$(".form-group.field-labsamplerequest-departments").hide(); results();');
?>

<div class="labsamplerequest-form">
	<div class="panel panel-default">
		<div class="panel-heading">
			
		</div>
		<div class="panel-body">
			<div class="row">
				<div class="col-lg-12">
					<?php
						// $form = ActiveForm::begin(['id' => 'dynamic-form1', 'options' => ['class' => 'form-horizontal']]);
						$form = ActiveForm::begin(['enableAjaxValidation' => true, 'id' => 'dynamic-form1', 'options' => ['class' => 'form-horizontal']]);
						$template = [
							'labelOptions' => ['class' => 'form-label'],
							'template' => '<div class="col-sm-5">{label}{hint}</div><div class="col-sm-4">{input}{error}</div>',
						];
						$htemplate = [
							'options' => ['tag' => false],
							'template' => '{input}'
						];
						$dynamictemplate = [
							// 'options' => ['tag' => false],
							'template' => '<div class="col-md-12">{input}{error}{hint}</div>'
						];
						$chklist_template = [
							'options' => ['class' => ($model->isNewRecord) ? 'form-group' : 'form-group hidden'],
							'labelOptions' => ['class' => 'form-label'],
							'template' => '<div class="col-sm-5">{label}{hint}</div><div class="col-sm-4 checkbox-list">{input}{error}</div>',
						];
					?>
					<?php // echo $form->errorSummary($model); ?>
					<?= Common::generateControl($form, $model, $template, 'lab_smple_sur_id', $Surveys, 'survey', 'getLabrequestPIDs') ?>
					<?= Common::generateControl($form, $model, $template, 'lab_smple_loc', $Locations, 'location', '', [Html::getInputId($model, 'lab_smple_sur_id')]) ?>
					<?= Common::generateControl($form, $model, $template, 'lab_smple_part_id', $PIDs, 'pid', '', [Html::getInputId($model, 'lab_smple_sur_id'), Html::getInputId($model, 'lab_smple_loc')]) ?>
					<?php if(!$model->isNewRecord): ?>
						<?= $form->field($model, 'lab_smple_acc_no', $template)->textInput(['disabled' => true, 'readonly' => true]) ?>
					<?php endif; ?>
					<?= $form->field($model, 'departments', $chklist_template)->checkboxList($Depts, ['onchange' => 'tests(this)', 'data-href' => Yii::$app->urlManager->createUrl(['/labsamplerequest/ajax'])]) ?>
					<?php DynamicFormWidget::begin([
						'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
						'widgetBody' => '.container-items', // required: css class selector
						'widgetItem' => '.item', // required: css class
						'limit' => 999, // the maximum times, an element can be cloned (default 999)
						'min' => 1, // 0 or 1 (default 1)
						'insertButton' => '.add-item', // css class
						'deleteButton' => '.remove-item', // css class
						'model' => $models[0],
						'formId' => 'dynamic-form1',
						'formFields' => [
							'lab_smple_id',
							'lab_smple_sur_id',
							'lab_smple_tst_id',
							'lab_smple_spcmn_id',
							'lab_smple_spcmn_clctd',
							'lab_smple_date',
							'lab_smple_result',
							'lab_smple_resultdate',
							'create_user',
							'update_user',
						],
					]); ?>
					<table class="table table-bordered container-items" border="0" cellpadding="0" cellspacing="0" align="center">
						<thead>
							<tr>
								<td class="col-md-3"><?= Html::activeLabel($model,'lab_smple_tst_id'); ?></td>
								<td class="col-md-2"><?= Html::activeLabel($model,'lab_smple_spcmn_id'); ?></td>
								<td class="col-md-1"><?= Html::activeLabel($model,'lab_smple_spcmn_clctd'); ?></td>
								<td class="col-md-2"><?= Html::activeLabel($model,'lab_smple_date'); ?></td>
								<td class="col-md-2"><?= Html::activeLabel($model,'lab_smple_result'); ?></td>
								<td class="col-md-2"><?= Html::activeLabel($model,'lab_smple_resultdate'); ?></td>
								<td class="hidden" align="center">
									<button type="button" class="add-item btn btn-success btn-xs"><i class="fa fa-plus"></i></button>
								</td>
							</tr>
						</thead>
						<tbody>
							<?php foreach ($models as $index => $modelAddress): ?>
								<tr class="item" data-index="<?= $index ?>">
									<td>
										<?= $form->field($modelAddress, "[{$index}]lab_smple_id", $htemplate)->hiddenInput()->label("") ?>
										<?= $form->field($modelAddress, "[{$index}]lab_smple_sur_id", $htemplate)->hiddenInput()->label("") ?>
										<?= $form->field($modelAddress, "[{$index}]lab_smple_tst_id", $htemplate)->hiddenInput()->label("") ?>
										<?= $form->field($modelAddress, "[{$index}]isspot", $htemplate)->hiddenInput(['value' => $modelAddress->isspot])->label("") ?>
										<?php
											if(isset($modelAddress->tests->lab_test_name))
												echo $modelAddress->tests->lab_test_name;
											else
												echo '<span>&nbsp;</span>';
										?>
									</td>
									<td>
										<?= $form->field($modelAddress, "[{$index}]lab_smple_spcmn_id", $htemplate)->hiddenInput()->label("") ?>
										<?php
											if(isset($modelAddress->specimens->lab_spcmn_name))
												echo $modelAddress->specimens->lab_spcmn_name;
											else
												echo '<span>&nbsp;</span>';
										?>
									</td>
									<td>
										<?= $form->field($modelAddress, "[{$index}]lab_smple_spcmn_clctd", $dynamictemplate)->checkboxList(["1" => ""], ['label' => null, 'onchange' => "enable_result(this)"]) ?>
									</td>
									<td>
										<?= $form->field($modelAddress, "[{$index}]lab_smple_date", $dynamictemplate)->textInput(['class' => 'form-control datepicker', "maxlength" => true, "disabled" => !($modelAddress->lab_smple_spcmn_clctd)]) ?>
									</td>
									<td>
										<?php
											if(!$model->isNewRecord) {
												$modelAddress->results = $modelAddress->lab_smple_result;
												$Labresults = Common::getLabresults($modelAddress->lab_smple_tst_id);
											}
										?>
										<?= $form->field($modelAddress, "[{$index}]results", $dynamictemplate)->dropDownList($Labresults, ['prompt'=>"Select", 'onchange' => "result_change(this)", "disabled" => !($modelAddress->lab_smple_spcmn_clctd)]) ?>
										<?= $form->field($modelAddress, "[{$index}]lab_smple_result", $dynamictemplate)->textInput(["maxlength" => true, 'onchange' => "set_date(this)", "disabled" => !($modelAddress->lab_smple_spcmn_clctd)]) ?>
										<?= $form->field($modelAddress, $modelAddress->isNewRecord ? "[{$index}]create_user" : "[{$index}]update_user", $htemplate)->hiddenInput(['value' => yii::$app->user->identity->id])->label("") ?>
									</td>
									<td>
										<?= $form->field($modelAddress, "[{$index}]lab_smple_resultdate", $dynamictemplate)->textInput(['class' => 'form-control datepicker', "maxlength" => true, "disabled" => !($modelAddress->lab_smple_spcmn_clctd)]) ?>
									</td>
									<td class="hidden" align="center">
										<button type="button" class="remove-item btn btn-danger btn-xs"><i class="fa fa-minus"></i></button>
									</td>
								</tr>
							<?php endforeach; ?>
						</tbody>
					</table>
					<?php DynamicFormWidget::end(); ?>
					<?= $form->field($model, "delrec", $htemplate)->hiddenInput(['value' => ""])->label("") ?>
					<?= $form->field($model, 'status', $htemplate)->hiddenInput(['value' => 1])->label("") ?>
					<?= $form->field($model, $model->isNewRecord ? 'create_user' : 'update_user', $htemplate)->hiddenInput(['value' => yii::$app->user->identity->id])->label("") ?>
					<div class="form-group">
						<div class="col-sm-offset-5 col-sm-7">
							<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
							<?= Html::a('Cancel', ['/'.Yii::$app->controller->id], ['class' => 'btn btn-default']) ?>
						</div>
					</div>
					<?php ActiveForm::end(); ?>
				</div>
				<!-- /.col-lg-6 (nested) -->
			</div>
			<!-- /.row (nested) -->
		</div>
		<!-- /.panel-body -->
	</div>
	<!-- /.panel -->
</div>