<?php

ini_set("display_errors","1");

include_once ("_dirinfo.php");

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

// Display the graph
//$graph->Stroke();
	


$idProject = $_POST['id_project'];

$idRecord = $_POST['id_record'];


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

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

if($idRecord)
{
	$record = $db->get($tableName.'_structure',$idRecord);
	//var_dump($record);
}
else 
{
	$record = $db->get($tableName.'_structure',"flag_bad = 101");
	if(!$record)
	{
		echo "Ext.Msg.alert('Warning','No records available!')";
		exit;
	}
}
$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' )));	
	
}

function recursiveSelect($id,$level)
{
	global $outputTable,$tableName,$db,$record,$scores,$folderScores,$idProject,$idRecord,$mainLevelArray;
	
	$sql = "SELECT a.*,b.qComment FROM $tableName"."_tree a LEFT JOIN _QuestionComments b ON b.id_question=a.id AND id_project=$idProject AND id_structure='$idRecord' WHERE id_sup = $id ORDER BY orderBy";
	$res = $db->SQLexecute($sql);
	while($row = $db->fetchAssoc($res) )
	{
		$outputTable .= "<TR>";
		if($row['is_leaf'])
		{
			$q = Question::createQuestionFromTable($db,$tableName,$row['id']);
			$ansArr = $q->getAnswerArray();
			$ansCnt = count($ansArr);
			
			$outputTable .= "<TD>".$q->q_name ." </TD>";
			$outputTable .= "<TD>".strip_tags( $q->vpr_sql )."</TD>";
			//$outputTable .= "<TD>".$ansArr[0][1] ."</TD>";
			//$outputTable .= "</TR>";
			if($q->tip_sql == 4)//we make the answer array from actual answers...kinda
			{
				
			}
			$outputTable .= "<TD>";
			if($ansCnt > 0)
			{
				//$outputTable .= "11";
				$outputTable .= "<TABLE>";
				for ($cm = 0;$cm<$ansCnt;$cm++) {
					
						$outputTable .= "<TR>";
					
					$bckColor = '';
					if($q->tip_sql == 1 OR $q->tip_sql == 3)
					{
						if($idRecord)
						{
							
							
							if ($q->tip_sql == 1) 
								$questVar = $q->q_name;
							elseif ($q->tip_sql == 3)
								$questVar = $q->q_name."_".($cm+1);

							$db->LogWrite($q->q_name." - ".$ansArr[$cm][0]." - ".$record[$questVar],true,"mistery inside id record");
								
							if($ansArr[$cm][0] ==  $record[$questVar] )
							{
								$db->LogWrite("questVar:".$questVar." - row['id']:".$row['id']." - scores[row[id]_ansArr[cm][0]:".$scores[$row['id'].'_'.$ansArr[$cm][0] ],true,"score");

								$sc = $scores[$row['id'].'_'.$ansArr[$cm][0] ];

								$db->LogWrite($sc,true,"sc variable");
								if($sc > 0 )
								{
									$folderScores[$id]['pos'] += $sc;
									$bckColor = "bgcolor=#C6EFCE";
								}
								else if($sc < 0 )
								{
									$folderScores[$id]['neg'] += abs($sc);
									$bckColor = "bgcolor=#FFC7CE";
								}
								else
									$bckColor = "bgcolor=#cccccc";
							}
						}
						else //no records selected...we have to PULL in ALL records! 
						{
								foreach ($record as $rec) {
									if ($q->tip_sql == 1) 
										$questVar = $q->q_name;
									elseif ($q->tip_sql == 3)
										$questVar = $q->q_name."_".($cm+1);
																
									if($ansArr[$cm][0] ==  $rec[$questVar] )
									{
											 $sc = $scores[$row['id'].'_'.$ansArr[$cm][0] ];
											if($sc > 0 )
											{
												$folderScores[$id]['pos'] += $sc;
											}
											else if($sc < 0 )
											{
												$folderScores[$id]['neg'] += abs($sc);
											}
									}
								}
								
						}
						
						$outputTable .= "<TD $bckColor>".strip_tags(  $ansArr[$cm][1] )."</TD>";
					
					
					} elseif ($q->tip_sql == 2) {
						$qLegend =  $q->getLegendArray();
						
						$outputTable .= "<TD>".strip_tags(  $ansArr[$cm][1] )."</TD>";
						foreach ($qLegend as $qLegKey => $qLegVal) {
								
								$bckColor = "";

									if($idRecord)
									{
										$t = $q->q_name."_".($cm+1);
										if($qLegVal[0] ==  $record[$t] )
										{
											$myKey = $row['id'].'_'.$qLegVal[0]."_".($cm+1);
											
											$sc = $scores[$myKey];
											if($sc > 0 )
											{
												$folderScores[$id]['pos'] += $sc;
												$bckColor = "bgcolor=#C6EFCE";
											}
											else if($sc < 0 )
											{
												$folderScores[$id]['neg'] += abs($sc);
												$bckColor = "bgcolor=#FFC7CE";
											}
											else
												$bckColor = "bgcolor=#cccccc";
										}
									}
									else //no records selected...we have to PULL in ALL records! 
									{
											$t = $q->q_name."_".($cm+1);
											foreach ($record as $rec) {
											
												if($qLegVal[0] ==  $rec[$t] )
												{
											
														$myKey = $row['id'].'_'.$qLegVal[0]."_".($cm+1);
														$sc = $scores[$myKey];
														
														if($sc > 0 )
														{
															$folderScores[$id]['pos'] += $sc;
														}
														else if($sc < 0 )
														{
															$folderScores[$id]['neg'] += abs($sc);
														}
												}
											}
											
									}
										
							
							
							$outputTable .= "<TD ".$bckColor.">"; 
								
								//$outputTable .=$row['id']."-".$record[$t]."-";
								//$outputTable .= $folderScores[$id]['pos']." | ".$folderScores[$id]['neg']." || ";
								$outputTable .= $qLegVal[1]; 	
							$outputTable .= "</TD>";
							}
						}
						$outputTable .= "</TR>";
					}
					
				$outputTable .= "</TABLE>";
			}
			else if($q->tip_sql == 4)
			{
				if($q->open_sql == 1)
				$outputTable .= strip_tags( $record[ $q->q_name.'_1' ] )."&nbsp;";
				else
				{
					
				}
			}
			else if($q->tip_sql == 5)
			{
				$outputTable .= "&nbsp;";
			}
			
			
			$outputTable .= "</TD>";
			
			$outputTable .= "<TD>".($row['qComment'] ? $row['qComment'] : '&nbsp;' )."</TD></TR>";

			
			if($q->open_answers)
			{
				$open = $q->getStructureFields();
				foreach ($open as $openFld) {
					if(strpos($openFld,'_opn') > 0 )
						if ($record[ $openFld ]) 
							$outputTable .="<TR><TD Style=\"vertical-align:top; border-top:0px solid #CECECE\">&nbsp;</TD><td Style=\"vertical-align:top; border-top:0px solid #CECECE\" align=right valign=bottom>&nbsp;</td><td Style=\"vertical-align:top; border-top:0px solid #CECECE\"><table width=100%><tr><TD><i><font color=grey>{$record[ $openFld ]}</font></i></td></tr></table></TD><td Style=\"vertical-align:top; border-top:0px solid #CECECE\">&nbsp;</td></TR>";
				}
				
				
			}
		}
		else 
		{
			$folderScores[$id]['subFolder'][] = $row['id'];
			$folderScores[$row['id']]['name'] = $row['idLab'];
			
			$color = "#cccccc";
			if($level == 1)
				$color = "#FFFF7F";
			else //we store ID's
			{
				$mainLevelArray[] = $row['id'];	
			}
			$outputTable .= "<TD colspan = 5 bgcolor=$color ><b>".strip_tags( $row['idLab'] )."<b></TD>";
			recursiveSelect($row['id'],$level+1);
		}
		$outputTable .= "</TR>";
	}
}
$outputTable .= "<table class=reportTable cellpadding=0 cellspacing=0>";
recursiveSelect(0,0);
$outputTable .= "</table>";

unset ($folderScores[0]);
$outputTotal .= "
<table Style=\"font:Verdana 16px;color:#303030;\"
cellpadding=4 cellspacing=0><tr Style=\"font-weight:bold;\">
<td>Atributi za ocenjivanje</td>
<td align=center>Maksimalan<br>broj poena</td>
<td align=center>Postignuce</td><td align=center>Nedostatak</td>
<td align=center>Postignuće<br>(%)</td>
<td align=center>Nedostatak<br>(%)</td>
</tr>";
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;
		}
		
	}
			
		if(!$poz) $poz = '&nbsp;';
		if(!$neg) $neg = '&nbsp;';
	
	$outputTotal .= "<tr $bckColor>";
	$outputTotal .= "<td>".$frdb['name']."</td>";
	
	$outputTotal .= "<td align=center>".$max."</td>"; 
	$outputTotal .= "<td align=center>".$poz."</td>"; 
	$outputTotal .= "<td align=center>".$neg."</td>"; 
	if($max)
	{
		$pozPerc = round($poz/$max,2)*100;
		$outputTotal .= "<td align=center>". $pozPerc."</td>"; 
	
		$outputTotal .= "<td align=center>". (100 - $pozPerc)."</td>";
	}
	else 
	{
		$outputTotal .= "<td>&nbsp;</td>"; 
		$outputTotal .= "<td>&nbsp;</td>";
	}
	$outputTotal .= "</tr>";
}
	$outputTotal .= "<tr $bckColor Style=\"font-weight:bold;\">";
	$outputTotal .= "<td>TOTAL</td>";
	$max = ($totalPoz + $totalNeg );
	$outputTotal .= "<td align=center>".$max."</td>"; 
	$outputTotal .= "<td align=center>".$totalPoz."</td>"; 
	$outputTotal .= "<td align=center>".$totalNeg."</td>"; 
	if($max)
	{
		$outputTotal .= "<td align=center>".(round($totalPoz/$max,2)*100)."</td>"; 
	
		$outputTotal .= "<td align=center>".(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;
		
	}
	$outputTable = str_replace("\n",'',$outputTable);
	$outputTotal = str_replace("\n",'',$outputTotal);
	$_SESSION['mysteryReportHTML'] = $outputTable;
	$_SESSION['mysteryReportTotal'] = $outputTotal;
	$_SESSION['mysteryReportGraph'] = $graphData;
	
echo "var panel = new Ext.TabPanel({
	title: 'Mystery report - $tableName',
	closable:true,
	activeTab:0,
	items: [";
if($idRecord)
	echo "{
		title: 'Report',
		html: '<iframe src=webcati/_forms/mysteryShopping/report.html.php?type=1 height=100% width=100% />'
	},";
echo "{
		title: 'Total',
		html:'<iframe src=webcati/_forms/mysteryShopping/report.html.php?type=2 height=100% width=100% />'
	},{
		title: 'Graph',
		ref:'graphFrame',
		html:'<iframe id=mystery_$idProject src=webcati/_forms/mysteryShopping/report.graph.php 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 ",{
		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
						}
					});
				}
			}
		]
	},{
		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();";
?>