<?php

ini_set("display_errors","1");

include_once ("_dirinfo.php");

include_once (PATH_TO_ROOT."mystery/init.php");
require_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');



if ($_POST['id_visit']) {
	$sql = " SELECT id, id_sup, id_project,idLab FROM ".DB_WARPIT_MYSTERY."._Visits WHERE id = ".$_POST['id_visit'];
	$res = $db->SQLexecute($sql);
	$zad = $db->fetchAssoc($res);
	
	// table header, take group name
	$additionalTableTitel = ", ".$zad['idLab'];
	 
	if ($zad['id_project']) {
		$idProject = $zad['id_project'];
		$sql = "SELECT id_structure FROM ".DB_WARPIT_MYSTERY."._Visits WHERE id_sup = ".$zad['id_sup'];
		$res = $db->SQLexecute($sql);
		while ($zad = $db->fetchAssoc($res)) $records[] = $zad['id_structure'];
		
		//  for table header I get group name of Visit, because in visits item was selected
		$sql = "SELECT idLab FROM ".DB_WARPIT_MYSTERY."._Visits WHERE id = ".$zad['id_sup'];
		$res = $db->SQLexecute($sql);
		$zad = $db->fetchAssoc($res);
		$additionalTableTitel = ", ".$zad['idLab'];
		
	} else {
		$sql = "SELECT id_structure, id_project FROM ".DB_WARPIT_MYSTERY."._Visits WHERE id_sup = ".$zad['id'];
		$res = $db->SQLexecute($sql);
		while ($zad = $db->fetchAssoc($res)) {
			$idProject = $zad['id_project'];
			$records[] = $zad['id_structure'];
		}
	}
} else {

	$idProject = $_POST['id_project'];
	$idRecord = $_POST['id_record'];
	if ($idRecord) {
		$sql = "SELECT idLab FROM ".DB_WARPIT_MYSTERY."._Visits WHERE id_structure = ".$idRecord." AND id_project = ".$idProject;
		//echo $sql;
		$res = $db->SQLexecute($sql);
		$zad = $db->fetchAssoc($res);
		
		$additionalTableTitel = ", ".$zad['idLab'];
	}
}


$tableName = $db->get('_Projects',$idProject,'proj_name',DB_WARPIT_WEBCATI_BASE);

$reqUrl = "_forms/ajax.mysteryShopping.php";

if ($records) {
	
	$record = $db->get($tableName.'_structure',"id IN (".implode(",",$records).")"); 
	if ($_POST['id_visit']) $title = $languagePack['visit_total_report']; else 	$title = $languagePack['total_report'];
	
	
} elseif($idRecord) {
	$record = $db->get($tableName.'_structure',$idRecord);
	//var_dump($record);
	$title = $languagePack['pojedinacni_izvestaji'];
}
else 
{
	$record = $db->get($tableName.'_structure',"flag_bad = 101");
	if(!$record)
	{
		echo "Ext.Msg.alert('Warning','No records available!')";
		exit;
	}
	$title = $languagePack['total_report'];
}
$db->ChangeDatabase(DB_WARPIT_WEBCATI);

$sql= "SELECT * FROM $tableName"."_mystery";
$res = $db->SQLexecute($sql);
while ($row=$db->fetchAssoc($res) )
{
	$key = $row['id_question'];
	if($row['id_answer'])
		$key .= '_'.$row['id_answer'];
	if($row['id_legend'])
		$key .= '_'.$row['id_legend'];
	$scores[$key] = $row['sc_value'];
}

$folderScores = array();
$mainLevelArray = array();
function labelsFunction($string)
{
	
	$l = strlen($string);
	$cut = 40;
	for($i=$cut;$i<$l;$i+=40)
	{
		$pos = strpos($string,' ',$i);
		if($pos === false)
		{
			break;
		}
		$string[$pos] = "\n";
		
	}
	
	return ucfirst(( mb_strtolower( $string,'UTF-8' )));	
	
}

include("calculator.php");


unset ($folderScores[0]);
$outputTotal .= "
<style type=\"text/css\">
table {
	border-collapse: collapse;
}

.report-table {
    font-family: \"Lucida Sans Unicode\",\"Lucida Grande\",Sans-Serif;
    font-size: 10px;
    margin: 20px;
    text-align: left;
    width: 95%;
}
.report-table th {
	border: 1px solid #fff;
    color: #fff;
    font-size: 14px;
    font-weight: bold;
    padding: 12px 15px;
	background: #00B0F0;
	text-align:center;
}
.report-table td {
    font-size: 13px;
    border: 1px solid #e0e0e0;
    color: #666699;
    padding: 10px 15px;
	text-align:center;
}
.report-table td:first-child {
	text-align:left;
	font-size: 14px;
	font-weight: bold;

}

.report-table th:first-child {
	text-align:left;
	width:700px;
}

/*.report-table tr:hover td {
    background: none repeat scroll 0 0 #f4f4f4;
    color: #333399;
    
}*/
.zaprti {
	display : none;
}
h2 {
	font-family: \"Lucida Sans Unicode\",\"Lucida Grande\",Sans-Serif;
    font-size: 22px;
    margin-left: 20px;
    text-align: left;
    
}
</style>
<h2>".$tableName.$additionalTableTitel."</h2>
<div class=\"report-table\">
<table width=100%><thead>
<tr>
<th >Atributi za ocenjivanje</th>
<th >Maksimalan<br>broj poena</th>
<th >Postignuce</th>
<th>Nedostatak</th>
<th >Postignuće<br>(%)</th>
<th >Nedostatak<br>(%)</th>
</tr>
</thead>
<tbody>";
//print_r($folderScores); exit;
foreach ($folderScores as $qId => $frdb) {
	
	$poz = $frdb['pos'];
	$neg = $frdb['neg'];
	unset($bckColor);
	if($frdb['subFolder'])
		{
			
			foreach ($frdb['subFolder'] as $subFldId) {
				$subFld = $folderScores[$subFldId];
				$poz += $subFld['pos'];
				$neg += $subFld['neg'];;
			}
			
		}
	$max = ($poz + $neg );
	
	if(in_array($qId,$mainLevelArray))
	{
		$bckColor = 'bgcolor=#E0E0E0';
		$totalPoz += $poz;
		$totalNeg += $neg;
		if($max)
		{
			
			$graphData[$qId]['label'] = $frdb['name'];
			$graphData[$qId]['checked'] = true;
			$graphData[$qId]['gLabel'] = labelsFunction( $frdb['name'] );
	
//			$data1y[] = round($poz/$max,2)*100;
//			$data2y[] = round($neg/$max,2)*100;
			$bgrg = round($poz/$max,2)*100;
			$graphData[$qId]['data1y'] = $bgrg;
			$graphData[$qId]['data2y'] = 100-$bgrg;
		}
		$classTd = "glavni";
	} else {
		$classTd = "glavniSub";
		$bckColor = 'bgcolor=#f4f2f2';
	}
			
		if(!$poz) $poz = '&nbsp;';
		if(!$neg) $neg = '&nbsp;';
	
		$outputTotal .= "<tr $bckColor style=\"cursor: pointer\" class=\"".$classTd."\" id=\"area_".$qId."\">";
		$outputTotal .= "<td style=\"border-color:white\">".$frdb['name']."</td>";
	
		$outputTotal .= "<td style=\"border-color:white\" >".$max."</td>"; 
		$outputTotal .= "<td style=\"border-color:white\" >".$poz."</td>"; 
		$outputTotal .= "<td style=\"border-color:white\" >".$neg."</td>"; 
	if($max)
	{
		$pozPerc = round($poz/$max,2)*100;
		$outputTotal .= "<td style=\"border-color:white\">". $pozPerc."</td>"; 
	
		$outputTotal .= "<td style=\"border-color:white\">". (100 - $pozPerc)."</td>";
	}
	else 
	{
		$outputTotal .= "<td style=\"border-color:white\">&nbsp;</td>"; 
		$outputTotal .= "<td style=\"border-color:white\">&nbsp;</td>";
	}
	$outputTotal .= "</tr>";
	/*echo "<pre>";
	var_dump($frdb['questions']);
	echo "</pre>";*/
	//exit;
	// izpis pod menijev
	if ($frdb['questions']) {
		foreach ($frdb['questions'] as $subQuestions) {
			$outputTotal .= "<tr class=\"zaprti item_".$qId."\">";
				$outputTotal .= "<td style=\"font-size:11px\">".$subQuestions['quest']."</td>";
				
				$max = $subQuestions['pos'] + $subQuestions['neg'];
				
				$outputTotal .= "<td>".($subQuestions['pos'] + $subQuestions['neg'])."</td>";
				
				// if we make total report on some records only then we need to add extra filter on request for showing only this visits
				if ($records) {
					$additionalShowVisitFilter = " AND a.id IN (".implode(",",$records).")";
				} elseif ($idRecord) $additionalShowVisitFilter = " AND a.id IN (".$idRecord.")";
				else $additionalShowVisitFilter = "";
				
				if (!$subQuestions['pos']) $pos = "&nbsp;"; else $pos = "<a href=\"javascript:window.parent.CallScript('_forms/forms.pregledPoseta.php', { title: '".$tableName."', projectId: ".$idProject." , visitsFilter: '".$subQuestions['name']." = 1 ".$additionalShowVisitFilter ."' });\">".$subQuestions['pos']."</a>";
				if (!$subQuestions['neg']) $neg = "&nbsp;"; else $neg = "<a href=\"javascript:window.parent.CallScript('_forms/forms.pregledPoseta.php', { title: '".$tableName."', projectId: ".$idProject." , visitsFilter: '".$subQuestions['name']." = 2 ".$additionalShowVisitFilter ."' });\">".$subQuestions['neg']."</a>"; 
				
				$outputTotal .= "<td>".$pos."</td>";
				$outputTotal .= "<td>".$neg."</td>";
				if ($max) {
					$pozPerc = round($subQuestions['pos']/$max,2)*100;
					$outputTotal .= "<td align=center>". $pozPerc."</td>"; 	
					$outputTotal .= "<td align=center>". (100 - $pozPerc)."</td>";
				} else {
					$outputTotal .= "<td align=center>&nbsp;</td>"; 	
					$outputTotal .= "<td align=center>&nbsp;</td>";
				}
			$outputTotal .= "</tr>";
		}
	}
}

	$outputTotal .= "<tr $bckColor Style=\"font-weight:bold;\">";
	$outputTotal .= "<td style=\"border-color:white\">TOTAL</td>";
	$max = ($totalPoz + $totalNeg );
	$outputTotal .= "<td style=\"border-color:white\">".$max."</td>"; 
	$outputTotal .= "<td style=\"border-color:white\">".$totalPoz."</td>"; 
	$outputTotal .= "<td style=\"border-color:white\">".$totalNeg."</td>"; 
	if($max)
	{
		$outputTotal .= "<td style=\"border-color:white\">".(round($totalPoz/$max,2)*100)."</td>"; 
	
		$outputTotal .= "<td style=\"border-color:white\">".(round($totalNeg/$max,2)*100)."</td>";
		
		$graphData[-1]['label'] = 'Total';
		$graphData[-1]['checked'] = true;
		$graphData[-1]['gLabel'] = 'Total';
	
//			$data1y[] = round($poz/$max,2)*100;
//			$data2y[] = round($neg/$max,2)*100;
			$bgrg = round($totalPoz/$max,2)*100;
			$graphData[-1]['data1y'] = $bgrg;
			$graphData[-1]['data2y'] = 100-$bgrg;
		
	}
	
	$outputTotal .= "</tbody></table></div>";
	$outputTable = str_replace("\n",'',$outputTable);
	$outputTotal = str_replace("\n",'',$outputTotal);
	
	//file_put_contents("/tmp/soulLog.txt",$outputTotal,FILE_APPEND);
	
	$_SESSION['mysteryReportHTML'] = $outputTable;
	
	//$_SESSION['mysteryReportTotal'] = $outputTotal;
	file_put_contents("/tmp/data.txt",$outputTotal);
	
	$_SESSION['mysteryReportGraph'] = $graphData;

	//$_SESSION['mysteryReportGraph'] = '';

	//exit;
	
if ($idRecord) {
	include_once (PATH_TO_ROOT."mystery/_forms/grid.Comments.php");
}


echo "var panel = new Ext.TabPanel({
	title: '$title - $tableName',
	closable:true,
	activeTab:0,
	items: [";
if($idRecord)
	echo "{
		title: 'Report',
		html: '<iframe src=_forms/report.html.php?type=1 height=100% width=100% />'
	},";
echo "{
		title: 'Total',
		html:'<iframe src=_forms/report-total-table.html.php height=100% width=100% />'
	},{
		title: 'Graph',
		ref:'graphFrame',
		html:'<iframe id=mystery_$idProject src=_forms/report.graph.php?projectName=".$tableName." height=100% width=100% />'
	},
	{
		title: 'Settings',
		xtype:'form',
		labelWidth:400,
		defaults:{
			listeners:{
				check: function(){
					new RMajax().request({
						url: 'webcati/_forms/mysteryShopping/report.html.php',
						params: {
							checked:this.checked ? 1 : 0,
							value:this.value,
							action: 'graph'
						},
						success: function(){
							var f =document.getElementById('mystery_$idProject');
							if(f)
								f.src = f.src;
						}
					});
				}
			}
		},
		items:[
		";
		if($graphData)
		{
			foreach ($graphData as $fId => $lab) {
				$formItems[] = "{xtype:'checkbox',checked:true,value:$fId ,fieldLabel:'{$lab['label']}' }" ;
			}
			echo implode(',',$formItems);
		}
echo "
		]
	}";

if($idRecord)
{
$uniqeFormId = 'myseryReportForm_'.$idProject.'_'.$idRecord;

echo ", ".$grid;
/*echo ",{
		title:'Comment',
		xtype:'form',
		frame:true,
		hideLabels:true,
		items:[
			{
				xtype:'textarea',
				ref:'commentArea',
				width:300,
				height:200,
				value:". json_encode($record['mystery_comment'])."
			},
			{
				xtype:'button',
				text:'Save',
				fieldLabel:'&nbsp;',
				handler:function(){
					new RMajax().request({
						url:'$reqUrl',
						params:{
							action:'saveComment',
							value:this.ownerCt.commentArea.getValue(),
							id_project:$idProject,
							id_record:$idRecord
						}
					});
				}
			}
		]
	} */
	
echo ",{
		title:'Image',
		xtype:'form',
		layout:'fit',
		id:'$uniqeFormId',enctype:'multipart/form-data',
      			  fileUpload: true,method:'POST',url: '$reqUrl',
      			  baseParams: { id_project : $idProject,id_record:$idRecord,action:'uploadImage' },
      	items:{
      	ref:'baba',	  
      	autoScroll:true,
      	deleteImage: function(num){ new RMajax().request({
						url:'$reqUrl',
						params:{
							action:'deleteImage',
							value:num,
							id_project:$idProject,
							id_record:$idRecord
						},success: function(a,b){
							var c = Ext.decode(a.responseText);
							var f= Ext.getCmp('$uniqeFormId');
							f.baba.load({
									url:'$reqUrl',
									params:{
										action:'loadImage',
										id_project:$idProject,
										id_record:$idRecord
									},nocache: true
								});
						}
					}); },
		tbar:['Upload ',{
			xtype:'fileuploadfield',
			buttonOnly:true,
			name: 'uploadLink',
			ctCls: 'button-fix',
			buttonCfg:
			{
				//text:'Upload links',
				text:'',
				 iconCls: 'upload-icon'
			},
			listeners: {
				fileselected: function(t,file)
				{
				
				
				var f= Ext.getCmp('$uniqeFormId');
					f.getForm().submit({
						method:'post',
						success: function(a,b){
						
							var c = Ext.decode(b.response.responseText);
							f.baba.load({
									url:'$reqUrl',
									params:{
										action:'loadImage',
										id_project:$idProject,
										id_record:$idRecord
									},nocache: true
								});
						}
					});
				}
			}
		}],
		listeners:{
				afterrender:function(){
					this.load({
						url:'$reqUrl',
						params:{
							action:'loadImage',
							id_project:$idProject,
							id_record:$idRecord
						},nocache: true
					});
				}
				}
		 
		}
	}";
}
echo "]
});
mainTabPanel.add(panel).show();";
?>