<?php
// HTML ELEMENTS

function fixElement(&$element,$group=false)
{
	if(isset($element['alc']) && $element['alc']!=ALC())
	{
		$element['attrib'] = 'disabled';
	}
	$element['name'] = $element['name']??'';
	$element['basename'] = $element['name'];
	$element['dbtype'] = $element['dbtype']??'varchar';
	$element['type'] = $element['type']??'text';
	$element['pattern'] = $element['pattern']??'';
	$element['help'] = $element['help']??'';
	$element['target'] = $element['target']??false;
	$element['label'] = t_($element['label']??$element['name']);
	$element['lenght'] = $element['lenght']??'255';
	$element['numeric-max'] = $element['numeric-max']??'999999';
	$element['fields'] = $element['fields']??'';
	$element['class'] = $element['class']??'';
	$element['error-mesage'] = $element['error-mesage']??'';
	$element['attrib'] = $element['attrib']??'';
	$element['data_list'] = $element['data_list']??array();
	$element['source'] = $element['source']??false;
	$element['val'] = $element['val']??array('');
	$element['multiple'] = $element['multiple']??false;
	$element['indexed'] = $element['indexed']??false;
	$element['tab'] = $element['tab']??1;
	$element['id'] = $group.'_'.$element['name'];
	$element['class'] .= ' '.$element['id'];
	if(!is_array($element['data_list'])) $element['data_list'] = array($element['data_list']);
	if(!is_array($element['val'])) $element['val'] = array($element['val']);
	if($element['source'])	{
		$element['class']  .= ' ajax-control';
		$element['attrib'] .= ' source="get_'.$element['target'].'s"';
	}
	if($group)	{
		$element['name'] = $group.'['.$element['name'].']';	}
	if($element['multiple'])	{
		$element['attrib'] .= ' multiple="multiple" ';
		$element['name'] .= '[]';
	}
	return $element;
}

function getFormElement($element,$group='',$tab=1,$formType='right')
{
	if(!fixElement($element,$group)) return '';
	//print_r($element);
	if($element['type']=='none') return '';
	if($tab!=$element['tab'])
	{
		return '';
	}
	$labelclass= $formType=='right'?'col-sm-3':'';
	$divclass= $formType=='right'?'col-sm-9':'col-sm-12';
	$hidden = $element['type']=='hidden'?'display:none;':'';
	$icon = $element['icon']??'';
	$html  =  '<div class="form-group has-feedback" style="'.$hidden.'">';
	$html .=  '<label class="'.$labelclass.' control-label">'.$element['label'].'</label>';
	$html .=  '<div class="'.$divclass.'">';
	$html .=  call_user_func_array('createElement'.$element['type'], array($element,$labelclass,$divclass, $group));
	$html .= '<i class="icon icon-'.$icon.' form-control-feedback"></i>';
	
	if($element['help']!='')$html .= '<span class="help-block">'.t_($element['help']).'</span>';
	
	$html .= '</div> </div>';
	echo $html;
}
/**
Formlar için text temelli inputlar
**/

function createElementnone($element,$labelclass='',$divclass='', $group='basic')
{
	return false;
}

function createElementtext($element,$labelclass='',$divclass='', $group='basic')
{
	if($element['dbtype']=='int')
	{
		$element['type']='number';
		$element['attrib'] .= ' min="0" max="'.pow(10,$element['lenght']).'"';
	}
	return '<input id="'.$element['id'].'" name="'.$element['name'].'" type="'.$element['type'].'" class="form-control '.$element['class'].'" '.$element['attrib'].' error-mesage="'.$element['error-mesage'].'" value="'.current($element['val']).'" maxlength="'.$element['lenght'].'">';
}


function createElementnumeric($element,$labelclass='',$divclass='', $group='basic')
{
	//$max = pow(10,$element['lenght']);
	$html = '<input id="'.$element['id'].'" name="'.$element['name'].'" type="text" class="form-control '.$element['class'].'" '.$element['attrib'].' error-mesage="'.$element['error-mesage'].'" value="'.current($element['val']).'" maxlength="'.($element['numeric-max']).'"  onkeyup="this.value = minmax(this.value, 0, '.$element['numeric-max'].')"  >';
	if($element['pattern']!='')$html .="<script>$('#".$element['id']."').formatter({ pattern: '".$element['pattern']."' });</script>";
	return $html;
}


function createElementhidden($element,$labelclass='',$divclass='', $group='basic')
{
	return createElementtext($element,$labelclass,$divclass);
}

function createElementemail($element,$labelclass='',$divclass='', $group='basic'){
	return createElementtext($element,$labelclass,$divclass);
}

function createElementpassword($element,$labelclass='',$divclass='', $group='basic')
{
	return createElementtext($element,$labelclass,$divclass);
}

function createElementdate($element,$labelclass='',$divclass='', $group='basic')
{
	$date = new DateTime();
	if(current($element['val'])!='0') $date = new DateTime(current($element['val']));
	$html =  '<input id="'.$element['id'].'" name="'.$element['name'].'" type="text" class="form-control '.$element['class'].'" '.$element['attrib'].' error-mesage="'.$element['error-mesage'].'" value="" maxlength="'.$element['lenght'].'">';
	$html .=  "<script>
				$('#".$element['id']."').pickadate({
				monthsFull: ['Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık'],
				weekdaysShort: ['Paz', 'Pzt', 'Sal', 'Çar', 'Per', 'Cum', 'Cmt'],
				labelMonthNext: 'Sonraki',
				labelMonthPrev: 'Önceki',
				labelMonthSelect: 'Pick a month from the dropdown',
				labelYearSelect: 'Pick a year from the dropdown',
				selectMonths: true,
				selectYears: true,
				today: 'Bugün',
				clear: 'Temizle',
				close: 'Kapat',
				formatSubmit: 'yyyy-mm-dd',
				/*format:'yyyy-mm-dd',*/
				onStart: function()
				{
					var picker = this;
					picker.set('select', '".$date->format('Y-m-d')."', { format: 'yyyy-mm-dd' });
				}
			});
		   </script>";
	return $html;
}

function createElementdisabled($element,$labelclass='',$divclass='', $group='basic')
{
	return '';
}

function createElementselect($element,$labelclass='',$divclass='', $group='basic'){
	return '<select id="'.$element['basename'].'" name="'.$element['name'].'" source="'.$element['source'].'" data-val="'.current($element['val']).'" data-placeholder="'.$element['label'].'" class="select source-'.!empty($element['source']).' '.$element['class'].'"  '.$element['attrib'].' target="'.$element['target'].'"></select>';
}

function createElementyesno($element,$labelclass='',$divclass='', $group='basic'){
	$html = '<select id="'.$element['basename'].'" name="'.$element['name'].'" source="'.$element['source'].'" data-val="'.current($element['val']).'" data-placeholder="'.$element['label'].'" class="select-fixed-single">';

	if(current($element['val']))	
	{
		$html .= '<option value="1" selected>'.t_('Yes').'</option>';
		$html .= '<option value="0" >'.t_('No').'</option>';
	} else {
		$html .= '<option value="1" >'.t_('Yes').'</option>';
		$html .= '<option value="0" selected>'.t_('No').'</option>';
	}
	return $html .='</select>';
}

function createElementdataselect($element,$labelclass='',$divclass='', $group='basic'){
	$html = '<select id="'.$element['basename'].'" name="'.$element['name'].'" source="'.$element['source'].'" data-val="'.current($element['val']).'" data-placeholder="'.$element['label'].'" class="select '.$element['class'].'" '.$element['attrib'].'>';
	$html .= '<option value="" >&nbsp</option>';
	foreach($element['data'] as $key=>$val)	{
		if(is_numeric($key) && !$element['indexed']) $key = $val;
		$selected = '';
		if(is_array($element['val']))
		{
			if(in_array($key, $element['val']))$selected = 'selected';
		} else {
			if(current($element['val']) == $key )$selected = 'selected';
		}
		$html .= '<option value="'.$key.'" '.$selected.'>'.t_($val).'</option>';
		
	}
	return $html .='</select>';
}

function createElementsearch($element,$labelclass='',$divclass='', $group='basic'){
	//$element['class'] .= ' select-remote-data';
	$html = '<select id="'.$element['basename'].'" name="'.$element['name'].'" source="search_'.$element['source'].'" data-val="'.current($element['val']).'" data-placeholder="'.$element['label'].'" class="'.$element['class'].'"  '.$element['attrib'].' ></select>';
	$html .='<script>// Initialize
$.ajax({
  url: site_url+"ajax/search_'.$element['source'].'?sender='.current($element['val']).'",
  success: function(data) {
    $("#'.$element['basename'].'").html(data);
  }
});
    $("#'.$element['basename'].'").select2({
        ajax: {
            url: 
function (params) {
			  return site_url+"ajax/" +  $(this).attr("source");
			},
            /*dataType: "json",*/
            delay: 250,
            data: 
function (params) {
                return {
                    q: params.term, // search term
                    page: params.page
                };
            },
            processResults: 
function (data, params) {
                // parse the results into the format expected by Select2
                // since we are using custom formatting functions we do not need to
                // alter the remote JSON data, except to indicate that infinite
                // scrolling can be used
				data =  jQuery.parseJSON(data);
				console.log(data);
                params.page = params.page || 1;
                return {
                    results: data.items,
                    pagination: {
                        more: (params.page * 30) < data.total_count
                    }
                };
            },
            cache: true
        },
        //escapeMarkup: 
function (markup) { return markup; }, // let our custom formatter work
        minimumInputLength: 2,
        //templateResult: formatRepo, // omitted for brevity, see the source of this page
        //templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
    });</script>';
 	return $html;
}


function createElementmultifield($element,$labelclass='',$divclass='', $group='basic'){
	$fields = explode(',',$element['fields']);
	$html = '';
	foreach($fields as $field)	{
		$checked = '';
		if(isset($element['val'][$field]) && $element['val'][$field]==1) $checked = 'checked';
		$html .='<div class="checkbox">
					<label>
						<input type="hidden" id="'.$element['basename'].'" name="'.$group.'['.$field.']"  value="0">
						<input type="checkbox" class="styled control-primary" name="basic['.$field.']"  value="1" '.$checked.'>'.t_($field).'</label>
				</div>';
	}

	$html .= '';

	return $html ;
}


function createElementmultiple($element,$labelclass='',$divclass='', $group='basic'){
	$pratikDb = new pratikDb();
	$pratikDb->connect();
	sort($element['val']);
	$labels=array();
	if($element['val'])	{
		foreach($element['val'] as $val)
		{
			$labels[]= $pratikDb->get_($element['basename'] ,'categoryName', "categoryCode='".$val."'") ;
		}
	}
	$pratikDb->disconnect();

	return '<select id="'.$element['basename'].'" name="'.$element['name'].'[]" data-placeholder="'.$element['label'].'" class="select-multiple" multiple="multiple" ></select>
	<span><ul class="breadcrumb"><li>'.implode('<li></li>',$labels).'</ul></span>';
}

function createElementfiller($element,$labelclass='',$divclass='', $group='basic'){
	return '<select id="'.$element['basename'].'" name="'.$element['name'].'" source="'.$element['source'].'" target="'.$element['target'].'" data-val="'.current($element['val']).'" '.$element['attrib'].' data-placeholder="'.$element['label'].'" class="select filler" ></select>';
}

function createElementtextarea($element,$labelclass='',$divclass='', $group='basic'){
	return '<textarea id="'.$element['id'].'" name="'.$element['name'].'" type="'.$element['type'].'" class="form-control '.$element['class'].'" '.$element['attrib'].' error-mesage="'.$element['error-mesage'].'" maxlength="'.$element['lenght'].'">'.current($element['val']).'</textarea>';
}

function createElementtexteditor($element,$labelclass='',$divclass='', $group='basic')
{
	return '<textarea id="'.$element['id'].'" name="'.$element['name'].'" type="'.$element['type'].'" class="form-control wysihtml5 wysihtml5-default '.$element['class'].'" '.$element['attrib'].' error-mesage="'.$element['error-mesage'].'" maxlength="'.$element['lenght'].'">'.current($element['val']).'</textarea>';
}

function createElementimage($element,$labelclass='',$divclass='', $group='basic')
{
	$url = current($element['val']);
	$html = getImg($url,64,64,'file-image','id="img_'.$element['id'].'"');
	$html .= '<div class="file-container" style="display:none;" >
				<input type="file" name="'.$element['id'].'" class="file-input-ajax">
			  </div>';
	$html .= '<input id="'.$element['id'].'" name="'.$element['name'].'" type="hidden" class="form-control '.$element['class'].'" '.$element['attrib'].' error-mesage="'.$element['error-mesage'].'" value="'.current($element['val']).'" maxlength="'.$element['lenght'].'">';

	return $html;
}

/**
Data Table
*/


function make_datatable($id, $rows, $state=1, $elements=array()) 
{
	foreach($elements as $key => $element)	{
		$elements['key'] = fixElement($element); 
	}
	$th='';
	$ths= explode(';',$rows);
	$ths[] = 'İşlem';
	foreach($ths as $row)	{
		$th.='<th>'.(isset($elements[$row])?t_($elements[$row]['label']):'').'</th>';
	}

	$function = $id;
	$table='
	
	<table id="'.$id.'" class="table datatable-button-html5-basicx table-hover" cellspacing="0" width="100%">
        <thead>
            <tr class="bg-blue">
                <th></th>'.$th.'
            </tr>
        </thead>
        <tfoot>
            <tr class="bg-grey-300">
                <th></th>'.$th.'
            </tr>
        </tfoot>
    </table>
	';
	echo $table.'
	<script>
	var ajaxDataUrl = "'.getSubUrl().'/datatable/get_datatable?f='.$function.'&s='.$state.'&tr='.$rows.'";

	$(document).ready(function() {
    $.extend( $.fn.dataTable.defaults, {
        autoWidth: false,
        dom: \'<"datatable-header"fBl><"datatable-scroll-wrap"t><"datatable-footer"ip>\',
        language: {
            search: \'<span>Filter:</span> _INPUT_\',
            searchPlaceholder: \'Type to filter...\',
            lengthMenu: \'<span>Show:</span> _MENU_\',
            paginate: { "first": "First", "last": "Last", "next": "&rarr;", "previous": "&larr;" }
        }
    });
	   $("#'.$id.'").DataTable({
			"processing": true,
			"serverSide": true,
			/*"pagingType": "input",*/
				"ajax": ajaxDataUrl,
	        buttons: {            
            dom: {
                button: {
                    className: "btn btn-default"
                }
            },
            buttons: [
                /*"copyHtml5",*/
                "excelHtml5",
                /*"csvHtml5",*/
                "pdfHtml5"
            ]
        }
    } );

	$("body").on("change", "#extraFilter", function(){
		extraFilter = "&extraFilter="+$(this).attr("field")+"="+ $(this).val();
		dataTable.ajax.url( ajaxDataUrl+ extraFilter).load();
		console.log(extraFilter);
	  });

	} );
	</script>';
	
}

function make_table($basicid, $module, $rows=array(), $fields='', $title='Tablo', $rowclass='id') 
{
	$fields = explode(';',$fields);
	$html = '<div class="panel panel-flat">
				<div class="panel-heading">
					<h5 class="panel-title">'.$title.'</h5>
				</div>
				<div class="table-responsive">
					<table class="table table-hover">
						<thead>
							<tr><th>#</th>';
	$baslik ='';
	foreach($fields as $field)
	{
		$baslik .= '<th class="table-'.$field.'">'.t_($field).'</th>';
	}
	$baslik .='<th>İşlemler</th></tr>';
	
	$body ='';
	if(is_array($rows))
	{
		foreach($rows as $key => $row)
		{
			$body .= '<tr class="row-'.$row[$rowclass].'"><td>'.($key+1).'</td>';
			foreach($fields as $field)
			{
				$value = isset($row[$field])?$row[$field]:'';
				$body .= '<th>'.$value.'</th>';
			}
			$body .= '<th><a class="confirm" href="'.getSubUrl($module).'/delete_hesap?id='.$basicid.'&hesap_id='.$row['id'].'" message="Hesap kaydının silinmesini onaylıyor musunuz?">'.t_('Sil').'</a></th></tr>';

		}
		
	} 
	$html .= $baslik.' </thead><tbody>'.$body.'</tbody></table></div></div>';
	
	return $html;
}

