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

	
	if ($_POST['action'] == "save") {
		
		// ------------ CHECKING VARIABLES
		$CheckVariable 	= sf_CheckForMySQL($_POST);
		$samplePoint 	= intval($_POST['id_sample']);

		$sql = "SELECT obisk_st as last_visit_number, id_structure, quest_id 
					FROM ".DB_WARPIT_WEBCATI_BASE."._Capi_interviewer_visits 
				
				WHERE			id_project 		= ".$_SESSION['capi']['id_project']." 
						AND 	sample_point	= ".$samplePoint." 
				ORDER BY id DESC LIMIT 1		
				";
	
		$res = $db->SQLexecute($sql);
		$zad = $db->fetchAssoc($res);
		if ($zad['last_visit_number']) 
		{
			$new_visit_num = $zad['last_visit_number'] + 1;
		}
		else 
		{
			$new_visit_num = 1;
		}
			
		$sql = "INSERT INTO  ".DB_WARPIT_WEBCATI_BASE."._Capi_interviewer_visits 
					SET 
						id_project 		= ".$_SESSION['capi']['id_project'].",
						user_id 		= ".$_SESSION['UserInfo']['id'].",
						sample_point	= ".$samplePoint.",
						id_structure	= '".$zad['id_structure']."',
						obisk_st		= ".$new_visit_num.",
						priimek_gosp 	= '".$CheckVariable['priimek_gosp']."',
						komentar 		= '".$CheckVariable['komentar']."',
						quest_id 		= '".$zad['quest_id']."',	
						cas_obiska		= NOW(), ";
		
		if ($CheckVariable['status_obiska'] == 8 || $CheckVariable['status_obiska'] == 22) 
				$sql .= " ponovni_dogovor = '".$CheckVariable['input_date']." ".$CheckVariable['input_time'].":00',";
		
	  	$sql .= "	status_obiska	= '".$CheckVariable['status_obiska']."'";
		
		$db->SQLexecute($sql);
		
		if ( $new_visit_num == 1 ) {
			$lastID = $db->GetLastInsertId();
			$sql = "UPDATE ".DB_WARPIT_WEBCATI_BASE."._Capi_interviewer_visits SET quest_id = ".$lastID." WHERE id = ".$lastID;
			$db->SQLexecute($sql);
				
		}
	}
	echo "{ success: true }";
	
?>