<?php
class Assignment {
	private $hasQuotes, $PRIVATE_KEY, $TABLE_NAME;
	public function __construct($ID){
		global $con;
		if(strtoupper(substr($ID,0,1)) == "A"){
			$ID = substr($ID,1,10);
		}
		//
		//	Private Key
		//
		$this->PRIVATE_KEY = "AssignmentID";
		//
		// Table name
		//
		$this->TABLE_NAME = "ASSIGNMENT_HEAD";
		$this->ID = $ID;
		if(!is_null($ID)){
				$this->init($ID);
		}
	}
	public function create(){
		global $con;

		$query = "INSERT INTO `{$this->TABLE_NAME}` (`{$this->PRIVATE_KEY}`) VALUES (NULL)";
		$result = mysqli_query($con, $query);
		$id = mysqli_insert_id($con);
		$this->init($id);
	}
	private function init($ID){
		global $con;
		$this->ID = $ID;
		//
		// Get Table Column and add to object.
		//
		$query = "SELECT * FROM `{$this->TABLE_NAME}` WHERE `{$this->PRIVATE_KEY}` = $ID";
		//echo $query;
		$result = mysqli_query($con, $query);
		$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
		foreach($row as $key => $value){
				$this->$key = $value;
		}
		//
		// Get Columns Names and either if they need quotes in a query or not.
		//
		$this->hasQuotes = [];
		$query = "SHOW COLUMNS FROM `{$this->TABLE_NAME}`";
		$result = mysqli_query($con,$query);
		while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
			if(stripos($row['Type'], "int") === 0 || stripos($row['Type'], "double") === 0 || stripos($row['Type'], "tinyint") === 0 || stripos($row['Type'], "numeric") === 0 || stripos($row['Type'], "double") === 0 || stripos($row['Type'], "decimal") === 0 || stripos($row['Type'], "float") === 0 || stripos($row['Type'], "bigint") === 0 || stripos($row['Type'], "real") === 0 || stripos($row['Type'], "bool") === 0){
				$this->hasQuotes[$row['Field']] = false;
			}else{
				$this->hasQuotes[$row['Field']] = true;
			}
		}
	}
	public function getTokenKey(){
		$realKey = md5($this->AssignmentID . "AssigmentWestingPR");
		$realKey = substr($realKey, -16);
		return $realKey;
	}
	//
	// Function to create a "column = value" string usable by mysql query;
	//
	public function RemoveFromDelivery(){
		$this->DeliveryUser = NULL;
		$this->PickupDate = NULL;
		$this->save();
	}
	private function saveString($Column, $Value){

		if(is_null($Value)){
			$returnValue = "NULL";
		}else if(strtoupper($Value) == "NOW()"){
			$returnValue = "NOW()";
		}else{
			$returnValue = ($this->hasQuotes[$Column])?"'$Value'":"$Value";
		}
		return " `$Column` = $returnValue ";
	}
	//
	// function to save all the values in the object to the table.
	//
	public function save(){
		global $con;

		$query = "UPDATE `{$this->TABLE_NAME}` SET ";
		$saveQuery = [];
		foreach($this->hasQuotes as $fieldName => $quotes){
			if($fieldName != $this->PRIVATE_KEY){
				$saveQuery[] = $this->saveString($fieldName, $this->$fieldName);
			}
		}
		$query .= implode(", ", $saveQuery) . " WHERE `{$this->PRIVATE_KEY}` = " . $this->ID;
		return mysqli_query($con, $query);
	}
}


?>
