<?php

use app\base\Common;
use yii\web\View;
use yii\helpers\Url;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\widgets\ActiveForm;
use kartik\select2\Select2;
use rmrevin\yii\fontawesome\FA;
use wbraganca\dynamicform\DynamicFormWidget;

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

$Surveys = Common::getSurvey();
$Locations = Common::getLocations();
$PIDs = Common::getNurseServicePIDs("cd4test");
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::getNurseServicePIDs("cd4test", Yii::$app->params['SURVEY'], Yii::$app->params['LOCATION']);
}

$headJS = "
    var datefmt = '".strtolower(Yii::$app->formatter->dateFormat)."';
	function survey_change(ctrl) {
		// console.log($(ctrl).val());
		jQuery('.dynamicform_wrapper .item').each(function(index) {
			$('#cd4-' + index + '-cd4_test_survey').val($(ctrl).val());
	    });
	}
	function pid_change(ctrl) {
		var pid = $(ctrl).val();
		var link = $('#pid-list').data('link') + pid;
		$('#pid-list').attr('link', link);
		$('#pid_list').load(link);
		var link = $('#pid-info').data('link') + pid;
		$('#pid-info').removeClass('hidden');
		$('#pid-info').attr('link', link);
		jQuery('.dynamicform_wrapper .item').each(function(index) {
			$('#cd4-' + index + '-cd4_test_part_id').val($(ctrl).val());
	    });
	}
";
$this->registerJs($headJS, View::POS_HEAD);

$JS = "
	$('.datepicker').datepicker({autoclose: true, startDate: '01-01-1900', endDate: '0', format: '".strtolower(Yii::$app->formatter->dateFormat)."'});
	
	$('#cd4-cd4_test_part_id').on('select2:select', function (evt) {
		var pid = $(this)[0].value;
		if(pid != '') {
			var link = $('#pid-list').data('link') + pid;
			$('#pid-list').attr('link', link);
			$('#pid_list').load(link);
			var link = $('#pid-info').data('link') + pid;
			$('#pid-info').removeClass('hidden');
			$('#pid-info').attr('link', link);
			jQuery('.dynamicform_wrapper .item').each(function(index) {
				$('#cd4-' + index + '-cd4_test_survey').val($('#cd4-cd4_test_survey').val());
				$('#cd4-' + index + '-cd4_test_loc').val($('#cd4-cd4_test_loc').val());
				$('#cd4-' + index + '-cd4_test_part_id').val(pid);
		    });
		}
	});

	$('#cd4-cd4_test_part_id').on('select2:unselect', function (evt) {
		$('#pid_list').html('');		
	});

	$('#cd4-cd4_test_q2').change(function(){
		// $('div.form-group').show();
		$('div.help-block').html('');
		$('div.form-group').removeClass('has-success').removeClass('has-error');
		if($(this).val() == 1) {
			$('div.form-group.field-cd4-cd4_test_q3, div.form-group.field-cd4-cd4_test_q4, div.form-group.field-cd4-cd4_test_q5, div.form-group.field-cd4-cd4_test_q6').addClass('required').show();
			$('.dynamicform_wrapper').show();
		} else {
			$('div.form-group.field-cd4-cd4_test_q3, div.form-group.field-cd4-cd4_test_q4, div.form-group.field-cd4-cd4_test_q5, div.form-group.field-cd4-cd4_test_q6').removeClass('required').hide();
			$('.dynamicform_wrapper').hide();
			
			$('#cd4-cd4_test_q3, #cd4-cd4_test_q4, #cd4-cd4_test_q5, #cd4-cd4_test_q6').val('');
		}
	});
	// $('#cd4-cd4_test_q1, #cd4-cd4_test_q2').trigger('change');
	$('#cd4-cd4_test_q2').trigger('change');
";

$this->registerJs($JS);

$js = <<<JS
jQuery(".dynamicform_wrapper").on("afterInsert", function(e, item) {
    jQuery(".dynamicform_wrapper .item").each(function(index) {
    	if($("#cd4-" + index + "-cd4_test_survey").val() == "") {
			$('#cd4-' + index + '-cd4_test_survey').val($("#cd4-0-cd4_test_survey").val());
			$('#cd4-' + index + '-cd4_test_part_id').val($("#cd4-0-cd4_test_part_id").val());
			$('#cd4-' + index + '-cd4_test_loc').val($("#cd4-0-cd4_test_loc").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;
			//     }
			// });
    	}
    });
    $(".datepicker").datepicker("destroy");
	addPicker(datefmt);
});

jQuery(".dynamicform_wrapper").on("beforeDelete", function(e, item) {
	// console.log($(item).find(':input').first().val());
	$("#cd4-delrec").val($(item).find(':input').first().val() + "," + $("#cd4-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);
?>

<div class="cd4-form">
	<div class="panel panel-default">
		<div class="panel-heading">
			
		</div>
		<div class="panel-body">
			<div class="row">
				<div class="col-lg-12">
					<?php
						$ajaxdata['cd4_test_part_id'] = '';
						// $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>',
						];
						$template_icon = [
							'labelOptions' => ['class' => 'form-label'],
							'template' => '<div class="col-sm-5">{label}{hint}</div><div class="col-sm-4">{input}{error}</div><a id="pid-info" class="btn btn-warning hidden"  href="#" link="'.Url::to(['getlist', 'pid' => ""]).'" header="List" data-link="'.Url::to(['getlist', 'pid' => ""]).'" data-toggle="modal" data-target="#modal-popup">'.FA::icon('info-circle').'</a><a id="pid-list" class="btn btn-warning hidden" href="#" link="'.Url::toRoute(['/cd4', 'ajaxload' => true, 'pagesize' => 6, 'Cd4Search' => $ajaxdata]).'" header="List" data-link="'.Url::toRoute(['/cd4', 'ajaxload' => true, 'pagesize' => 6, 'Cd4Search' => $ajaxdata]).'" data-toggle="modal" data-target="#modal-popup">'.FA::icon('info-circle').'</a>',
						];
						$htemplate = [
							'options' => ['tag' => false],
							'template' => '{input}'
						];
						$dynamictemplate = [
							// 'options' => ['tag' => false],
							// 'template' => '<div class="col-md-12">{input}{error}{hint}</div>'
							'template' => '<div class="col-sm-12">{label}{hint}</div><div class="col-sm-12">{input}{error}</div>',
						];
					?>
					<?php // echo $form->errorSummary($model); ?>
					<?= Common::generateControl($form, $model, $template, 'cd4_test_survey', $Surveys, 'survey', 'getNurseServicePIDs', 'cd4test') ?>
					<?= Common::generateControl($form, $model, $template, 'cd4_test_loc', $Locations, 'location', '', [Html::getInputId($model, 'cd4_test_survey')]) ?>
					<?= Common::generateControl($form, $model, $template_icon, 'cd4_test_part_id', $PIDs, 'pid', '', [Html::getInputId($model, 'cd4_test_survey'), Html::getInputId($model, 'cd4_test_loc')]) ?>
					<?= $form->field($model, 'cd4_test_q1', $template)->dropDownList($model->q1, ['prompt'=>'Select']); ?>
					<?= $form->field($model, 'cd4_test_q2', $template)->dropDownList($model->q2, ['prompt'=>'Select']); ?>
					<?php if(!$model->isNewRecord): ?>
						<?= $form->field($model, 'cd4_test_q3', $template)->textInput(['class' => 'form-control datepicker']) ?>
						<?= $form->field($model, 'cd4_test_q4', $template)->textInput(['maxlength' => true, 'data-min' => 0, 'data-max' => 1499, 'data-msg' => 'Please double-check that this answer is correct']) ?>
						<?= $form->field($model, 'cd4_test_q5', $template)->dropDownList($model->q5, ['prompt'=>'Select']); ?>
						<?= $form->field($model, 'cd4_test_q6', $template)->dropDownList($model->q6, ['prompt'=>'Select']); ?>
					<?php else: ?>
						<div id="pid_list" class="row-fluid popup"></div>
						<?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' => [
								'cd4_test_survey',
								'cd4_test_part_id',
								'cd4_test_q3',
								'cd4_test_q4',
								'cd4_test_q5',
								'cd4_test_q6',
								'create_user',
								'update_user',
							],
						]); ?>
						<?php // echo $form->errorSummary($models); ?>
						<table class="table table-bordered container-items" border="0" cellpadding="0" cellspacing="0" align="center">
							<thead>
								<tr>
									<td><?= Html::activeLabel($model,'cd4_test_q3'); ?></td>
									<td><?= Html::activeLabel($model,'cd4_test_q4'); ?></td>
									<td><?= Html::activeLabel($model,'cd4_test_q5'); ?></td>
									<td><?= Html::activeLabel($model,'cd4_test_q6'); ?></td>
									<td align="center">
										<?php if($model->isNewRecord): ?>
											<button type="button" class="add-item btn btn-success btn-xs"><i class="fa fa-plus"></i></button>
										<?php endif; ?>
									</td>
								</tr>
							</thead>
							<tbody>
								<?php foreach ($models as $index => $modelAddress): ?>
									<tr class="item">
										<td>
											<?= $form->field($modelAddress, "[{$index}]cd4_test_id", $htemplate)->hiddenInput()->label("") ?>
											<?= $form->field($modelAddress, "[{$index}]cd4_test_survey", $htemplate)->hiddenInput()->label("") ?>
											<?= $form->field($modelAddress, "[{$index}]cd4_test_part_id", $htemplate)->hiddenInput()->label("") ?>
											<?= $form->field($modelAddress, "[{$index}]cd4_test_loc", $htemplate)->hiddenInput()->label("") ?>
											<?= $form->field($modelAddress, "[{$index}]cd4_test_q3", $dynamictemplate)->textInput(['class' => 'form-control datepicker'])->label("") ?>
										</td>
										<td>
											<?= $form->field($modelAddress, "[{$index}]cd4_test_q4", $dynamictemplate)->textInput(['maxlength' => true, 'data-min' => 0, 'data-max' => 1499, 'data-msg' => 'Please double-check that this answer is correct'])->label("") ?>
										</td>
										<td>
											<?= $form->field($modelAddress, "[{$index}]cd4_test_q5", $dynamictemplate)->dropDownList($model->q5, ['prompt'=>'Select'])->label("") ?>
										</td>
										<td>
											<?= $form->field($modelAddress, "[{$index}]cd4_test_q6", $dynamictemplate)->dropDownList($model->q6, ['prompt'=>'Select'])->label("") ?>
											<?= $form->field($modelAddress, $modelAddress->isNewRecord ? "[{$index}]create_user" : "[{$index}]update_user", $htemplate)->hiddenInput(['value' => yii::$app->user->identity->id])->label("") ?>
										</td>
										<td 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("") ?>
					<?php endif; ?>
					<?= $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>