<?php
include_once("_dirinfo.php");
include_once(PATH_TO_ROOT."init.php");



/**
 * **
 *
 * Function returns
 * 		original sample ID from sample table (capi___PROJECT-NAME -> id )
 * and 	id of sample table ( _CapiTables -> ID )
 *
 * @param integer $idSample
 * @return array
 */
function getSampleID($idSample,$db) {

	$sql = "SELECT proj_name FROM ".DB_WARPIT_WEBCATI_BASE."._Projects as a
				WHERE 	a.id = ".$_SESSION['capi']['id_project'];
	$res = $db->SQLexecute($sql);
	$zad = $db->fetchAssoc($res);
	//file_put_contents("/tmp/capi.txt",print_r($sql,true),FILE_APPEND);
	$sql = "SELECT id_sample, id_sampleTable
				FROM ".DB_WARPIT_WEBCATI_BASE.".".$zad['proj_name']."___sample
			WHERE id = ".intval($idSample);
	$res = $db->SQLexecute($sql);
	$zad = $db->fetchAssoc($res);
	//file_put_contents("/tmp/capi.txt",print_r($sql,true),FILE_APPEND);
	return array("IDsampleMain" => $zad['id_sampleTable'],"IDsampleTable" => $zad['id_sample']);

}

$dbConfigCapi = configLoader::loadConfig('capi');

$sql = "SELECT  translate_key, translate_text
				FROM  ".DB_WARPIT_MAIN."._languagePack
					WHERE id_programme = 2 AND id_language = ".$dbConfigCapi['default-language']." AND sub_page = 'capi'";
	//echo $sql;
$res = $db->SQLexecute($sql);
while ($zad = $db->fetchAssoc($res)) $languagePack[$zad['translate_key']] = $zad['translate_text'];


if($_POST['action'] == 'getProjects'){

	$date = date("Y-m-d H:i:s");
	$sql = 	" SELECT proj_name,loginSID,naziv_proj, b.id as id_project FROM ".DB_WARPIT_WEBCATI_BASE."._www_ids as a
				INNER JOIN ".DB_WARPIT_WEBCATI_BASE."._Projects as b ON a.id_project = b.id
				WHERE b.active = 1 AND b.start_date < '$date' AND b.end_date > '$date' AND a.id_user = ".$_SESSION['UserInfo']['id']." AND a.user_type=".$_SESSION['UserInfo']['user_type'];
		$res = $db->SQLexecute($sql);
	while ($zad = mysql_fetch_assoc($res)) {
		if (!$zad['naziv_proj']) $zad['naziv_proj'] = $zad['proj_name'];
		$projects[] = array("pId" => $zad['id_project'], "name" => $zad['naziv_proj']);
		//$projects[$zad['id_project']] = $zad['naziv_proj'];
	}

	$result = array();
	$result['success'] = true;
	$result['rows'] = $projects;
	echo json_encode($result);

}elseif ($_POST['action'] == "change-project") {

	$_SESSION['capi']['id_project'] = $_POST['id_project'];

	echo "hideSampleFunctions();";
	echo "showTools();";
	echo "Ext.getCmp('mainTabPanel').removeAll();";
	echo "store = Ext.getCmp('CapiAppointmentsGrid').getStore();";
	echo "store.removeAll();";
	echo "store.reload();";
	echo "CallScript(\"_forms/forms.quota-statistics.php\",{  id_project: '".$_POST['id_project']."' })";


} elseif ($_POST['action'] == "interrupt") {


	$sql = "UPDATE ".DB_WARPIT_WEBCATI_BASE."._Capi_interviewer_visits SET status_obiska = 9 WHERE id = ".$_POST['id_visit'];
	$db->SQLexecute($sql);

	$sql = 	" SELECT a.id, a.id_user, a.id_site, b.proj_name FROM ".DB_WARPIT_WEBCATI_BASE."._www_ids as a
						LEFT JOIN ".DB_WARPIT_WEBCATI_BASE."._Projects as b ON a.id_project = b.id
							WHERE
										id_project 	= ".$_SESSION['capi']['id_project']."
									AND id_user 	= ".$_SESSION['UserInfo']['id']."
									AND user_type 	= 4
									AND id_site		IN 	(SELECT quest_id FROM ".DB_WARPIT_WEBCATI_BASE."._Capi_interviewer_visits WHERE id = ".$_POST['id_visit'].")";

	//	file_put_contents("/tmp1/capi.txt",print_r($sql,true),FILE_APPEND);
		$res = $db->SQLexecute($sql);
		$zad = $db->fetchAssoc($res);

		//file_put_contents("/tmp1/capi.txt",print_r($sql,true),FILE_APPEND);


		$sql = "UPDATE `".DB_WARPIT_WEBCATI_BASE."`.`".$zad['proj_name']."_structure`
					SET
							`status` = 51,
							`status_rec` = 0
					WHERE
									user_id 		= ".$zad['id_user']."
							AND		id_site			= '".$zad['id_site']."'
							AND 	id_loginSID		= ".$zad['id'];

		$db->SQLexecute($sql);


	echo "Ext.getCmp('CapiAppointmentsGrid').getStore().removeAll();";
	echo "Ext.getCmp('CapiAppointmentsGrid').getStore().reload();	";
	echo "showTools();";
	echo "tb.show();  ";
	echo "Ext.getCmp('MainPanel').doLayout();";

    echo "Ext.getCmp('surv-panel-".$_SESSION['capi']['id_project']."').destroy(); ";



} elseif(
				$_POST['action'] == "start-new"
			|| 	$_POST['action'] == "start-test"
			||  $_POST['action'] == "continue-with-interview"
			||  $_POST['action'] == "start-with-interview-sample"

		) {

	if (!$_SESSION['capi']['id_project']) {
		echo "	Ext.Msg.show({
					title:'".$languagePack['project-status']."',
					msg: '".$languagePack['no-project-is-selected']."',
					buttons: Ext.Msg.OK,
					animEl: 'elId',
					icon: Ext.MessageBox.QUESTION
				});";
		exit;
	} else {
		$date = date("Y-m-d H:i:s");
		$sql = 	" SELECT proj_name,loginSID,naziv_proj FROM ".DB_WARPIT_WEBCATI_BASE."._www_ids as a
				INNER JOIN ".DB_WARPIT_WEBCATI_BASE."._Projects as b ON a.id_project = b.id
				WHERE 	b.active = 1
						AND b.start_date < '".$date."'
						AND b.end_date > '".$date."'
						AND b.id = ".$_SESSION['capi']['id_project']."
						AND a.id_user = ".$_SESSION['UserInfo']['id']."
						AND a.user_type=".$_SESSION['UserInfo']['user_type'];

		$res = $db->SQLexecute($sql);
		$zad = $db->fetchAssoc($res);

		if ($zad['loginSID']) {
			if (!$zad['naziv_proj']) $projectName = $zad['proj_name']; else $projectName =  $zad['naziv_proj'];

			if ($_POST['action'] == "continue-with-interview") {

				 $sql = "UPDATE ".DB_WARPIT_WEBCATI_BASE."._Capi_interviewer_visits SET status_obiska = 2 WHERE id = ".$_POST['id_record'];
				 $db->SQLexecute($sql);

				 $sql = "SELECT quest_id,sample_point,obisk_st,id_structure FROM ".DB_WARPIT_WEBCATI_BASE."._Capi_interviewer_visits WHERE id = ".$_POST['id_record'];
				 $res 					=  	$db->SQLexecute($sql);
				 $zad 					= 	$db->fetchAssoc($res);
				 $quest 				= 	$zad['quest_id'];
				 $_POST['id_sample']	=	$zad['sample_point'];

				 $sql = "INSERT INTO ".DB_WARPIT_WEBCATI_BASE."._Capi_interviewer_visits
							SET
								obisk_st 		= 	".($zad['obisk_st'] + 1).",
								id_project 		= 	'".$_SESSION['capi']['id_project']."',
								user_id 		= 	'".$_SESSION['UserInfo']['id']."',
								user_type 		= 	'".$_SESSION['UserInfo']['user_type']."',
								cas_obiska 		= 	NOW(),
								sample_point	=	".$zad['sample_point'].",
								id_structure	=	".$zad['id_structure'].",
								quest_id = ".$quest.";";

				 $db->SQLexecute($sql);
				 $visitID = $lastID = $db->GetLastInsertId();

				 if ($zad['id_structure'] == 0) {
				 	$lastID = $quest;
				 	include(PATH_TO_ROOT."webcati/_ajax/generateWwwIds/ajax.generate-capi-sid.php");
				 }


				// Here is situation that we have made visit with appointment on sample point but we did not
				// start questionnaire, so IDsampleMain or IDsampleTable has not been saved to structure table
				// in this case we need to take into database to find correct IDsampleMain and IDsampleTable
				// so everything will be correct saved into structure database file
				//
				// for key we take $_POST[id_sample] which is ID of sample point in project__sample
				if (!$_POST['IDsampleMain'] || !$_POST['IDsampleTable']) {
					$r = getSampleID($_POST['id_sample'],$db);
					$_POST['IDsampleMain'] = $r['IDsampleMain'];
					$_POST['IDsampleTable'] = $r['IDsampleTable'];
				}


				 $sql = 	" SELECT loginSID FROM ".DB_WARPIT_WEBCATI_BASE."._www_ids
								WHERE
										id_project 	= ".$_SESSION['capi']['id_project']."
									AND id_user 	= ".$_SESSION['UserInfo']['id']."
									AND user_type 	= 4
									AND id_site		= ".$quest;
				$res = $db->SQLexecute($sql);
				$zad = $db->fetchAssoc($res);
				$params = array();

				$params[] = "capi=1";
				$params[] = "id_site=".$quest;
				$params[] = "IDsampleProject=".$_POST['id_sample'];
				$params[] = "IDsampleMain=".$_POST['IDsampleMain'];
				$params[] = "IDsampleTable=".$_POST['IDsampleTable'];

				$link = "../survey/index.php?loginSID=".$zad['loginSID']."&".implode("&",$params);

				//echo "Ext.getCmp('CapiAppointmentsGrid').getStore().reload();";

			} elseif ( $_POST['action'] == "start-new" || $_POST['action'] == "start-with-interview-sample" ) {

				// now I have checked if interviewer has permission for interviewing on this project


				$sql = "SELECT MAX(obisk_st) as obisk_st, MAX(quest_id) as quest_id, id_structure  FROM ".DB_WARPIT_WEBCATI_BASE."._Capi_interviewer_visits
							WHERE 			sample_point 	= '".$_POST['id_sample']."'
									AND 	id_project 		= ".$_SESSION['capi']['id_project']."
									AND		user_id  		= ".$_SESSION['UserInfo']['id'];
				$res = $db->SQLexecute($sql);
				$zad = $db->fetchAssoc($res);


				// next step is to prepare record in capi interviewer visits and to create new login SID for this interviewer

				// -------------- ADDING NEW VISIT INTO VISIT TABLE ----------------------------------
				$sql = "INSERT INTO ".DB_WARPIT_WEBCATI_BASE."._Capi_interviewer_visits
							SET
								obisk_st 		= ".($zad['obisk_st'] + 1 ).",
								id_project 		= ".$_SESSION['capi']['id_project'].",
								user_id  		= ".$_SESSION['UserInfo']['id'].",
								user_type 		= '".$_SESSION['UserInfo']['user_type']."',
								id_structure	= '".$zad['id_structure']."',
								sample_point 	= '".$_POST['id_sample']."',
								quest_id 		= '".$zad['quest_id']."',
								cas_obiska 		= NOW() ";
				$db->SQLexecute($sql);



				if ($zad['id_structure']) {
					$lastID 	= 	$zad['quest_id'];
					$visitID 	=  	$db->GetLastInsertId();
				}
				else {

					$visitID 	=	$lastID 	= 	$db->GetLastInsertId();
					$sql = "UPDATE ".DB_WARPIT_WEBCATI_BASE."._Capi_interviewer_visits SET quest_id = ".$lastID." WHERE id = ".$lastID;

					echo "/*".$sql." */";

					$db->SQLexecute($sql);

					// -------------- CREATING NEW loginSID ----------------------------------

					include(PATH_TO_ROOT."webcati/_ajax/generateWwwIds/ajax.generate-capi-sid.php");

					// -------------- GET new loginSID
				}


				$sql = 	" SELECT loginSID FROM ".DB_WARPIT_WEBCATI_BASE."._www_ids
								WHERE
										id_project 	= ".$_SESSION['capi']['id_project']."
									AND id_user 	= ".$_SESSION['UserInfo']['id']."
									AND user_type 	= 4
									And id_site		= ".$lastID;
				echo "/*".$sql." */";

				$res = $db->SQLexecute($sql);
				$zad = $db->fetchAssoc($res);

				$params[] = "capi=1";
				$params[] = "id_site=".$lastID;
				$params[] = "IDsampleProject=".$_POST['id_sample'];
				$params[] = "IDsampleMain=".$_POST['IDsampleMain'];
				$params[] = "IDsampleTable=".$_POST['IDsampleTable'];

				$link = "../survey/index.php?loginSID=".$zad['loginSID']."&".implode("&",$params);


			} else {
				// testiranje
				$sql = 	" SELECT loginSID FROM ".DB_WARPIT_WEBCATI_BASE."._www_ids
								WHERE
										id_project 	= ".$_SESSION['capi']['id_project']."
									AND id_user 	= 0
									AND user_type 	= 3 ";

				$res = $db->SQLexecute($sql);
				$zad = $db->fetchAssoc($res);
				$link = "../survey/index.php?loginSID=".$zad['loginSID']."&capi=1&test=1";

			}

			echo "mainTabPanel.add(
					new Ext.Panel({
						title: 'Interview: ".$projectName."',
						closable: true,
						listeners: {

							close : function(p) {
								tb.show();
								Ext.getCmp('MainPanel').doLayout();
								showTools();
							}
						},


						id: 'surv-panel-".$_SESSION['capi']['id_project']."', ";

			if ($_POST['action'] == "start-new" || $_POST['action'] == "continue-with-interview" || $_POST['action'] == "start-with-interview-sample") :
				echo 	"   tbar: [{
					        			 text: '<span style=\'margin-left:10px\'><b>Interrupt Interview</b></span>',
					        			 iconCls: 'buttonInterrupt',
					        			 id: 'surveyButtonInterrupt',
							           	 handler: function() {

							           	 	Ext.Msg.show({
													   title:'".$languagePack['interrupt-interview']."',
													   msg: '".$languagePack['interrupt-are-sure']."',
													   buttons: Ext.Msg.YESNO,
													   fn: function(selBtn) {
													   		if (selBtn == 'yes') {
													   			CallScript(\"_ajax/ajax.project-actions.php\",{ action: 'interrupt', id_visit : '".$visitID."' })
													   		}
													   },
													   animEl: 'elId',
													   icon: Ext.MessageBox.QUESTION
													});
							            }

	        					},
	        					{
					        			 text: '<span style=\'margin-left:10px\'><b>".$languagePack['make-appointment']."</b></span>',
					        			 iconCls: 'buttonAppointment',
					        			 id: 'surveyButtonAppointment',
							           	 handler: function() {

							           	 	Ext.Msg.show({
													   title:'".$languagePack['appointment']."',
													   msg: '".$languagePack['sure-make-appointment']."',
													   buttons: Ext.Msg.YESNO,
													   fn: function(selBtn) {
													   		if (selBtn == 'yes') {
													   			CallScript(\"_forms/window.capi.appointment.php\",{ id_visit : '".$visitID."' })
													   		}
													   },
													   animEl: 'elId',
													   icon: Ext.MessageBox.QUESTION
													});
							            }

	        					}
	        					], ";
	        endif;
	        	echo "	items: new Ext.ux.IFrameComponent({
								width: '100%',
								height: '100%',
								id: 'survey-".$_SESSION['capi']['id_project']."',
								url: '".$link."'
							})
	        	})).show();";
		}
	}

	echo "Ext.getCmp('CapiAppointmentsGrid').getStore().removeAll();";
	echo "Ext.getCmp('CapiAppointmentsGrid').getStore().reload();	";

}

elseif ($_POST['action'] == "finishQuestionnaire") {
	//echo "alert('test12345');";

	$t = explode("-",$_POST['qSid']);
	$sql = "SELECT * FROM `".DB_WARPIT_WEBCATI_BASE."`.`_www_ids` WHERE id = ".intval($t[1]);
	$res = $db->SQLexecute($sql);
	$zad = $db->fetchAssoc($res);

	// we check if SID is correct and not some attack...
	if ($zad['loginSID'] == $_POST['qSid']) {

		$sql = "UPDATE `".DB_WARPIT_WEBCATI_BASE."`.`_Capi_interviewer_visits`
					SET
							status_obiska 	= ".$_POST['qStatusRec'].",
							id_structure	= ".$_POST['qID_structure']."
					WHERE
								user_id  	=	".$zad['id_user']."
							AND	id_project 	=	".$zad['id_project']."
							AND	quest_id	= 	".$zad['id_site']."
					ORDER BY id DESC LIMIT 1 ";

		$db->SQLexecute($sql);
		echo "Ext.getCmp('surveyButtonAppointment').hide();";
		echo "Ext.getCmp('surveyButtonInterrupt').hide();";

		$sql = "SELECT setting_value FROM `".DB_WARPIT_WEBCATI_BASE."`.`_CapiProperties`
					WHERE 		id_project IN (0, ".$zad['id_project']." )
							AND setting_name = 'close-survey-timeout'
			ORDER BY id_project DESC LIMIT 1 ";
		$res = $db->SQLexecute($sql);
		if ($db->NumRows($res)) :
			$zadTimeout = $db->fetchAssoc($res);
			$val = intval($zadTimeout['setting_value']);

			if ($val == 0) {

				echo "tb.show(); ";
				echo "Ext.getCmp('MainPanel').doLayout();";
				echo "showTools(); ";
				echo "Ext.getCmp('surv-panel-".$zad['id_project']."').destroy();";

			} elseif ($val > 0) {

				echo "setTimeout(function(){ ";
					echo "tb.show(); ";
					echo "Ext.getCmp('MainPanel').doLayout();";
					echo "showTools(); ";
					echo "Ext.getCmp('surv-panel-".$zad['id_project']."').destroy();";
				echo " }, ".($val * 1000).");";
			}
		endif;

	} else {
		echo "alert('Error saving completed interview in visit table!');";
	}
} elseif ($_POST['action'] == "saveIDstructure") {
	$t = explode("-",$_POST['qSid']);
	$sql = "SELECT * FROM `".DB_WARPIT_WEBCATI_BASE."`.`_www_ids` WHERE id = ".intval($t[1]);
	$res = $db->SQLexecute($sql);
	$zad = $db->fetchAssoc($res);

	// we check if SID is correct and not some attack...
	if ($zad['loginSID'] == $_POST['qSid']) {

		$sql = "UPDATE `".DB_WARPIT_WEBCATI_BASE."`.`_Capi_interviewer_visits`
					SET
							id_structure	= ".$_POST['qID_structure']."
					WHERE
								user_id  	=	".$zad['id_user']."
							AND	id_project 	=	".$zad['id_project']."
							AND	quest_id	= 	".$zad['id_site']."
					ORDER BY id DESC LIMIT 1 ";

		$db->SQLexecute($sql);
	}
}
?>