<?php
include_once ("_dirinfo.php");
include_once (PATH_TO_ROOT."init.php");
include_once (PATH_TO_ROOT."config.php");
include_once (PATH_TO_ROOT."CRM/_CRM_config.php");
include_once(PATH_TO_ROOT."CRM/class/class.Language-Pack.php");
include_once (PATH_TO_ROOT.'CRM/class/class.logger.php');
include_once(PATH_TO_ROOT."CRM/class/class.checkString.php");

$Logger = new LoggerX($db);

//ini_set("display_errors",1);

$LangPack = new LanguagePack($db, $aLanguage);
$table = "_visitStatistic";
if($_POST['action'] == 'submit'){
	//Assistent
	$assistent_id = StringChecker::Check($_POST['assistent']);
	//Product
	$article = StringChecker::Check($_POST['izdelek']);
	$product_amount = StringChecker::Check($_POST['kolicina_izdelkov']);
	$tip_narocila = StringChecker::Check($_POST['tip_narocila']);
	$product_price = StringChecker::Check($_POST['cena_izdelka']);
	
	//Način dostave
	$delivery_type = StringChecker::Check($_POST['tip_dostave']);
	$delivery_date = StringChecker::Check($_POST['datum_dostave']);
	$delivery_comment = StringChecker::Check($_POST['opomba_datuma_dostave']);
	
	//Vzrok naročila
	$vzrok = StringChecker::Check($_POST['brez_nakupa_vzrok']);
	$komentarBrezNakupa = StringChecker::Check($_POST['brez_nakupa_komentar']);
	
	//potrebni parametri
	$projectId = StringChecker::Check($_POST['projectId']);
	$id_tel = StringChecker::Check($_POST['id_tel']);
	
	//Enkratni znesek
	$avans = StringChecker::Check($_POST['avans_check']);
	$avans_payment_type = StringChecker::Check($_POST['avans_tip_placila']);
	$avans_amount = StringChecker::Check($_POST['avans_amount']);
	$avans_credit = StringChecker::Check($_POST['credit_card_avans_amount']);
	$avans_date = StringChecker::Check($_POST['datum_placila_avansa']);
	$one_time_payment_type = StringChecker::Check($_POST['enkratni_nacin_placila']);
	
	//Credit payment
	$credit_payment_type = StringChecker::Check($_POST['placilo_na_kredit_nacin_placila']);
	
	//Credit lon
	$number_of_payments = StringChecker::Check($_POST['credit_lon_stevilo_obrokov']);
	$show_deposit = StringChecker::Check($_POST['prikazi_polog']);
	
	//oseba dostava
	$delivery_name = StringChecker::Check($_POST['Ime']);
	$delivery_surname = StringChecker::Check($_POST['Priimek']);
	$delivery_address = StringChecker::Check($_POST['Naslov']);
	$delivery_post_code = StringChecker::Check($_POST['Posta']);
	$delivery_city = StringChecker::Check($_POST['Kraj']);
	$delivery_phone = StringChecker::Check($_POST['Telefonska_stevilka']);
	
	//podjetje dostava
	$company_delivery_title = StringChecker::Check($_POST['naziv_podjetja']);
	$company_delivery_tax_number = StringChecker::Check($_POST['davcna_stevilka']);
	$company_delivery_address = StringChecker::Check($_POST['Naslov_podjetja']);
	$company_delivery_post_code = StringChecker::Check($_POST['Posta_podjetja']);
	$company_delivery_city = StringChecker::Check($_POST['Kraj_podjetja']);
	$company_delivery_phone = StringChecker::Check($_POST['Telefonska_stevilka_podjetja']);
	
    $deposit_amount = 0;
    if($tip_narocila == 5){
        $filter[] = "DATE(i.dateFrom) < NOW()";
        $filter[] = "DATE(i.dateTo) > NOW()";
        $filter[] = "numberOfAnnuities = ".$number_of_payments;
        $filter[] = "id_product = ".$article;
        $filter[] = "active = 1";
        $sql = "SELECT id_interval FROM ".WARPIT_CRM."._loanCreditsDefinitions as d JOIN ".WARPIT_CRM."._loanCreditsIntervals as i ON i.id = d.id_interval WHERE ".implode(" AND ", $filter);
        $res = $db->SQLexecute($sql);
        $dat = $db->fetchAssoc($res);
        $loanIntervalId = $dat['id_interval'];
    }
    
	//prodobitev: project name
	$sqlProjName = "SELECT proj_name FROM ".DB_WARPIT_WEBCATI_BASE.".`_Projects` WHERE id = $projectId";
    $res = $db->SQLexecute($sqlProjName);
 	$dat = $db->fetchAssoc($res);
 	$ProjectName = $dat['proj_name'];
	
	//pridobitev: id tel
	$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE.".".$ProjectName."_structure WHERE `status` = 1 AND id_tel = $id_tel AND status_rec = 1";
	$res = $db->SQLexecute($sql);
	if($db->NumRows($res) != 0){
		
		$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE.".".$ProjectName."_structure WHERE id_tel = $id_tel";
		$res = $db->SQLexecute($sql);
		$data = $db->fetchAssoc($res);
		$array1 = explode(' ', $data['oseba_1'], 2);
		$array2 = explode(' ', $data['oseba_3'], 2); 
		$ime = $array1[0];
		$priimek = $array1[1];
		$naslov = $data['oseba_2'];
		$postnaSt = $array2[0];
		$kraj = $array2[1];
		$dan = $data['dan'];
		$ura = $data['ura'];
		$dogodek = $data['dogodek_2'];
		$cati_location = StringChecker::Check($_POST['cati_location']);
		$projectZip = "0".$data['TP_OMS'].$data['TP_telephone'];
		
		$sql = "SELECT * FROM ". WARPIT_CRM.".".$table ." WHERE id_tel = $id_tel";
		$res = $db->SQLexecute($sql);
		
		$creatorID = "";
		if($_SESSION['UserInfo']['user_type'] == 1){
			$creatorID = "u_".$_SESSION['UserInfo']['id'];
		}else{
			$creatorID = "i_".$_SESSION['UserInfo']['id'];
		}
		
		if($db->NumRows($res) == 0){
		
			$sql = "INSERT INTO ". WARPIT_CRM.".".$table ." (id_project, firstname, surname, address, post_code, city, dan, ura, dogodek, id_tel, cati_location, documentModify, phone1, order_creator_id, deposit_amount) 
					   	  VALUES ( '".$projectId."', '".$ime."', '".$priimek."', '".$naslov."', '".$postnaSt."', '".$kraj."', '".$dan."', '".$ura."', '".$dogodek."', '".$id_tel."', '".$cati_location."', NOW(), '".$projectZip."', '".$creatorID."', '".$deposit_amount."')";
			$db->SQLexecute($sql);
			$Logger->Log('changePeriod', 'multiple-filed-insert', 'id_project, firstname, surname, address, post_code, city, dan, ura, dogodek, id_tel, cati_location', 
					  ".WARPIT_CRM.".".$table.", '', StringChecker::Check($sql));	
		}
	}
	$sql = "SELECT order_date FROM ". WARPIT_CRM.".".$table ." WHERE id_tel = ".$id_tel;
    $res = $db->SQLexecute($sql);
    $dat = $db->fetchAssoc($res);
    $orderDate = $dat['order_date'];
    if($orderDate == "0000-00-00"){
       $sql = "UPDATE ". WARPIT_CRM.".".$table ." SET order_date = NOW() WHERE id_tel = ".$id_tel; 
       $db->SQLexecute($sql);
    }
    
	($vzrok == 5) ? $orderStatus = 1 : $orderStatus = 0; 
		$sql = "UPDATE ". WARPIT_CRM.".".$table ." SET 
							company_delivery_phone = '".$company_delivery_phone."',
							company_delivery_city = '".$company_delivery_city."',
							company_delivery_post_code = '".$company_delivery_post_code."',
							company_delivery_address = '".$company_delivery_address."',
							company_delivery_tax_number = '".$company_delivery_tax_number."',
							company_delivery_title = '".$company_delivery_title."',
							delivery_phone = '".$delivery_phone."',
							delivery_city = '".$delivery_city."',
							delivery_post_code = '".$delivery_post_code."',
							delivery_address = '".$delivery_address."',
							delivery_surname = '".$delivery_surname."',
							delivery_name = '".$delivery_name."',
							number_of_payments = '".$number_of_payments."',
							credit_payment_type = '".$credit_payment_type."',
							one_time_payment_type = '".$one_time_payment_type."',
							avans_date = STR_TO_DATE('".$avans_date."', '%d.%m.%Y'),
							avans_amount = '".$avans_amount."',
							avans_credit_amount = '".$avans_credit."',
							avans_payment_type = '".$avans_payment_type."',
							avans = '".$avans."',
							assistant_id = '".$assistent_id."',
							tipDostave = '".$delivery_type."',
							brez_nakupa_komentar = '".$komentarBrezNakupa."',
							tip_narocila = '".$tip_narocila."',
							article_id = '".$article."',
							product_amount = '".$product_amount."',
							order_reason = '".$vzrok."',
							order_status = ".$orderStatus.",
							show_deposit = '".$show_deposit."',
							product_price = '".$product_price."',
							datum_dostave = STR_TO_DATE('".$delivery_date."', '%d.%m.%Y'),
							opomba_dostave = '".$delivery_comment."',
							documentModify = NOW(),
							order_creator_id = '".$creatorID."',
							loanIntervalId = '".$loanIntervalId."'
							
				WHERE id_tel = ".$id_tel."";
                echo "/*$sql*/";
		
		//pridobitev stare vrednosti
		$sqlOld = "SELECT company_delivery_phone, company_delivery_city, company_delivery_post_code, company_delivery_address, company_delivery_tax_number, company_delivery_title, delivery_phone, delivery_city, delivery_post_code, delivery_address, delivery_surname, delivery_name, number_of_payments, credit_payment_type, one_time_payment_type, avans_date, avans_amount, avans_credit_amount, avans_payment_type, avans, assistant_id, tipDostave, brez_nakupa_komentar, tip_narocila, article_id, product_amount, order_reason, order_status, show_deposit, product_price, datum_dostave, opomba_dostave, documentModify 
				   FROM ". WARPIT_CRM.".".$table ." WHERE id_tel = ".$id_tel."";
		$resOld = $db->SQLexecute($sqlOld);
		$dataOld = $db->fetchAssoc($resOld);
				
		$Logger->Log('posodabljanje_uporabnika', 'multiple-filed-update', 'company_delivery_phone, company_delivery_city, company_delivery_post_code, company_delivery_address, company_delivery_tax_number, company_delivery_title, delivery_phone, delivery_city, delivery_post_code, delivery_address, delivery_surname, delivery_name, number_of_payments, credit_payment_type, one_time_payment_type, avans_date, avans_amount, avans_credit_amount, avans_payment_type, avans, assistant_id, tipDostave, brez_nakupa_komentar, tip_narocila, article_id, product_amount, order_reason, order_status, show_deposit, product_price, datum_dostave, opomba_dostave, documentModify', 
					  ". WARPIT_CRM.".".$table .", json_encode($dataOld), addslashes($sql));
					  	  
		$db->SQLexecute($sql);
		
	echo "{ success: true, msg: '".$LangPack->GetLabel("edit_order_window", "add_order_success_msg","Podatki so uspešno shranjeni!")."' }";
				
} else if($_POST['action'] == "get"){
	
	$id_tel = StringChecker::Check($_POST['id_tel']);
	
	$sql = "SELECT * FROM ".WARPIT_CRM."._visitStatistic WHERE id_tel = $id_tel AND id_project = ".StringChecker::Check($_POST['projectId']);
	$res = $db->SQLexecute($sql);
	if($db->NumRows($res) != 0){
		$row = $db->fetchAssoc($res);
		//print_r($row);
		
		$data['tip_narocila'] = $row['tip_narocila'] ;
		$data['datum_dostave'] = $row['datum_dostave'] != '0000-00-00' ? $row['datum_dostave'] : "";
		$data['brez_nakupa_komentar'] = $row['brez_nakupa_komentar'];
		$data['brez_nakupa_vzrok'] = $row['order_reason'];
		$data['Telefonska_stevilka_podjetja'] = $row['company_delivery_phone'];
		$data['Kraj_podjetja'] = $row['company_delivery_city'];
		$data['Posta_podjetja'] = $row['company_delivery_post_code'];
		$data['Naslov_podjetja'] = $row['company_delivery_address'];
		$data['davcna_stevilka'] = $row['company_delivery_tax_number'];
		$data['naziv_podjetja'] = $row['company_delivery_title'];
		$data['Telefonska_stevilka'] = $row['delivery_phone'] != null ? $row['delivery_phone'] : $row['phone1'];
		$data['Kraj'] = $row['delivery_city'] != null ? $row['delivery_city'] : $row['city'];
		$data['Posta'] = ($row['delivery_post_code'] != null && $row['delivery_post_code'] != 0)  ? $row['delivery_post_code'] : $row['post_code'];
		$data['Naslov'] = $row['address'];
		$data['Priimek'] = $row['surname'];
		$data['Ime'] = $row['firstname'];
		$data['credit_lon_stevilo_obrokov'] = $row['number_of_payments'];
		$data['placilo_na_kredit_nacin_placila'] = $row['credit_payment_type'];
		$data['enkratni_nacin_placila'] = $row['one_time_payment_type'];
		if ($row['avans_date'] == '0000-00-00') {
			//$row['avans_date'] = date("Y-m-d");
			$row['avans_date'] = "";
		}
		$data['datum_placila_avansa'] = $row['avans_date'];
		
		$data['avans_amount'] = $row['avans_amount'];;
		$data['credit_card_avans_amount'] = $row['avans_credit_amount'];;
		
		$data['avans_tip_placila'] = $row['avans_payment_type'];
		$data['avans_check'] = $row['avans'];
		$data['assistent'] = $row['assistant_id'];
		$data['tip_dostave'] = $row['tipDostave'];
		$data['izdelek'] = $row['article_id'];
		$data['kolicina_izdelkov'] = $row['product_amount'];
		$data['cena_izdelka'] = $row['product_price'];
		$data['opomba_datuma_dostave'] = $row['opomba_dostave'];
		$data['prikazi_polog'] = $row['show_deposit'];
	}
	
	$results['success'] = true;
	$results['results'] = 1;
	$results['data'] = $data != "" ? $data : "";
	
	//echo "/*$sql*/\n";
	
	echo json_encode($results);
}
if($_POST['action'] == "getPrices"){
    
    //var_dump($db);
    $sql = "SELECT * FROM ". WARPIT_CRM ."._Products WHERE id = " . StringChecker::Check($_POST['id']);
    $res = $db->SQLexecute($sql);
    
    
    $dat = $db->fetchAssoc($res);
    
	$gotovina = strval((floatval($dat['cena1']) * floatval(StringChecker::Check($_POST['quant']))));
	$kartica = strval((floatval($dat['cena2']) * floatval(StringChecker::Check($_POST['quant']))));
	
	$loan = strval((floatval($dat['cena5'] * floatval(StringChecker::Check($_POST['quant'])))));
	
	$gotovinaSingle = $dat['cena1'];
	$karticaSingle = $dat['cena12'];
	$loanSingel = $dat['cena5'];
	
	
	$sql = "SELECT * FROM ".WARPIT_CRM."._loanCreditsDefinitions as d JOIN ".WARPIT_CRM."._loanCreditsIntervals as i ON i.id = d.id_interval WHERE i.id_product = '".StringChecker::Check($_POST['id'])."' AND d.numberOfAnnuities = '".StringChecker::Check($_POST['numberOfAnnuities'])."'";
	$res = $db->SQLexecute($sql);
	$loan = $db->fetchAssoc($res);
	$loan = json_encode($loan);
	$price = array($gotovina, $kartica, $kartica, $gotovina, $loan);
	$single = array($gotovinaSingle, $karticaSingle, $karticaSingle, $gotovinaSingle, $loanSingel);
	
	$tipiPlacila = array();
    $sql = "SELECT * FROM ". WARPIT_CRM."._tipiPlacila WHERE deleted = 0 ORDER BY orderBy";
    $res = $db->SQLexecute($sql);
	$i = 0;
    while($dat = $db->fetchAssoc($res)){
    	$d = array("id" => $dat['id'], "value" => $price[$i] != "false" ? $dat['naziv_placila']." - ".$price[$i] : $dat['naziv_placila'] , "price" => $price[$i], "single" => $single[$i]);
        array_push($tipiPlacila, $d);
		$i++;
    }
	
    $result['success'] = TRUE;
    $result['results'] = sizeof($data);
    $result['rows'] = $tipiPlacila;
    print json_encode($result);
    exit;  

}
if($_POST['action'] == "saveDelyveryFinish")
{
    foreach($_POST['data'] as $key => $value)
    {
    	if($key == "delivery_finish_date"){
    		$tmpSql[] = $key ." = STR_TO_DATE('".StringChecker::Check($value)."', '%d.%m.%Y')";
    	}else
	         $tmpSql[] = $key ." = '".StringChecker::Check($value)."'";
		 $fields[] = $key; 
    }
	$tmpSql[] = " order_status = 2";
    
    $sql = "UPDATE " . WARPIT_CRM."._visitStatistic SET " . implode(',', $tmpSql) . " WHERE id = " . StringChecker::Check($_POST['projectId']);
	
	$sqlOld = "SELECT " . implode(',', $fields) . " FROM " . WARPIT_CRM."._visitStatistic WHERE id = " . StringChecker::Check($_POST['projectId']);
	$resOld = $db->SQLexecute($sqlOld);
	$dataOld = $db->fetchAssoc($resOld);
	
    $Logger->Log('sprememba_osebe', 'multiple-field-update', addslashes(implode(',', $fields)), WARPIT_CRM."._visitStatistic", json_encode($dataOld), addslashes($sql));
    $db->SQLexecute($sql);
    
    $log[] = 'status_date = NOW()';
    $log[] = 'user_type =  "'.$_SESSION['UserInfo']['user_type'].'"';
    $log[] = 'log_user =  "'.$_SESSION['UserInfo']['id'].'"';
    $log[] = 'status_state = 2';
    $log[] = 'status_comment = "'.StringChecker::Check($_POST['data']['delivery_finish_comment']).'"';
    $sql = "INSERT INTO " . WARPIT_CRM."._statusLog SET " . implode(',', $log) . ", id_order = " . StringChecker::Check($_POST['projectId']) . 
        " ON DUPLICATE KEY UPDATE " . implode(',', $log);
    $db->SQLexecute($sql);
    $Logger->Log('statusLog', 'deliveryAdded', '', WARPIT_CRM."._statusLog", '', addslashes($sql));
    //echo "/*$sql*/";
    
    $results['success'] = true;
    
    echo json_encode($results);
}elseif($_POST['action'] == 'getLoanCredit'){
    $filter[] = "DATE(i.dateFrom) < NOW()";
    $filter[] = "DATE(i.dateTo) > NOW()";
    $filter[] = "numberOfAnnuities = '".StringChecker::Check($_POST['numberOfAnnuities'])."'";
    $filter[] = "id_product = '".StringChecker::Check($_POST['id_product'])."'";
    $filter[] = "active = 1";
    
	$sql =     "SELECT * 
	           FROM ".WARPIT_CRM."._loanCreditsDefinitions as d 
	           JOIN ".WARPIT_CRM."._loanCreditsIntervals as i 
	           ON i.id = d.id_interval 
	           WHERE ".implode(" AND ", $filter);
	$res = $db->SQLexecute($sql);
	$loan = $db->fetchAssoc($res);
	echo json_encode($loan);
}
elseif($_POST['action'] == "getDeposit"){
	$sql = "SELECT * 
	       FROM ".WARPIT_CRM."._loanCreditsDefinitions as d 
	       JOIN ".WARPIT_CRM."._loanCreditsIntervals as i 
	       ON i.id = d.id_interval, 
	       ".WARPIT_CRM."._visitStatistic v  
	       WHERE i.id_product = v.article_id 
	       AND i.id_product = '".StringChecker::Check($_POST['id_product'])."' 
	       AND d.numberOfAnnuities = '".StringChecker::Check($_POST['numberOfAnnuities'])."' 
	       AND v.id = ".StringChecker::Check($_POST['id']);
	$res = $db->SQLexecute($sql);
	$loan = $db->fetchAssoc($res);
	
	$polog = $loan['DepositePrice'] * $loan['product_amount'];
	$rez['success'] = true;
	$rez['polog'] = $polog;
	echo json_encode($rez);
}
elseif($_POST['action'] == "getName"){
	$id_tel = StringChecker::Check($_POST['id_tel']);
	$sql = "SELECT CONCAT_WS(' ', firstname, surname) AS name FROM ".WARPIT_CRM."._visitStatistic WHERE id_tel = '".$id_tel."'";
	$res = $db->SQLexecute($sql);
	$row = $db->fetchAssoc($res);
	
	$rez['success'] = true;
	$rez['name'] = $row['name'];
	echo json_encode($rez);
}
?>