HEX
Server: Apache
System: Linux v38079.2is.nl 3.10.0-1160.119.1.el7.x86_64 #1 SMP Tue Jun 4 14:43:51 UTC 2024 x86_64
User: democfellows (10015)
PHP: 8.1.34
Disabled: opcache_get_status
Upload Files
File: /var/www/vhosts/creativefellows.nl/jhtaxatie.creativefellows.nl/classes/TaxationController.php
<?php

	/**
	* Description
	*/
	class TaxationController
	{
								
		function __construct($db_connection,$router,$user_id,$view=null,$user_role=null,$settings=null)//}$taxation_fields=null,$baseUrl=null)
		{
			$this->db 				= $db_connection;
			$this->router			= $router;
			$this->view 			= $view;
			$this->user_role		= $user_role;
			$this->user_id 			= $user_id;
			
			$this->settings			= $settings;			
			$this->taxation_fields	= $this->settings['taxation_fields'];
			$this->baseUrl 			= $this->settings['baseUrl'];
			$this->siteUrl 			= $this->settings['siteUrl'];		
			
			$this->heftruckinruilen = $this->settings['heftruckinruilen'];
			$this->jungheinrich 	= $this->settings['jungheinrich'];
		
			// role is user
			if($this->user_role == 1)
			{	
				
				// role user cant archive an order
				unset($this->taxation_fields["Klant"][1][5][3]);
				
				//$this->taxation_fields["Klant"][6][2] = "hidden";
				
				$this->taxation_fields["Conditie"][11][2] = "hidden";
				$this->taxation_fields["Conditie"][12][2] = "hidden";
				
				//$this->taxation_fields["Klant"][7][2] = "hidden";
				
				//print_r($this->taxation_fields["Klant"][6][1]);
				
				// and cant add a value to a taxation 
				//unset($this->taxation_fields["Klant"][5][5][3]);
			}
		}
	
		public function postHiTaxation($request, $response, $args){
			
			
			// Post
	        $post = $request->getParsedBody();
			
			// get the images
			$images = $request->getUploadedFiles();
			

			$imagename_array = [];
			
			// move uploads to folder
			foreach($images as $img_name => $img_array)
			{	

				foreach($img_array as $img_data)
				{
					
				
					$uploadFileName = "";	
					if($img_data->getError() === UPLOAD_ERR_OK)
					{
					    $uploadFileName = uniqid() .".". $this->getFileExtension($img_data->getClientFilename());
					    $img_data->moveTo( $this->getUploadPath() . $uploadFileName);
						
						// resize the image
						$imgdata_cropped = $this->compressImageUpload( $this->getUploadPath() . $uploadFileName,700,700);
						$extension = $this->getImageExtension($uploadFileName);
							
							
						// save resized image
						$this->saveCroppedImage($imgdata_cropped,$uploadFileName,$extension);
						
					}
					// set filename to post body
					$imagename_array[] = [$uploadFileName,$img_data->getClientFilename()];
				}
				
			}	
			
			
					
			$sth = $this->db->prepare(
				"INSERT INTO taxations(
						user_id,
						company,
						salutation,
						name, 
						email,
						phone,
						afkoop_inruil,
						truck_brand, 
						city, 
						truck_type, 
						truck_serial, 
						truck_year, 
						truck_hours,
						truck_battery,
						cond_hascharger,
						cond_drive,
						cond_lift,
						cond_remarks,
						taxation_tradein,
						date,
						source
					) 
				VALUES(
						:user_id,
						:company, 
						:salutation,
						:full_name,
						:email,
						:phone,
						:afkoop_inruil, 
						:truck_brand, 
						:city, 
						:truck_type, 
						:truck_serial, 
						:truck_year, 
						:truck_hours,
						:truck_battery,
						:cond_hascharger,
						:cond_drive,
						:cond_lift,
						:cond_remarks,
						:taxation_tradein,
						:datetime,
						:source
					)
				");
			


			$sth->execute(
				array(
					"user_id" => 6,
					"company" => $post["company_name"],
					"salutation" => $post["salutation"],
					"full_name" => $post["source"] == 1 ? $post["full_name"] : implode(" ",[$post["firstname"],$post["prefixname"],$post["lastname"]]),
					"email" => $post["email"],
					"phone" => $post["phone"],
			    	"afkoop_inruil" => ($post["enquiry_type"] ?? 0),
					"truck_brand" => $post["truck_brand"],
					"city" => $post["city"],
					"truck_type" => $post["truck_type"],
					"truck_serial" => $post["truck_serial"],
					"truck_year" => $post["truck_buildyear"],
					"truck_hours" => $post["truck_hours"],
					"truck_battery" => $post["truck_battery"],
					"cond_hascharger" => ($post["truck_charger"] ?? 0),
					"cond_drive" => ($post["truck_driving"] ?? 0),
					"cond_lift" => ($post["truck_lifting"] ?? 0),
					"cond_remarks" => $post["remarks"],
					"taxation_tradein" => "nnb",
					"datetime" => date('Y-m-d H:i:s'),
					"source" => $post["source"]
				)
			);

			// taxation ID
			$taxation_id = $this->db->lastInsertId();
			
			$this->newTaxationImages($this->db->lastInsertId(),$imagename_array);
			
			// return json if HI taxation
			if($post["source"] == 1){
		        return $response
		            ->withHeader('Content-Type', 'application/json')
		            ->withStatus(200);					
			}
			else{
				
				//
				// Send JH email to client with confirmation of the request
				// 
				
				$cm = new CampaignMonitorReader();
				
				// taxation
				$taxation	= $this->getTaxtionById($taxation_id);	
				
				// form
				$taxation_form = new TaxationFormReader($this->settings['taxation_fields_external']);
				$form = $taxation_form->get("",$post); 
		
				// set up template	
				$email_body = $cm->replaceText($this->settings["root_dir"]."/template_jh.html",[
					"/{logo_path}/" 		=> $this->jungheinrich["logo"],
					"/{company_name}/" 		=> $this->jungheinrich["name"],
					"/{primary_color}/" 	=> $this->jungheinrich["primary_color"],
					"/{secondary_color}/" 	=> $this->jungheinrich["secondary_color"],
					"/{subject}/" 			=> $this->jungheinrich["subject"],
					"/{email_lead}/" 		=> "Beste ". $taxation->customerSalutatioLastName(),
					"/{email_intro}/"		=> $this->jungheinrich["email_intro"],
					"/{body_html}/" 		=> $form->fieldsHtml(),
				]);
				
				
				// CM mail data
				$email_data = [
					"from" 				=> $this->jungheinrich["from"],
					"subject" 			=> implode(" ",[$this->jungheinrich["subject"],$taxation->getTruck(),$taxation->serialNumber() ]),
					"to" 				=> [$taxation->email()],
					"html" 				=> $email_body,
					"cm_label" 			=> "1. Aanvraag Jungheinrich",
				];
			
			
				// set body
				$cm->set($email_data);

				// send email
				$cm_response = $cm->send();
				
	  		    return $response
					->withRedirect("https://www.jungheinrich.nl/gebruikte-heftrucks/heftruck-inruilen-bedankt-1937954")	
		            ->withStatus(200);					
			}
			
			
		}
		
		function arrayFlatten($array){

		   $return = array();
		   foreach ($array as $key => $value) {
		       if (is_array($value)){ $return = array_merge($return, arrayFlatten($value));}
		       else {$return[$key] = $value;}
		   }
		   return $return;

		}
		
		
		/*
		 * Get Aconym on customer name
		 */
		public function getAcronym($str,$length=2)
		{
			$words 		= explode(" ", $str);
			
			if(count($words) == 1) return substr($str,0,2);
			
			$acronym 	= "";
		
			for($i=0;$i<$length;$i++)
			{
				$acronym .= $words[$i][0];
			}
		
			return $acronym;
		}
		
		
		public function getUserRole()
		{
			return $this->user_role;
		}
			
			
		/*
		 * Search DB for taxations
		 */
	    public function showSearch($request, $response, $args)
		{
			$params		= $request->getQueryParams();
			$q			= $params["q"];
			
			$view_page	= isset($params["p"]) ? $params["p"] : 1;
			$taxations 	= $this->searchTaxations($q,$view_page);
			
			
			return $this->view->render($response, 'search.php', array("router" => $this->router, "taxations" => $taxations, "header_lbl" => "Zoekresultaten","pagination" => $this->pagination,"active_page" => $view_page, "page" => $routeName,"q" =>$q));
	    }
		
		public function setPageMax($int)
		{
			$this->pageMax = $int;
		}
		
		public function getPageMax()
		{
			return $this->pageMax;// = 20;
		}
		
		
		/*
		 * Search DB for taxations
		 */
		public function searchTaxations($query,$view_page)
		{
			$view_page		= is_numeric($view_page) && $view_page > 0 ? $view_page : 1;
			$start 			= ($view_page - 1 ) * $this->getPageMax();
			$limit_query	= " LIMIT $start,". $this->getPageMax();
			
			$sql1 		= 'SELECT count(*) AS count FROM taxations WHERE company LIKE :search OR city LIKE :search OR truck_brand LIKE :search OR truck_serial LIKE :search OR advisor LIKE :search OR truck_type LIKE :search';
			$sth1 = $this->db->prepare($sql1);		
			$sth1->execute(["search" => "%$query%"]);
			
			$count = $sth1->fetch();	
			$this->pagination = ceil($count["count"]/ $this->getPageMax() );
						
			
			$sql		= 'SELECT * FROM taxations WHERE company LIKE :search OR city LIKE :search OR truck_brand LIKE :search OR truck_serial LIKE :search OR advisor LIKE :search OR truck_type LIKE :search ORDER BY company DESC '.$limit_query;
			$sth 		= $this->db->prepare($sql);
			$sth->execute(["search" => "%$query%"]);	
			
			$taxations = [];
	        while($row = $sth->fetch()) {				
	            $taxations[] = new TaxationEntity($row);
	        }		
			return $taxations;
				
		}
		
		
		/*
		 * Get routename of current request
		 */
		public function getCurrentRouteName($request)
		{
			$route 		= $request->getAttribute('route');			
			return $route ? $route->getName() : null;
		}	
			
			
		/*
		 * Get all taxations
		 */
		public function getUserTaxations($request, $response, $args)
		{
			//echo $this->getUserRole();
			
			// get routename
			$routeName 	= $this->getCurrentRouteName($request);
			
			// show gg dashboard
			$action_route 	= 'taxation';
											
			$params 		= $request->getQueryParams();
			$view_page		= isset($params["p"]) ? $params["p"] : 1;
			

			$user_taxations = $this->getTaxations(array(1,2),$view_page);
						
			return $this->view->render($response, 'dashboard.php', array("router" => $this->router, "taxations" => $user_taxations, "header_lbl" => "Taxaties", "action" => $action_route, "pagination" => $this->pagination, "active_page" => $view_page, "page" => $routeName)); 

		}
		
		
		public function getTaxationsToPrice($request, $response, $args)
		{
			
			// get routename
			$routeName 	= $this->getCurrentRouteName($request);
			
			// show gg dashboard
			$action_route = "pricing";
								
											
			$params 		= $request->getQueryParams();
			$view_page		= isset($params["p"]) ? $params["p"] : 1;
			$user_taxations = $this->getTaxations(1,$view_page);
						
			return $this->view->render($response, 'dashboard.php', array("router" => $this->router, "taxations" => $user_taxations, "header_lbl" => "Taxaties", "action" => $action_route, "pagination" => $this->pagination,"active_page" => $view_page, "page" => $routeName)); 
			
		}
		
		
		/*
		 * Archived taxations
		 */
		
		public function viewArchive($request, $response, $args)
		{
			// get routename
			$routeName 		= $this->getCurrentRouteName($request);
			
			$params 		= $request->getQueryParams();
			$view_page		= isset($params["p"]) ? $params["p"] : 1;
			$user_taxations = $this->getTaxations(3,$view_page,"DESC");
									
			return $this->view->render($response,'view_archive.php', array( 
					"router" 		=> $this->router, 
					"taxations" 	=> $user_taxations,
					"header_lbl" 	=> "Archief", 
					"action" 		=> "archive", 
					"pagination"	=> $this->pagination, 
					"active_page" 	=> $view_page, 
					"page" 			=> $routeName
				)
			);
		}
		
		
		public function getTaxationArchive($request, $response, $args)
		{
			// get routename
			$routeName 		= $this->router->pathFor('taxation.archive');//"";//$this->getCurrentRouteName($request);
			
			$params 		= $request->getQueryParams();
			$view_page		= isset($params["p"]) ? $params["p"] : 1;
			$user_taxations = $this->getTaxations(3,$view_page,"DESC");
									
			return $this->view->render($response,'dashboard.php', array(
					"taxations" 	=> $user_taxations, 
					"router" 		=> $this->router, 
					"header_lbl"	=> "Archief", 
					"action" 		=> "archive", 
					"pagination" 	=> $this->pagination, 
					"active_page" 	=> $view_page, 
					"page" 			=> $routeName
				)
			);
			
		}
		
		
		private function getTaxations($status=1,$view_page = 1,$sort = "ASC")
		{
			
			$view_page		= is_numeric($view_page) && $view_page > 0 ? $view_page : 1;
			$start 			= ($view_page - 1 ) * 20;
			$limit_query	= " LIMIT $start,20";
			
			if(is_array($status)) $status_sql = "status IN (". implode(",",$status) .")";
			else $status_sql = 'status = '.$status;
			
		

			//die($this->getUserRole());
			
			switch($this->getUserRole())
			{	
				// user only sees own active taxations
				default:
				case 1:
					
					// get archived items max 6 months old
					if($status == 3){
						
					
						// calculate archive date
						$six_months_ago = strtotime( date("Y-m-d"). ' -6 months');
						$archive_date = date('Y-m-d', $six_months_ago);
						
						// guery taxations
						$sql		= 'SELECT * FROM taxations WHERE user_id = :user_id AND '. $status_sql .' AND archive_date >= :archive_date ORDER BY date_report DESC, date DESC '.$limit_query;
						$sth 		= $this->db->prepare($sql);
						$sth->execute([
							"user_id" => $this->user_id,
							"archive_date" => $archive_date
						]);
					
						$sql1		= 'SELECT * FROM taxations WHERE user_id = :user_id AND '. $status_sql .' AND archive_date >= :archive_date';
						$sth1 		= $this->db->prepare($sql1);		
						$sth1->execute([
							"user_id" => $this->user_id,
							"archive_date" => $archive_date
						]);		
						$this->pagination = ceil($sth1->rowCount()/20);
						
					}
					else{
						
						$sql		= 'SELECT * FROM taxations WHERE user_id = :user_id AND '. $status_sql .' ORDER BY date_report DESC, date DESC '.$limit_query;
						$sth 		= $this->db->prepare($sql);
						$sth->execute(["user_id" => $this->user_id]);
					
						$sql1		= 'SELECT * FROM taxations WHERE user_id = :user_id AND '. $status_sql;
						$sth1 		= $this->db->prepare($sql1);		
						$sth1->execute(["user_id" => $this->user_id]);		
						$this->pagination = ceil($sth1->rowCount()/20);
						
					}				
					

				break;
				
				
				// Admin sees all
				case 2:
				case 14:
										
					$sql		= 'SELECT * FROM taxations WHERE '. $status_sql .' ORDER BY date '. $sort .' '.$limit_query;
					$sth 		= $this->db->prepare($sql);
					$taxations 	= $sth->execute();
					
					$sql1		= 'SELECT * FROM taxations WHERE '.$status_sql;
					$sth1 		= $this->db->prepare($sql1);		
					$sth1->execute();		
										
					$this->pagination = ceil($sth1->rowCount()/20);
					
				break;
				
				
				// admin & GG see all active taxations
				case 3:
				case 4:
								
					$sql		= 'SELECT * FROM taxations WHERE status = :status ORDER BY date '. $sort .' '.$limit_query;
					$sth 		= $this->db->prepare($sql);
					$taxations 	= $sth->execute(["status" => $status ]);
					
					$sql1		= 'SELECT * FROM taxations WHERE status = :status';
					$sth1 		= $this->db->prepare($sql1);		
					$sth1->execute(["status" => $status ]);							
					$this->pagination = ceil($sth1->rowCount()/20);
					
				break;
				
			}
							
			$user_taxations = [];
	        while($row = $sth->fetch()) {				
	            $user_taxations[] = new TaxationEntity($row);
	        }
	
			return $user_taxations;
			
		}
		
		
		public function getTaxationValues($request, $response, $args)
		{
			// qp
			$params 		= $request->getQueryParams();
			
			// page
			$view_page		= isset($params["p"]) && is_numeric($params["p"]) && $params["p"] > 0 ? $params["p"] : 1;
			$start 			= ($view_page - 1 ) * 20;
			$limit_query	= " LIMIT $start,20";
			
							
			// get taxations
			$sql		= 'SELECT * FROM taxations WHERE max_taxation_value = 0 ORDER BY date DESC'.$limit_query;
			$sth 		= $this->db->prepare($sql);
			$taxations 	= $sth->execute();
			
			//pagination
			$sql1		= 'SELECT * FROM taxations WHERE max_taxation_value = 0';
			$sth1 		= $this->db->prepare($sql1);		
			$sth1->execute();		
								
			$this->pagination = ceil($sth1->rowCount()/20);
							
			$user_taxations = [];
	        while($row = $sth->fetch()) {				
	            $user_taxations[] = new TaxationEntity($row);
	        }
	
						
			return $this->view->render($response, 'taxation-values.php', array(
				"router" => $this->router, 
				"taxations" => $user_taxations, 
				"header_lbl" => "Taxaties", 
				"action" => $action_route, 
				"pagination" => $this->pagination,
				"active_page" => $view_page, 
				"page" => $routeName)
			); 
			
		}
		
		public function approveValue($request,$response,$args)
		{
			
			$sth = $this->db->prepare("UPDATE taxations SET max_taxation_value = :value WHERE taxation_id = :taxation_id");
			$sth->execute([
				"taxation_id" => $args["id"], 
				"value" => ($args["value"] == 1 ? 1 : 2)
			]);
			
			// redirect
			$url = $this->router->pathFor("taxation.values");
			
			// taxation
			$taxation	= $this->getTaxtionById($args["id"]);	

			// confirm url
			$confirm_url = $this->settings["siteUrl"]. $this->router->pathFor('taxation.complete.external', ['id' => $args["id"],"hash" => hash('sha512', $args["id"] . $_SERVER['HTTP_USER_AGENT'])]);
			
			
			// back to taxation values pages
  		    return $response->withRedirect( $this->router->pathFor('taxation.values') );	
			
		}
		
		public function newJhTaxation($request, $response, $args)
		{
			// get routename
			$routeName 		= $this->getCurrentRouteName($request);
			
		//	$params 		= $request->getQueryParams();
		//	$view_page		= isset($params["p"]) ? $params["p"] : 1;
		//	$user_taxations = $this->getTaxations(3,$view_page,"DESC");
			
			$form = new TaxationFormReader($this->settings['taxation_fields_external']);

									
			return $this->view->render($response,'taxation/view_jh_taxation.php', [
				"form" => $form->get(),
				
			]);
		}
		
		public function confirmTaxation($request,$response,$args){
			
			// taxation
			$taxation = $this->getTaxtionById($args["id"]);	
			$view_taxation = $this->settings["siteUrl"] . $this->router->pathFor("taxation.view",["id" => $args["id"]]);
			
			$cm = new CampaignMonitorReader();
	
			// set up template	
			$email_body = $cm->replaceText($this->settings["root_dir"]."/template_jh_empty.html",[
				"/{logo_path}/" 		=> $this->jungheinrich["logo"],
				"/{company_name}/" 		=> $this->jungheinrich["name"],
				"/{primary_color}/" 	=> $this->jungheinrich["primary_color"],
				"/{secondary_color}/" 	=> $this->jungheinrich["secondary_color"],
				"/{subject}/" 			=> $this->jungheinrich["subject"],
				"/{email_intro}/"		=> "<p style=\"margin-bottom:0;padding-bottom:0;font-size:18px;\"><strong>". $taxation->getCompany() . "</strong> is akkoord gegaan met de inruilwaarde voor de <strong>". $taxation->getTruck() ."</strong> met referentienummer ". $taxation->getIdFormatted() .".</p>",
				"/{body_html}/" 		=> "<p>Je kunt het dossier direct inzien en vervolgstappen ondernemen via de onderstaande link:</p><table class=\"button primary\" style=\"Margin:0 0 16px 0;border-collapse:collapse;border-spacing:0;margin:0 0 16px 0;padding:0;text-align:left;vertical-align:top;width:auto\"><tbody><tr style=\"padding:0;text-align:left;vertical-align:top\"><td style=\"-moz-box-sizing:border-box;-moz-hyphens:auto;-webkit-box-sizing:border-box;-webkit-hyphens:auto;Margin:0;border-collapse:collapse!important;box-sizing:border-box;color:#0a0a0a;font-family:Helvetica,Arial,sans-serif;font-size:14px;font-weight:400;hyphens:auto;line-height:1.3;margin:0;padding:0;text-align:left;vertical-align:top;word-wrap:break-word\"><table style=\"border-collapse:collapse;border-spacing:0;padding:0;text-align:left;vertical-align:top;width:auto\"><tbody><tr style=\"padding:0;text-align:left;vertical-align:top\"><td style=\"-moz-box-sizing:border-box;-moz-hyphens:none;-ms-hyphens:none;-webkit-box-sizing:border-box;-webkit-hyphens:none;Margin:0;background:".$this->jungheinrich["secondary_color"] .";border:none;border-collapse:collapse!important;box-sizing:border-box;color:#fefefe;font-family:Helvetica,Arial,sans-serif;font-size:14px;font-weight:400;hyphens:none;line-height:1.3;margin:0;padding:0;text-align:left;vertical-align:top;word-break:keep-all;word-wrap:break-word\"><a href=\"". $view_taxation ."\" style=\"border:0 solid #ec6600;border-radius:3px;color:#fefefe;display:inline-block;font-family:Helvetica,Arial,sans-serif;font-size:14px;font-weight:700;line-height:1.3;padding:12px 24px 12px 24px;text-align:left;text-decoration:none\">Taxatie bekijken</a></td></tr></tbody></table></td></tr></tbody></table>",
			]);
						
			// CM mail data
			$email_data = [
				"from" 				=> $this->jungheinrich["from"],
				"subject" 			=> "3. Akkoord inruilwaarde ". ($taxation->source() == 1 ? "Heftruckinruilen" : "Jungheinrich"),
				"to" 				=> [$this->jungheinrich["copy_gg"]],
				"html" 				=> $email_body,
				"cm_label" 			=> $taxation->getCompany()." akkoord inruilwaarde",
			];
			
					
			// copy to JH inside sales
			if($taxation->replaceTruck()) array_push($email_data["to"], $this->jungheinrich["copy_jh"]); 
		
			// set body
			$cm->set($email_data);

			// send email
			$cm_response = $cm->send();
			
			// redirect url		
			if($taxation->source() == 1) $redirect = "https://heftruckinruilen.nl/gratis-taxatie/gefeliciteerd";			
			else $redirect = "https://www.jungheinrich.nl/gebruikte-heftrucks/heftruck-inruilen-gefeliciteerd-1936918";
			
			// return to page
			return $response->withRedirect($redirect);	
		}
		
		/*
		 * Get all taxations
		 */
		public function getTaxationPdf($request,$response,$args)
		{
			
			
			$taxation	= $this->getTaxtionById($args["id"]);
			$fields		= $this->getFields();
			$taxation->setFields($fields);	
			
			$this->pdfreader = new PdfReader($this->settings["font_folder"],$args["id"]);
			
			switch($args["source"]){

				// JH app
				default:
			
					if($taxation->include_remarks == 0) $fields["Conditie"][11][6] = true;
					return $this->appPdf($taxation,$fields,$args);
			
				break;
				
				// heftruckinruilen
				case 1:
			
					return $this->heftruckInruilenPdf($taxation,$args);
			
				break;
				
				// jungheinrich
				case 2:
			
					return $this->jungheinrichPdf($taxation,$args);
			
				break;
			}

			
		}
		
		
		/*
		 * Generate pdf with application branding (default)
		 */
		private function appPdf($taxation,$fields,$args)
		{

			// set source
			$this->pdfreader->setSourceFile($this->settings["taxation_pdf_app"]);

			// fonts
			$font_light = TCPDF_FONTS::addTTFfont('MuseoSans-300.ttf');
			$font_bold 	= TCPDF_FONTS::addTTFfont('MuseoSans-700.ttf');
				
						
			// Page 1
			$this->pdfreader->addPage(1);

			$this->pdfreader->pdf->setXY(204,270);
			$this->pdfreader->pdf->StartTransform();
			$this->pdfreader->pdf->rotate(90);
			
			$this->pdfreader->pdf->Translate(-23, 0);
			//$pdf->Rect(125, 70, 40, 10, 'D');
			//$pdf->Text(125, 66, 'Translate');
			
			
			$this->pdfreader->pdf->SetTextColor(0,0,0,0);
			$this->pdfreader->pdf->SetFont($font_light,"",6);	
			$this->pdfreader->pdf->writeHTMLCell(20, null, null, null, $taxation->getIdFormatted());
			$this->pdfreader->pdf->StopTransform();
	
	
			// Page 2
			$this->pdfreader->addPage(2);
			$this->pdfreader->pdf->setY(30);
			$this->pdfreader->pdf->setCellHeightRatio(1.5);
			$this->pdfreader->pdf->SetCellPadding(1.5);
			$this->pdfreader->pdf->SetLineStyle(array('width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0,0,0,0)));

			// set last Y pos for image height
			$last_image_y = array();

			foreach($fields as $name => $group_fields)
			{	
				if($name == "Foto's") $this->pdfreader->addPage(3);
	
				// table header	
				$this->pdfreader->pdf->SetFont($font_bold,"",9,'',false);

				$this->pdfreader->pdf->setFillColor(20,0,0,85);
				$this->pdfreader->pdf->SetTextColor(0,0,0,0);
				$this->pdfreader->pdf->MultiCell(180,0,$name,1,"L",true,1);

				// td
				$this->pdfreader->pdf->SetFont($font_light,"",9,'',false);
				$this->pdfreader->pdf->setFillColor(4,0,0,18);
				$this->pdfreader->pdf->SetTextColor(4,0,0,180);

				$count = 0;
				foreach($group_fields as $field => $element)
				{	

					// hide field in pdf
					if(isset($element[6]) && $element[6] == true) continue;
	
					// images
					if($name == "Foto's")
					{
		
						$el = $element[0];
		
						// add image
						if($taxation->$el){
			
							$x_start= $this->pdfreader->pdf->GetX();
							$curx 	= $this->pdfreader->pdf->GetX();
							$cury 	= $this->pdfreader->pdf->GetY();
							$width	= 60;
							$height	= 75;
			
							$this->pdfreader->pdf->SetLineStyle(array('width' => 0.5,'color' => array(255, 255, 255)));
							$i = 0;
							foreach($taxation->$el as $img){
										
								$this->pdfreader->pdf->Image($this->getUploadPath() . $img["img_name"], $curx, $cury, $width, $height, '', '', '', false, 144, '', false, false, 1, 1);
								$curx += $width; 
								$last_image_y[] = $this->pdfreader->pdf->getImageRBY();
								$i++;
				
								if($i == 3)
								{
									$curx 	= $x_start;
									$cury	= max($last_image_y);	
									$i 		= 0;						
								}
							}	
			
						}
		
		
					}
					// text
					else
					{
						$ln 	= $count == 1 ? 1 : 0;

						if($element[2] == "hidden" || $element[0] == "transport_supplier") continue;				
						elseif($element[0] == "cond_remarks" || $element[0] == "gg_remarks")
						{	
							// taxation remarks Green row
							$this->pdfreader->pdf->ln(5);
							$this->pdfreader->pdf->setFillColor(20,0,0,85);
							$this->pdfreader->pdf->SetTextColor(0,0,0,0);

							// bold font
							$this->pdfreader->pdf->SetFont($font_bold,"",9,'',false);					
							$this->pdfreader->pdf->MultiCell(180,0,$element[1],1,"L",true,1);
							$this->pdfreader->pdf->SetTextColor(4,0,0,180);
							$this->pdfreader->pdf->setFillColor(4,0,0,18);
		
						 	// regular
							$this->pdfreader->pdf->SetFont($font_light,"ff",9,'',false);
		
							if($count == 1)
							{
								$this->pdfreader->pdf->MultiCell(45,0,"",1,"L",true,0);
								$this->pdfreader->pdf->MultiCell(45,0,"",1,"L",true,1);	
							}
		
							$this->pdfreader->pdf->MultiCell(180,0,$taxation->getElementValue($element[0],$element[2]),1,"L",true,1);
							$count = 1;	
						}
						elseif($element[0] == "taxation_tradein"){	
		
							// bold font
							$this->pdfreader->pdf->SetFont($font_bold,"",9,'',false);					
							$this->pdfreader->pdf->SetTextColor(4,0,0,180);
							$this->pdfreader->pdf->setFillColor(4,0,0,18);
							$this->pdfreader->pdf->MultiCell(45,0,$element[1],1,"L",true,0);
		
						 	// regular
							$this->pdfreader->pdf->SetFont($font_light,"ff",9,'',false);
		
							$this->pdfreader->pdf->MultiCell(45,0,$taxation->getElementValue($element[0],$element[2]),1,"L",true,0);
							$count = 1;	
			
					
							$this->pdfreader->pdf->SetFont($font_bold,"",9,'',false);			
							$this->pdfreader->pdf->MultiCell(45,0,"Rapportage #",1,"L",true,0);

							// column value			
							$this->pdfreader->pdf->SetFont($font_light,"",9,'',false);
							$el = $element[0];
							$this->pdfreader->pdf->MultiCell(45,0,$taxation->getIdFormatted(),1,"L",true,1);			
						
						}
						else{
							// column name
							$this->pdfreader->pdf->SetFont($font_bold,"",9,'',false);			
							$this->pdfreader->pdf->MultiCell(45,0,$element[1],1,"L",true,0);

							// column value			
							$this->pdfreader->pdf->SetFont($font_light,"",9,'',false);
							$el = $element[0];
							$this->pdfreader->pdf->MultiCell(45,0,$taxation->getElementValue($element[0],$element[2],$element[5]),1,"L",true,$ln);			
	
						}

						$count++;
						if($count == 2) $count = 0;
					}

				}

				// clear last cells
				if($count == 1)
				{
					$this->pdfreader->pdf->MultiCell(45,0,"",1,"L",true,0);
					$this->pdfreader->pdf->MultiCell(45,0,"",1,"L",true,1);	
				}
				// space 5mm
				$this->pdfreader->pdf->ln(5);

			}

			$this->pdfreader->pdf->SetY(max($last_image_y)+5);

			// table header	
			$this->pdfreader->pdf->SetFont($font_bold,"",14,'',false);

			$this->pdfreader->pdf->setFillColor(20,0,0,85);
			$this->pdfreader->pdf->SetTextColor(0,0,0,0);
			$this->pdfreader->pdf->MultiCell(180,0,"Inruilwaarde",1,"L",true,1);

			// td
			$this->pdfreader->pdf->SetFont($font_light,"",14,'',false);
			$this->pdfreader->pdf->setFillColor(4,0,0,18);
			$this->pdfreader->pdf->SetTextColor(4,0,0,180);
			$this->pdfreader->pdf->MultiCell(180,0,$taxation->getElementValue("taxation_value","price"),1,"L",true,1);

			header("Content-type: application/pdf");
			header("Content-Disposition:attachment;filename='". $args["company_name"] .".pdf'");						
			$this->pdfreader->showInline($args["company_name"].".pdf");			
			die();
			
		}
		
		
		/*
		 * Generate pdf with Jungheinrich branding
		 */
		private function jungheinrichPdf($taxation,$args){
			
			$this->pdfreader->setSourceFile($this->settings["taxation_pdf"]);
			
			// Page 1
			$this->pdfreader->addPage(4);
			
			// Address
			$this->pdfreader->setXY(15,54);
			$this->pdfreader->addTextBelow($taxation->customerAdress(), 9);	
			
			// taxation
			$this->pdfreader->setXY(15,86);
			$this->pdfreader->addHeader(strtoupper("Taxatiewaarde"),20,[0,37,100,0]);			
			$this->pdfreader->addTextBelow(strtoupper($taxation->getTruck()), 14);		
			
			
			$this->pdfreader->pdf->writeHTMLCell(40, null,153,90, '<div style="background-color:#282e32;color:white;font-size:22;text-align:center;font-family:museosans-700;">'. $taxation->getTaxationValue(true) .',-</div>',0);
			
			
			// intro
			$intro = '<p>
				<strong>Beste '. $taxation->customerSalutatioLastName() .'</strong>,<br><br>
				Bedankt voor het aanvragen van een gratis taxatie voor uw '. $taxation->getTruck() .' met serienummer '. $taxation->serialNumber() .'. Onze experts hebben uw informatie en de foto’s beoordeeld en op basis hiervan kennen we uw truck een inruilwaarde toe van '. $taxation->getTaxationValue(true) .',-<br><br>
				<strong style="color:#ffa700;font-family:museosans-700;font-weight:bold;">Hoe nu verder? </strong>
				<br>In de mail staat een link waarmee u digitaal akkoord kunt geven op dit voorstel. Wij regelen dan de administratieve zaken en zorgen ervoor dat de transporteur een afspraak met u maakt om de heftruck op te halen.<br><br>
				<strong style="color:#ffa700;font-family:museosans-700;">Wil je meer weten? </strong><br>Bel ons dan op <a href="tel:+31172446789" style="color:black;">0172 44 67 89</a> of stuur een email naar <a href="mailto:occasion@jungheinrich.nl" style="color:black;">occasion@jungheinrich.nl</a>.
				<br><br>Met vriendelijke groet,<br>
				Jungheinrich</p>';
			
			$this->pdfreader->setXY(15,115);
			$this->pdfreader->addBody($intro, 9);	
			$this->pdfreader->addSpacer(10);
			
			$this->pdfreader->setXY(15,185);
			
			// truckdata table
			$this->pdfreader->addBody($taxation->truckDataTable("museosans-700","#ffa700") .'', 9);	
			
			// pages algemene voorwaarden 
			$this->pdfreader->addPage(5);			
			$this->pdfreader->addPage(6);

	
			if(isset($args["output"]) && $args["output"] == "base64") return $this->pdfreader->outputPdfInline($args["name"], 'S');
			else{
				header("Content-type: application/pdf");
				header("Content-Disposition:attachment;filename='". $args["company_name"] .".pdf'");						
				
				$this->pdfreader->showInline($args["name"].".pdf");			
				die();
			}
			
		}
		
		
		/*
		 * Generate pdf with HI branding
		 */
		private function heftruckInruilenPdf($taxation,$args){

			$this->pdfreader->setAzoFonts();
			$this->pdfreader->setSourceFile($this->settings["taxation_pdf"]);
			
			// Page 1
			$this->pdfreader->addPage(1);
			
			// Address
			$this->pdfreader->setXY(15,54);
			$this->pdfreader->addTextBelow($taxation->customerAdress(), 9);	
			
			// taxation
			$this->pdfreader->setXY(15,86);
			$this->pdfreader->addHeader(strtoupper("Taxatiewaarde"),20);			
			$this->pdfreader->addTextBelow(strtoupper($taxation->getTruck()), 14);		
			
			
			$this->pdfreader->pdf->writeHTMLCell(40, null,153,90, '<div style="background-color:#90cc07;color:white;font-size:22;text-align:center;font-family:azo-sans-bold;">'. $taxation->getTaxationValue(true) .',-</div>',0);
			
			
			// intro
			$intro = '<p>
					<strong style="font-family:azo-sans-bold;">Beste '. $taxation->customerName() .'</strong>,<br><br>
					Bedankt voor het aanvragen van een gratis taxatie voor jouw '. $taxation->getTruck() .' met serienummer '. $taxation->serialNumber() .'. Op basis van jouw foto’s kennen wij jouw truck een waarde toe van '. $taxation->getTaxationValue(true) .',-<br><br>
					<strong style="font-family:azo-sans-bold;color:#90cc07;">Hoe nu verder? </strong><br>
					In de mail staat een link waarmee je digitaal akkoord kunt geven op dit voorstel. Wij regelen dan de administratieve zaken en zorgen ervoor dat de transporteur een afspraak met je maakt om de heftruck op te halen.<br><br>
					<strong style="font-family:azo-sans-bold;color:#90cc07;">Wil je meer weten? </strong><br>Bel ons dan op <a href="tel:+3117276644" style="color:black;">0172 76 67 44</a> of stuur een email naar <a href="mailto:verkoop@heftruckinruilen.nl" style="color:black;">verkoop@heftruckinruilen.nl</a>.<br><br>Met vriendelijke groet,<br>
					Heftruckinruilen.nl</p>';
			
			$this->pdfreader->setXY(15,115);
			$this->pdfreader->addBody($intro, 9);	
			$this->pdfreader->addSpacer(10);
			
			$this->pdfreader->setXY(15,185);

			// truckdata table
			$this->pdfreader->addBody($taxation->truckDataTable("azo-sans-bold") .'', 9);	
			
			// pages algemene voorwaarden 
			$this->pdfreader->addPage(2);			
			$this->pdfreader->addPage(3);
			
			//return $this->pdfreader->Output("taxatie.pdf", 'S');

			
			if(isset($args["output"]) && $args["output"] == "base64") return $this->pdfreader->outputPdfInline($args["name"], 'S');
			else{
				header("Content-type: application/pdf");
				header("Content-Disposition:attachment;filename='". $args["company_name"] .".pdf'");						
				
				$this->pdfreader->showInline($args["name"].".pdf");			
				die();
			}
			
		}
		
		
		/*
		 * Get a taxtion on with an id
		 */
		public function getTaxtionById($tax_id)
		{

			$sth 		= $this->db->prepare('SELECT * FROM taxations WHERE taxation_id = :taxation_id');
			$taxation 	= $sth->execute(["taxation_id" => $tax_id]);
			
			if( $sth->rowCount() > 0 )
			{	
				$data = $sth->fetch();
				$data["images"] = $this->getTaxationImages($tax_id);
				
				return new TaxationEntity( $data );
			}
		
		}
		
		
		/*
		 * Get images on taxation
		 */
		private function getTaxationImages($taxation_id,$status=1)
		{
			$sql 	= 'SELECT * FROM taxation_img WHERE taxation_id = :taxation_id AND status = :status';
			$sth 	= $this->db->prepare($sql);
			
			$images = $sth->execute(["taxation_id" => $taxation_id,"status" => $status]);
			
			if( $sth->rowCount() > 0 ) return $sth->fetchAll();
			
		}
		
		
		/*
		 * Migrate images to taxation_img table
		 */
		public function migrateImages()
		{
			$sql		= 'SELECT * FROM taxations';
			$sth 		= $this->db->prepare($sql);
			$sth->execute();
			
			foreach($sth->fetchAll() as $taxation){
				
				$imagename_array = array(
					array($taxation["img_front"],$taxation["img_front"]),
					array($taxation["img_side"],$taxation["img_side"]),
					array($taxation["img_plate"],$taxation["img_plate"])
				);
				
				$this->newTaxationImages($taxation["taxation_id"],$imagename_array);
				
			}

		}
		
		
		/*
		 * Get all taxation fields
		 */
		public function getFields()
		{

			return $this->taxation_fields;
		}
			
		
		/*
		 * Get a form field based on input type
		 */
		public function getHTMLFields()
		{
			
			
			
			$elements = [];
			foreach( $this->taxation_fields as $groupName => $fields)
			{	
				
				foreach($fields as $i=> $field)
				{				
					$elements[$groupName][$i] = new HtmlElement($field);
				}
				
				
			}
			
			return $elements;
			
		}
		
		
		/*
		 * Get new taxation form
		 */
		public function getTaxationForm($request, $response, $args)
		{
	
			$fields	= $this->getHTMLFields();				
				
			$fields["Klant"][4]->modifyFieldType("hidden");
			$fields["Klant"][4]->modifyFieldValue(0);
						
			return $this->view->render($response, 'new_taxation.php', array("fields" => $fields));
			
		}
		
		
		public function getTaxation($request, $response, $args)
		{
		
			$taxation	= $this->getTaxtionById($args["id"]);
			$fields		= $this->getFields();	
			
			$fields["Klant"][14][2] = "input";
			$fields["Klant"][13][2] = "select";
			
		
				
		    return $this->view->render($response, 'view_taxation.php', array( "taxation" => $taxation, "fields" => $fields) );
		
		}
		
		
		public function editTaxation($request, $response, $args)
		{
	
			$taxation	= $this->getTaxtionById($args["id"]);
			$fields		= $this->getHTMLFields();		
			
		    return $this->view->render($response, 'edit_taxation.php', array( "taxation" => $taxation, "fields" => $fields) );
		}
		
		
		public function editPricing($request, $response, $args)
		{

			$taxation	= $this->getTaxtionById($args["id"]);
			$fields		= $this->getHTMLFields();	
			
			
			// change input types
			$fields["Klant"][14]->modifyFieldType("input");
			$fields["Klant"][13]->modifyFieldType("select");
			
			
//			["transport_supplier",		"Transporteur",		"hidden",	"voer hoogte in", null, [0 => "- Selecteer -", 1 => "Kamps", 2 =>  "Derden"]],	
			
			//d($fields["Klant"][11]);
			//die();
			
		    return $this->view->render($response, 'taxation_pricing.php', array("router" => $this->router, "taxation" => $taxation, "fields" => $fields) );	
		}
		
		
		/*
		 * Post new Taxtation
		 */
		public function postTaxation($request, $response, $args)
		{
			
			// get form data
		 	$data = $request->getParsedBody();
	
			// get the images
			$images = $request->getUploadedFiles();
			
			$imagename_array = array();
			
			// move uploads to folder
			foreach($images as $img_name => $img_array)
			{	
				
				foreach($img_array as $img_data)
				{
					$uploadFileName = "";	
					if($img_data->getError() === UPLOAD_ERR_OK)
					{
					    $uploadFileName = uniqid() .".". $this->getFileExtension($img_data->getClientFilename());
					    $img_data->moveTo( $this->getUploadPath() . $uploadFileName);
						
						// resize the image
						$imgdata_cropped = $this->compressImageUpload( $this->getUploadPath() . $uploadFileName,700,700);
						$extension = $this->getImageExtension($uploadFileName);
							
							
						// save resized image
						$this->saveCroppedImage($imgdata_cropped,$uploadFileName,$extension);
						
					}
					// set filename to post body
					$imagename_array[] = array($uploadFileName,$img_data->getClientFilename());
				}
				
			}	
			
			
			//die("compression");
			
			// create new taxation
			$taxation_id = $this->newTaxationDb($data);
			
			// insert taxation iamges
			$this->newTaxationImages($taxation_id,$imagename_array);
			
			// pricing url
			$pricing_url = $this->siteUrl . $this->router->pathFor('pricing.view', ['id' => $taxation_id]);
			
			// get taxation
			$taxation = $this->getTaxtionById($taxation_id);
			
			
			/*
			 * new email
			 */
  			$email 		= new TaxationEmail();
  			$advisor 	= $this->getAdvisor( $taxation->getUserId() );

			// set email template
  			$email->setTemplate("taxation",["/{advisor}/" => $advisor->getFullName(),"/{company}/"=> $taxation->getCompany(), "/{route}/" => $pricing_url]); 
			$email->setSubject("Nieuw taxatierapport " . $taxation->getCompany());
  			$email->setFromAddress( $advisor->getEmailAddress() );
  			$email->setReceiver( $this->getDefaultToEmail() );
			$email->sendEmail(); 
			

			//die($email->getBody());
			
						
  		    return $response->withRedirect("/taxation");	
		
		}
		
		private function getImageExtension($filename)
		{
			$parts 	= explode(".",$filename);
			$ext 	= end($parts);
			return strtolower($ext);
		}
				
		/**
		 * Resize image given a height and width and return raw image data.
		 *
		 * @param type $file filepath
		 * @param type $w width in px
		 * @param type $h height in px
		 * @param type $crop Crop or not
		 * @return type
		 */
		function compressImageUpload($file, $w, $h){
			
		    list($width, $height) = getimagesize($file);
		    $r = $width / $height;
		
	        if ($w/$h > $r)
			{
	            $newwidth = $h*$r;
	            $newheight = $h;
	        }
			else{
	            $newheight = $w/$r;
	            $newwidth = $w;
	        }
	    
    
		    //Get file extension
		    $ext = $this->getImageExtension($file);
    
		    switch($ext){
		        case "png":
		            $src = imagecreatefrompng($file);
		        break;
		        case "jpeg":
		        case "jpg":
		            $src = imagecreatefromjpeg($file);
		        break;
		        case "gif":
		            $src = imagecreatefromgif($file);
		        break;
		        default:
		            $src = imagecreatefromjpeg($file);
		        break;
		    }
    
		
		    $dst = imagecreatetruecolor($newwidth, $newheight);
		    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

		    return $dst;
		}
		
		
		/*
		 * Compresss and resize taxation images
		 * @param 
		 * @paramsaveCroppedImage
		 * @param  
		 */
		private function saveCroppedImage($imgData,$fileName,$extension)
		{
			
			$resizedFilename = $this->getUploadPath().$fileName; //__DIR__ . "/../public/upload/" . $fileName;
			
		    switch($extension)
			{
		        case "png":
					imagepng($imgData, $resizedFilename);
		        break;
		        
				default:
					imagejpeg($imgData, $resizedFilename);
		        break;
		        
				case "gif":
					imagegif($imgData, $resizedFilename);
		        break;
		    }

			   
		}	 
		
		
		public function viewUpload($request, $response, $args)
		{
			
			//echo $this->getUploadPath(). $args["upload"];
			$image = file_get_contents( $this->getUploadPath(). $args["upload"] );
			
			if ($image === false){
				return $this->get404Page($request, $response, $args); 
			}

			$response->write($image);
			
			// return response
			return $response
				->withHeader('Content-Type', mime_content_type($this->getUploadPath(). $args["upload"]))
				->withHeader('Content-Disposition', 'inline');
			
			
		//	return $response->withHeader('Content-Type', FILEINFO_MIME_TYPE);


		}
		
		public function get404Page($request, $response, $args){
		    
			return $this->view->render($response, '404.php');
			
		}
		
		/*
		 * Add the taxation images
		 */
		private function newTaxationImages($taxation_id,$image_array)
		{
				
			$sth = $this->db->prepare(
				"INSERT INTO taxation_img(
						taxation_id, 
						img_name,
						org_name
					) 
				VALUES(
						:taxation_id,
						:img_name,
						:org_name
					)
				");
			
			foreach($image_array as $img)
			{
				if($img == "" || $img == "0") continue;
				
				$sth->execute(
					array(
						"taxation_id" => $taxation_id,
				    	"img_name" => $img[0],
						"org_name" => $img[1]
					)
				);
			}
			
		}
		
		
		/*
		 * update an taxation with new data
		 */
		public function patchTaxation($request, $response, $args)
		{
			
			// get form data
		 	$data = $request->getParsedBody();
	
			// get the images
			$images = $request->getUploadedFiles();
			
			// array for image names
			$imagename_array = array();
			
			// move uploads to folder
			foreach($images as $img_name => $img_array)
			{	
				
				foreach($img_array as $i => $img_data)
				{
					
					if($img_data->getError() === UPLOAD_ERR_OK)
					{
					    $uploadFileName = uniqid() .".". $this->getFileExtension($img_data->getClientFilename());
					    $img_data->moveTo( $this->getUploadPath() . $uploadFileName);
						
						// resize the image
						$imgdata_cropped = $this->compressImageUpload( $this->getUploadPath() . $uploadFileName,700,700);
						$extension = $this->getImageExtension($uploadFileName);
							
							
						// save resized image
						$this->saveCroppedImage($imgdata_cropped,$uploadFileName,$extension);
						
						
						// set filename to post body
						$imagename_array[] = array($uploadFileName,$img_data->getClientFilename());
						
						// delete image that has been overridden
						$this->deleteTaxtionImage($data[$img_name."_org"][$i],0);
						
					}
					
					
					
				}
				
			}
						
			
			// check for images to be deleted
			foreach($data[$img_name."_check"] as $check_image)
			{
				if( !in_array($check_image,$data[$img_name."_org"]) ) $this->deleteTaxtionImage($check_image,0);
			}
							
			// delete taxation
			$this->updateTaxationDb($args["id"],$data);
	
			// insert taxation iamges
			$this->newTaxationImages($args["id"],$imagename_array);

			return $response->withRedirect("/taxation/".$args["id"]);		
	
		}
		
		private function getFileExtension($filename)
		{
			return pathinfo($filename, PATHINFO_EXTENSION);
		}
		
		/*
		 * delete a taxation image with given id
		 */
		private function deleteTaxtionImage($img_id,$status=0)
		{
			$sql 	= 'UPDATE taxation_img set status = :status WHERE img_id = :img_id';
			$sth 	= $this->db->prepare($sql);			
			$sth->execute(["status" => $status, "img_id" => $img_id]);	
		}
		
		
		private function setArchiveDate($taxation_id)
		{
			$sth = $this->db->prepare(
				"UPDATE taxations 
					SET 
						archive_date = :date_archive 
					WHERE
						taxation_id = :taxation_id"
			);
			$sth->execute(array(
				"taxation_id" => $taxation_id, 
				"date_archive" => date("Y-m-d")
			));
			
		}
		
		
		/*
		 * patch the princing on a taxation
		 */
		public function patchPricing($request, $response, $args)
		{
			
			// get form data
		 	$data = $request->getParsedBody();
			
			$sth = $this->db->prepare(
				"UPDATE taxations 
					SET 
						taxation_value  = :taxation_value,
						status  = :status, 
						gg_id  = :gg_id,
						gg_remarks = :gg_remarks,
						transport_supplier = :transport_supplier
					WHERE
						taxation_id = :taxation_id"
			);
			$sth->execute( array(
				"taxation_value" => $data["taxation_value"],
				"status" => $data["status"],
				"gg_remarks" => $data["gg_remarks"], 
				"taxation_id" => $args["id"], 
				"transport_supplier" => $data["transport_supplier"],
				"gg_id" => $this->user_id
			));
		
			
			// get taxation
			$taxation = $this->getTaxtionById($args["id"]);
			
			// pricing url
			$taxation_route = $this->siteUrl . $this->router->pathFor('pricing.view', ['id' => $taxation->getId()]); //http://jhtaxatie.app:8888/pdf/2/Super%20Webshops
			
			// pdf url
			$pdf_path 		= $this->siteUrl . $taxation->pdfUrl();//. $this->siteUrl . $this->router->pathFor('pdf.view', ['id' => $taxation->getId(), 'company_name' => $taxation->getCompany()]);
				
			// send mail to advisor if report has been approved
			if( $taxation->getStatus() == 3 )
			{	
				// set archive date
				$this->setArchiveDate($args["id"]);
						
				/*
				 * new email
				 */
	  			$email = new TaxationEmail;
				
				// set user to receiver
	  			$advisor = $this->getAdvisor( $taxation->getUserId() );
				
				// set user to receiver
	  			$gg_user = $this->getAdvisor( $taxation->getGgId() );
						
				// set tempalte
	  			$email->setTemplate("complete",["/{advisor}/" => $advisor->getFullName() ,"/{company}/"=> $taxation->getCompany(), "/{route}/" => $pricing_url,"/{pdf_path}/" => $pdf_path,"/{taxation_route}/" => $taxation_route, "/{gg_user_name}/" => $gg_user->getFullName()]); 
				
				//set template
	  			$email->setSubject("Waardebepaling taxatierapport " . $taxation->getCompany());
	  			
				// set from to default
				$email->setFromAddress( $this->getDefaultToEmail() );
				
				// set advisor email to receipent
	  			$email->setReceiver( $advisor->getEmailAddress() );
				
				//die($email->getBody());
				
				
				// send email
				$email->sendEmail(); 
					
			}
			
			
			
			switch($taxation->source()){
								
				// HI
				case 1:	
					
				$cm = new CampaignMonitorReader();
				
					// set up template	 
					$email_body = $cm->replaceText($this->settings["root_dir"]."/template_hi.html",[
						"/{logo_path}/" 		=> $this->heftruckinruilen["logo"],
						"/{company_name}/" 		=> $this->heftruckinruilen["name"],
						"/{primary_color}/" 	=> $this->heftruckinruilen["primary_color"],
						"/{secondary_color}/" 	=> $this->heftruckinruilen["secondary_color"],
						"/{subject}/" 			=> $this->heftruckinruilen["subject"],
						"/{email_lead}/" 		=> "Beste ". $taxation->customerName(),
						"/{email_intro}/"		=> "<p style=\"margin-bottom:0;padding-bottom:0;font-size:18px;\">Bedankt voor het aanvragen van een gratis taxatie voor jouw <strong>". $taxation->getTruck() ."</strong>. Onze experts hebben jouw informatie en de foto's beoordeeld en op basis hiervan kennen we jouw truck een inruilwaarde toe van <strong>&euro;". $taxation->getTaxationValue() ."</strong>.</p>",
						"/{body_html}/" 		=> "<p><strong style=\"color:".$this->heftruckinruilen["primary_color"]."\">Hoe nu verder?</strong><br>
													Ben je tevreden met het bod? Klik dan op de link hieronder om zo digitaal akkoord te geven op het inruilvoorstel. Wij gaan dan voor je aan de slag om alles te regelen en zorgen ervoor dat onze transporteur een afspraak met je maakt om de truck op te halen.</p><p>Op de afgesproken datum wordt jouw truck door onze transporteur gecontroleerd en op onze kosten veilig meegenomen. Hierna ontvang je van ons een creditfactuur met het afgesproken bedrag. Of kies voor een korting als je de heftruck inruilt voor een nieuw model.</p><p><strong style=\"color:".$this->heftruckinruilen["primary_color"]."\">De kleine lettertjes</strong><br>
													De inruil is een gegarandeerde inruilwaarde voor jouw heftruck. Hierbij doen we een bod op basis van de informatie die jij ons hebt gegeven. Als bij inruil blijkt dat de conditie of urenstand anders blijkt dan opgegeven behouden wij ons het recht om een andere inruilprijs te bieden.</p>
													<p>Door op onderstaande knop te klikken ga je akkoord met dit aanbod. Wij gaan voor jou aan de slag en nemen op korte termijn contact met je op.</p><table class=\"button primary\" style=\"Margin:0 0 16px 0;border-collapse:collapse;border-spacing:0;margin:0 0 16px 0;padding:0;text-align:left;vertical-align:top;width:auto\"><tbody><tr style=\"padding:0;text-align:left;vertical-align:top\"><td style=\"-moz-box-sizing:border-box;-moz-hyphens:auto;-webkit-box-sizing:border-box;-webkit-hyphens:auto;Margin:0;border-collapse:collapse!important;box-sizing:border-box;color:#0a0a0a;font-family:Helvetica,Arial,sans-serif;font-size:14px;font-weight:400;hyphens:auto;line-height:1.3;margin:0;padding:0;text-align:left;vertical-align:top;word-wrap:break-word\"><table style=\"border-collapse:collapse;border-spacing:0;padding:0;text-align:left;vertical-align:top;width:auto\"><tbody><tr style=\"padding:0;text-align:left;vertical-align:top\"><td style=\"-moz-box-sizing:border-box;-moz-hyphens:none;-ms-hyphens:none;-webkit-box-sizing:border-box;-webkit-hyphens:none;Margin:0;background:".$this->heftruckinruilen["secondary_color"].";border:none;border-collapse:collapse!important;box-sizing:border-box;color:#fefefe;font-family:Helvetica,Arial,sans-serif;font-size:14px;font-weight:400;hyphens:none;line-height:1.3;margin:0;padding:0;text-align:left;vertical-align:top;word-break:keep-all;word-wrap:break-word\"><a href=\"".$confirm_url."\" style=\"border:0 solid #ec6600;border-radius:3px;color:#fefefe;display:inline-block;font-family:Helvetica,Arial,sans-serif;font-size:14px;font-weight:700;line-height:1.3;padding:12px 24px 12px 24px;text-align:left;text-decoration:none\">Ja, ik ga akkoord met dit aanbod</a></td></tr></tbody></table></td></tr></tbody></table><p><strong style=\"color:".$this->heftruckinruilen["primary_color"]."\">Heb je nog vragen?</strong><br>
													Aarzel niet en stuur ons een e-mail via <a href=\"mailto:verkoop@heftruckinruilen.nl\" style=\"color:".$this->heftruckinruilen["primary_color"]."\">verkoop@heftruckinruilen.nl</a> of bel <a href=\"tel:0172766744\" style=\"color:".$this->heftruckinruilen["primary_color"]."\">0172 - 76 67 44</a>.</p>",
					]);
			
					// CM mail data
					$email_data = [
						"from" 				=> $this->heftruckinruilen["from"],
						"subject" 			=> implode(" ",[$this->heftruckinruilen["subject"],$taxation->getTruck(),$taxation->serialNumber() ]),
						"to" 				=> [$taxation->email()],
						"html" 				=> $email_body,
						"cm_label" 			=> "2. Taxatiewaarde Heftruckinruilen",
						"attachment_base64"	=> $this->getTaxationPdf($request,$response,["source" => $taxation->source(),"id" => $args["id"],"output" => "base64", "name" => "heftruckinruilen-". $taxation->getIdFormatted() .".pdf" ]),
						"pdf_name"			=> "heftruckinruilen-". $taxation->getIdFormatted() .".pdf"
					];
					
					// copy to JH inside sales
					if($taxation->replaceTruck()) $email_data["bcc"] = $this->heftruckinruilen["copy_jh"];
										
					// set body
					$cm->set($email_data);

					// send email
					$cm_response = $cm->send();
									
				break;
				
				// JH
				case 2:
				
					$cm = new CampaignMonitorReader();
			
					// set up template	
					$email_body = $cm->replaceText($this->settings["root_dir"]."/template_jh.html",[
						"/{logo_path}/" 		=> $this->jungheinrich["logo"],
						"/{company_name}/" 		=> $this->jungheinrich["name"],
						"/{primary_color}/" 	=> $this->jungheinrich["primary_color"],
						"/{secondary_color}/" 	=> $this->jungheinrich["secondary_color"],
						"/{subject}/" 			=> $this->jungheinrich["subject"],
						"/{email_lead}/" 		=> "Beste ". $taxation->customerSalutatioLastName(),
						"/{email_intro}/"		=> "<p style=\"margin-bottom:0;padding-bottom:0;font-size:18px;\">Bedankt voor het aanvragen van een gratis taxatie voor uw <strong>". $taxation->getTruck() ."</strong>. Onze experts hebben uw informatie en de foto's beoordeeld en op basis hiervan kennen we uw truck een inruilwaarde toe van <strong>&euro;". $taxation->getTaxationValue() ."</strong>.</p>",
						"/{body_html}/" 		=> "<p><strong style=\"color:".$this->jungheinrich["primary_color"]."\">Hoe nu verder?</strong><br>
							Bent u tevreden met het bod? Klik dan op de link hieronder om zo digitaal akkoord te geven op het inruilvoorstel. Wij gaan dan voor u aan de slag om alles te regelen en zorgen ervoor dat onze transporteur een afspraak met u maakt om de truck op te halen. Op de afgesproken datum wordt uw truck door onze transporteur gecontroleerd en op onze kosten veilig meegenomen. Hierna ontvangt u van ons een creditfactuur met het afgesproken bedrag. Of kies voor een korting als u de heftruck inruilt voor een nieuw model.</p>
													<p><strong style=\"color:".$this->jungheinrich["primary_color"]."\">De kleine lettertjes</strong><br>
													De inruil is een gegarandeerde inruilwaarde voor uw heftruck. Hierbij doen we een bod op basis van de informatie die u ons hebt gegeven. Als bij inruil blijkt dat de conditie of urenstand anders blijkt dan opgegeven behouden wij ons het recht om een andere inruilprijs te bieden.</p>
													<p>Door op onderstaande knop te klikken gaat u akkoord met dit aanbod. Wij gaan voor u aan de slag en nemen op korte termijn contact met u op.</p><table class=\"button primary\" style=\"Margin:0 0 16px 0;border-collapse:collapse;border-spacing:0;margin:0 0 16px 0;padding:0;text-align:left;vertical-align:top;width:auto\"><tbody><tr style=\"padding:0;text-align:left;vertical-align:top\"><td style=\"-moz-box-sizing:border-box;-moz-hyphens:auto;-webkit-box-sizing:border-box;-webkit-hyphens:auto;Margin:0;border-collapse:collapse!important;box-sizing:border-box;color:#0a0a0a;font-family:Helvetica,Arial,sans-serif;font-size:14px;font-weight:400;hyphens:auto;line-height:1.3;margin:0;padding:0;text-align:left;vertical-align:top;word-wrap:break-word\"><table style=\"border-collapse:collapse;border-spacing:0;padding:0;text-align:left;vertical-align:top;width:auto\"><tbody><tr style=\"padding:0;text-align:left;vertical-align:top\"><td style=\"-moz-box-sizing:border-box;-moz-hyphens:none;-ms-hyphens:none;-webkit-box-sizing:border-box;-webkit-hyphens:none;Margin:0;background:".$this->jungheinrich["secondary_color"].";border:none;border-collapse:collapse!important;box-sizing:border-box;color:#fefefe;font-family:Helvetica,Arial,sans-serif;font-size:14px;font-weight:400;hyphens:none;line-height:1.3;margin:0;padding:0;text-align:left;vertical-align:top;word-break:keep-all;word-wrap:break-word\"><a href=\"".$confirm_url."\" style=\"border:0 solid #ec6600;border-radius:3px;color:#fefefe;display:inline-block;font-family:Helvetica,Arial,sans-serif;font-size:14px;font-weight:700;line-height:1.3;padding:12px 24px 12px 24px;text-align:left;text-decoration:none\">Ja, ik ruil mijn truck graag in</a></td></tr></tbody></table></td></tr></tbody></table><p><strong style=\"color:".$this->jungheinrich["primary_color"]."\">Heeft u nog vragen?</strong><br>
													Aarzel niet en stuur ons een e-mail via <a href=\"mailto:occasion@jungheinrich.nl\" style=\"color:".$this->jungheinrich["primary_color"]."\">occasion@jungheinrich.nl</a> of bel <a href=\"tel:0172446789\" style=\"color:".$this->jungheinrich["primary_color"]."\">0172 - 44 67 89</a>.</p>",
					]);
					
					
					// CM mail data
					$email_data = [
						"from" 				=> $this->jungheinrich["from"],
						"subject" 			=> implode(" ",[$this->jungheinrich["subject"],$taxation->getTruck(),$taxation->serialNumber() ]),
						"to" 				=> [$taxation->email()],
						"html" 				=> $email_body,
						"cm_label" 			=> "2. Taxatiewaarde Jungheinrich",
						"attachment_base64"	=> $this->getTaxationPdf($request,$response,["source" => $taxation->source(),"id" => $args["id"],"output" => "base64", "name" => "jungheinrich-". $taxation->getIdFormatted() .".pdf" ]),
						"pdf_name"			=> "jungheinrich-". $taxation->getIdFormatted() .".pdf"
					];
					
					// copy to JH inside sales
					if($taxation->replaceTruck()) $email_data["bcc"] = $this->jungheinrich["copy_jh"];
					
					// set body
					$cm->set($email_data);

					// send email
					$cm_response = $cm->send();
									
				break;
				
			}
				
			// return to dashboard
			return $response->withRedirect("/pricing");
						
		}
		
		
		/*
		 * Get default to emailadress
		 */
		public function getDefaultToEmail()
		{
			return $this->settings['default_to_email'];
		}
		
		
		/*
		 * Get the upload path
		 */
		public function getUploadPath()
		{
			return $this->settings['upload_path_hidden'];
		}
			
			
		/*
		 * Get an advisor on id
		 */	
		public function getAdvisor($user_id)
		{
			
			$sth 		= $this->db->prepare("SELECT * FROM users WHERE user_id LIKE :user_id");
			$user 		= $sth->execute(array("user_id" => $user_id));						
			return new JhUser( $sth->fetch() );

		}
		
				
		/*
		 * Delete a given taxation based in taxation ID
		 */
		public function deleteTaxation($request, $response, $args)
		{
			
			$sql 	= 'DELETE FROM taxations WHERE taxation_id = :taxation_id';
			$sth 	= $this->db->prepare($sql);			
			$sth->execute(["taxation_id" => $args["id"]]);	

			return $response->withRedirect("/taxation");
			
		}
		
		
		/*
		 * Insert a new taxation in the database
		 */
		public function newTaxationDb($post)
		{

			$sth = $this->db->prepare(
				"INSERT INTO taxations(
						user_id,
						company, 
						branche, 
						afkoop_inruil,
						truck_brand, 
						city, 
						date_report, 
						advisor,
						truck_type, 
						truck_serial, 
						truck_year, 
						truck_capacity, 
						truck_hours, 
						truck_drive, 
						truck_masttype, 
						truck_vorklengte, 
						truck_h1, 
						truck_h3,
						truck_sideshift,
						truck_mug,
						truck_battery,
						truck_battery_build,
						cond_global,
						cond_hascharger,
						cond_drive,
						cond_lift,
						cond_cabin,
						cond_chair,
						cond_break,
						cond_dashboard,
						cond_tires,
						cond_power_stear,
						cond_dents,
						cond_remarks,
						transport_loading,
						transport_door_height,
					 	taxation_tradein,
						date,
						status
					) 
				VALUES(
						:user_id,
						:company, 
						:branche, 
						:afkoop_inruil, 
						:truck_brand, 
						:city, 
						:date_report, 
						:advisor,
						:truck_type, 
						:truck_serial, 
						:truck_year, 
						:truck_capacity, 
						:truck_hours, 
						:truck_drive, 
						:truck_masttype, 
						:truck_vorklengte, 
						:truck_h1, 
						:truck_h3,
						:truck_sideshift,
						:truck_mug,
						:truck_battery,
						:truck_battery_build,
						:cond_global,
						:cond_hascharger,
						:cond_drive,
						:cond_lift,
						:cond_cabin,
						:cond_chair,
						:cond_break,
						:cond_dashboard,
						:cond_tires,
						:cond_power_stear,
						:cond_dents,
						:cond_remarks,
						:transport_loading,
						:transport_door_height,
						:taxation_tradein,
						:datetime,
						:status
					)
				");
			
			//$this->d($sth);

			$sth->execute(
				array(
					"user_id" => $this->user_id,
			    	"company" => $post["company"],
					"branche" => $post["branche"],
					"afkoop_inruil" => $post["afkoop_inruil"],
					"truck_brand" => $post["truck_brand"],
					"city" => $post["city"],
					"date_report" => $post["date_report"],
					"advisor" => $post["advisor"],
					"truck_type" => $post["truck_type"],
					"truck_serial" => $post["truck_serial"],
					"truck_year" => $post["truck_year"],
					"truck_capacity" => $post["truck_capacity"],
					"truck_hours" => $post["truck_hours"],
					"truck_drive" => $post["truck_drive"],
					"truck_masttype" => $post["truck_masttype"],
					"truck_vorklengte" => $post["truck_vorklengte"],
					"truck_h1" => $post["truck_h1"],
					"truck_h3" => $post["truck_h3"],
					"truck_sideshift" => 0,//isset($post["truck_sideshift"]) ? $post["truck_sideshift"] : 0,
					"truck_mug" => $post["truck_mug"],
					"truck_battery" => $post["truck_battery"],
					"truck_battery_build" => $post["truck_battery_build"],
					"cond_global" => $post["cond_global"],
					"cond_hascharger" => isset($post["cond_hascharger"]) ? $post["cond_hascharger"] : 0 ,
					"cond_drive" => isset($post["cond_drive"]) ? $post["cond_drive"] : 0 ,
					"cond_lift" => isset($post["cond_lift"]) ? $post["cond_lift"] : 0 ,
					"cond_cabin" => isset($post["cond_cabin"]) ? $post["cond_cabin"] : 0 ,
					"cond_chair" => 0,//isset($post["cond_chair"]) ? $post["cond_chair"] : 0 ,
					"cond_break" => 0,//isset($post["cond_break"]) ? $post["cond_break"] : 0 ,
					"cond_dashboard" => 0,//isset($post["cond_dashboard"]) ? $post["cond_dashboard"] : 0 ,
					"cond_tires" => 0,//isset($post["cond_tires"]) ? $post["cond_tires"] : 0 ,
					"cond_power_stear" => 0,//isset($post["cond_power_stear"]) ? $post["cond_power_stear"] : 0 ,
					"cond_dents" => 0,//isset($post["cond_dents"]) ? $post["cond_dents"] : 0 ,
					"cond_remarks" => $post["cond_remarks"],
					"transport_loading" => isset($post["transport_loading"]) ? implode(",",$post["transport_loading"]) : null,
					"transport_door_height" => $post["transport_door_height"],
					//"transport_supplier" => $post["transport_supplier"],
					"taxation_tradein" => $post["taxation_tradein"],
					"datetime" => date('Y-m-d H:i:s'),
					"status" => $post["status"]
				)
			);
			
			return $this->db->lastInsertId();
			
		}
		
		
		/*
		 * Update given taxation
		 */
		public function updateTaxationDb($taxation_id,$post)
		{
			$sth = $this->db->prepare(
				"UPDATE taxations 
					SET 
						company = :company, 
						branche = :branche, 
						afkoop_inruil = :afkoop_inruil,
						truck_brand = :truck_brand, 
						city = :city, 
						date_report = :date_report,
						advisor = :advisor,
						truck_type = :truck_type, 
						truck_serial = :truck_serial, 
						truck_year = :truck_year, 
						truck_capacity = :truck_capacity, 
						truck_hours = :truck_hours, 
						truck_drive = :truck_drive, 
						truck_masttype = :truck_masttype, 
						truck_vorklengte = :truck_vorklengte, 
						truck_h1 = :truck_h1, 
						truck_h3 = :truck_h3,
						truck_sideshift = :truck_sideshift,
						truck_mug = :truck_mug,
						truck_battery = :truck_battery,
						truck_battery_build = :truck_battery_build,
						cond_global = :cond_global,
						cond_drive = :cond_drive,
						cond_hascharger = :cond_hascharger,
						cond_lift = :cond_lift,
						cond_cabin = :cond_cabin,
						cond_chair = :cond_chair,
						cond_break = :cond_break,
						cond_dashboard = :cond_dashboard,
						cond_tires = :cond_tires,
						cond_power_stear = :cond_power_stear,
						cond_dents = :cond_dents,
						cond_remarks = :cond_remarks,
						transport_loading = :transport_loading,
						transport_door_height = :transport_door_height,
						taxation_tradein = :taxation_tradein,
						status = :status
				WHERE taxation_id = :taxation_id"
			);
			
			$sth->execute(
				array(
			    	"company" => $post["company"],
					"branche" => $post["branche"],
					"truck_brand" => $post["truck_brand"],
					"afkoop_inruil" => $post["afkoop_inruil"],
					"city" => $post["city"],
					"date_report" => $post["date_report"],
					"advisor" => $post["advisor"],
					"truck_type" => $post["truck_type"],
					"truck_serial" => $post["truck_serial"],
					"truck_year" => $post["truck_year"],
					"truck_capacity" => $post["truck_capacity"],
					"truck_hours" => $post["truck_hours"],
					"truck_drive" => $post["truck_drive"],
					"truck_masttype" => $post["truck_masttype"],
					"truck_vorklengte" => $post["truck_vorklengte"],
					"truck_h1" => $post["truck_h1"],
					"truck_h3" => $post["truck_h3"],
					"truck_sideshift" => 0,//isset($post["truck_sideshift"]) ? $post["truck_sideshift"] : 0,
					"truck_mug" => $post["truck_mug"],
					"truck_battery" => $post["truck_battery"],
					"truck_battery_build" => $post["truck_battery_build"],
					"cond_global" => $post["cond_global"],
					"cond_drive" => isset($post["cond_drive"]) ? $post["cond_drive"] : 0 ,
					"cond_hascharger" => isset($post["cond_hascharger"]) ? $post["cond_hascharger"] : 0 ,
					"cond_lift" => isset($post["cond_lift"]) ? $post["cond_lift"] : 0 ,
					"cond_cabin" => isset($post["cond_cabin"]) ? $post["cond_cabin"] : 0 ,
					"cond_chair" => 0,//isset($post["cond_chair"]) ? $post["cond_chair"] : 0 ,
					"cond_break" => 0,//isset($post["cond_break"]) ? $post["cond_break"] : 0 ,
					"cond_dashboard" => 0,//isset($post["cond_dashboard"]) ? $post["cond_dashboard"] : 0 ,
					"cond_tires" => 0,//isset($post["cond_tires"]) ? $post["cond_tires"] : 0 ,
					"cond_power_stear" => 0,//isset($post["cond_power_stear"]) ? $post["cond_power_stear"] : 0 ,
					"cond_dents" => 0,//isset($post["cond_dents"]) ? $post["cond_dents"] : 0 ,
					"cond_remarks" => $post["cond_remarks"],
					
					"transport_loading" => isset($post["transport_loading"]) ? implode(",",$post["transport_loading"]) : null,
					"transport_door_height" => $post["transport_door_height"],
					
					"status" => $post["status"],
					//"taxation_value" => $post["taxation_value"],
					"taxation_tradein" => $post["taxation_tradein"],
					"taxation_id" => $taxation_id
				));
				
		}
		
				
		/*
		 * Debug an array or object
		 */
		public function d($str)
		{
			echo "<pre>";
			print_r($str);
			echo "</pre>";
		}
		
		
	}

?>