<?

class TClient {

	private $db;
	private $localpath;
	private $adblogin;
	private $paths;
	public $remotedb;

	function __construct($db, $localpath, $paths) {
		$this->db = $db;
		$this->localpath = $localpath;
		$this->paths = $paths;
		$this->adblogin = Tacc_api_config::$adblogin;
		$this->adatabase = Tacc_api_config::$adblogin["database"];
	}

	//Minimum required fields
	public function Client_CheckBasic($client, $entity, &$err) {
		$form = array_merge($client, $entity);
		$req["email"] = "Please enter a valid Username";
		$req["password"] = "Please enter a valid Password";
		$req["email"] = "Please enter a valid Email address";
		$req["name"] = "Please enter a valid First Name";
		$req["address_country"] = "Please select a valid Country";
		if ($form["address_country"] == "US")
			$req["address_state"] = "Please select a valid state";

		$msg = ValidPassword($form["password"]);
		if ($msg != "")
			$req["password"] = $msg;

		$msg = ValidPassword($form["password"]);
		if ($msg != "")
			$req["password"] = $msg;

		if (!ValidEmail($form["email"]))
			unset($form["email"]);

		$res = CheckRequiredFields($err, $req, $form);

		return $res;
	}

	//Add new client to database - also create account & entity
	public function Client_New($client, $entity) {
		//global $acc_api_url, $acc_api_path;
		//Check if we should use the Province instead of the State
		if ($entity["address_country"] != "US") {
			if (!empty($entity["address_province"]))
				$entity["address_state"] = $entity["address_province"];
		}
		unset($entity["address_province"]);

		//set up extra entity/client data
		$entity["date_created"] = "NOW()";

		//first insert the client data
		$this->db->AddStatement('NOW()', 'date_created');
		$this->db->insert("client", $client);
		$clientID = $this->db->insert_id();

		//create the spacial API class
		require_once(Tacc_api_config::$acc_api_path . "/class.api.spacial.php");
		$spc = new TSpacial_api();
		$spc->api_url = Tacc_api_config::$acc_api_url;

		//create new entity and account on accounting system
		$spci = $spc->Spacial_NewClient($entity, $clientID);
		$entityID = $spci["entityID"];
		$accountID = $spci["accountID"];

		//data to update client
		$data = array();
		$data["entityID"] = $entityID;
		$data["accountID"] = $accountID;

		//update client with entityID and accountID
		settype($clientID, "integer");
		$this->db->update("client", $data, "(ID = $clientID)");

		//Update client data
		$client["clientID"] = $clientID;
		$client["entityID"] = $entityID;
		$client["accountID"] = $accountID;

		return $client;
	}

	public function Client_FindByEmail($email) {
		$database = $this->adblogin["database"];
		$sql = "	SELECT c.*, c.ID as clientID
                FROM $database.entity e, client c
               WHERE (e.email = :email)
                 AND (c.entityID = e.ID)
    ";

		$this->db->AddStr($email);
		$this->db->open($sql);
		if ($this->db->num_rows() > 0) {
			$row = $this->db->row();
			return $row;
		}
		return false;
	}

	/* -----------------------------------------------------------------------------\
	  |  Client->lookup_id( $email )                                                 |
	  |                                                                              |
	  |  PARAMATERS                                                                  |
	  |	   $email : STRING - Email Address                                         |
	  |  RESULT                                                                      |
	  |     Entity ID of client OR FALSE if not found                                |
	  |                                                                              |
	  \----------------------------------------------------------------------------- */

	public function client_LookupEmail($email) {
		$database = $this->adblogin["database"];
		$sql = "	SELECT e.ID
                FROM $database.entity e, client c
               WHERE (e.email = :email)
                 AND (c.entityID = e.ID)
    ";

		$this->db->AddStr($email);
		$this->db->open($sql);
		if ($this->db->num_rows() > 0) {
			$row = $this->db->row();
			return $row['ID'];
		}
		return 0;
	}

	public function ReadEntity($entityID) {
		$database = $this->adblogin["database"];
		$sql = "SELECT * FROM $database.entity WHERE (ID = :entityID)";

		$this->db->addInt($entityID);
		$this->db->open($sql);
		if ($this->db->num_rows() > 0) {
			$row = $this->db->row();
			return $row;
		}
		return false;
	}

	public function client_add($client) {
		//Set up some default values if none is supplied
		if (empty($client["comment"]))
			$client['comment'] = '';
		if (empty($client["date_created"]))
			$this->db->AddStatement('NOW()', 'date_created');

		$this->db->insert('client', $client);
		$clientID = $this->db->insert_id();
		return $clientID;
	}

	public function client_update($clientID, $client) {
		if (!empty($client)) {
			//$this->db->AddInt($clientID);
			$this->db->update('client', $client, "ID = :clientID", $clientID);
			return true;
		}
		else
			return false;
	}

	public function client_CheckPassword($entityID, $password, &$err) {
		$this->db->AddInt($entityID);
		$this->db->AddStr($password);
		$this->db->open("SELECT * FROM entity WHERE (ID = :ID) AND (password = :password) ");
		if ($this->db->num_rows() > 0)
			return true;
		else {
			$err["password"] = "Your current password does not match our records.";
			return false;
		}
	}

	public function client_sendemail($clientID, $what = 'general', $extrainfo = '', $masteraccount = '') {
		require_once(Tacc_api_config::$acc_api_path . "/config.accounts.php");
		require_once(Tacc_api_config::$acc_api_path . "/common.func.php");
		require_once(Tacc_api_config::$acc_api_path . "/class.api.spacial.php");
		//require_once($this->localpath."/mail.php");
		require_once($this->localpath . "/class.client_functions.php");
		$smarty = Tacc_api_config::$smarty;

		$paths = $this->paths;

		//Types of emails to send
		/*
		 *  1. Client creation
		 *  2. Lost password retrieve
		 *  3. Invoice payment
		 *  4. Refund/Chargeback/Fraud
		 *  5. Payment due
		 *  6. Email invoice with payment instructions
		 */

		$from_email = "debug@spacialaudio.com";
		$oldpath1 = $smarty->template_dir;
		$oldpath2 = $smarty->compile_dir;

		$smarty->template_dir = $this->paths['web'] . "/modules/clientsection/templates";
		//$smarty->template_dir = $this->paths['localpath']."/templates";
		//$smarty->compile_dir  = $this->paths['localpath']."/templates_c";

		$smarty->assign("acc_api_path", Tacc_api_config::$acc_api_path);
		$smarty->assign("is_email", true);
		if ($clientID > 0) {
			$database = $this->adatabase; //Accounting DB
			$this->db->AddInt($clientID);
			$this->db->open("SELECT
                            c.ID as clientID,
                            c.accountID as accountID,
                            e.*
                         FROM client c, $database.entity e
                        WHERE (c.entityID = e.ID)
                          AND (c.ID = :clientID)");
			if ($this->db->num_rows() > 0) {
				$client = $this->db->row();
				$entity = $client;
				$client["ID"] = $client["clientID"];

				$smarty->assign("client", $client);
				$smarty->assign("entity", $entity);
			}
			else
				$this->err["email"] = "Unable to find client ($clientID)";
		}//clientID > 0

		$smarty->assign('spacialurl', 'http://spacial.com/');

		/*
		  $spacial_params = array();
		  $spacial_params['name'] = "clients.email";
		  $spacial_params['chat'] = 'off';
		  $spacial_params['menu'] = 'off';
		  $spacial_params['addthis'] = 'off';

		  require($this->paths['web']."/spacial_template.php");
		  $smarty->assign('spacial_header',"static.header.$spacial_params[name].tpl");
		  $smarty->assign('spacial_footer',"static.footer.$spacial_params[name].tpl");
		  $smarty->assign('paths',$this->paths);
		 *
		 */

		//What email are we going to send and handle that request
		switch ($what) {
			case "general" :
				if (!empty($extrainfo["template"]))
					$body = $smarty->fetch($extrainfo["template"]);
				if (!empty($extrainfo["body"]))
					$body = $extrainfo["body"];
				$subject = $extrainfo["subject"];
				$this->sas_mail($client["email"], $subject, $body, $from_email, $extrainfo["mimetype"]);
				break;

			case "newsystem" :
				$body = $smarty->fetch("email.newsystem.tpl");
				$subject = "[Spacial] New client section";
				$this->sas_mail($client["email"], $subject, $body, $from_email, "html");
				break;

			case "reminder" :
				$body = $smarty->fetch("email.reminder.tpl");
				$subject = "[Spacial] Lost password reminder";
				$this->sas_mail($client["email"], $subject, $body, $from_email, "text");
				break;

			case "reverse" :
				$invoiceID = $extrainfo["invoice"]["ID"];
				$paymentURL = PaymentURL("INV", $invoiceID, $entity, "CLI");
				$smarty->assign("paymentURL", $paymentURL);

				require_once(Tacc_api_config::$acc_api_path . "/class.api.invoice.php");
				$inv = new TInvoice_api();
				$inv->api_url = Tacc_api_config::$acc_api_url;

				$inv->Invoice_SmartyInvoice($invoiceID, $smarty);
				$mode = $smarty->fetch($params["template"]);
				$tempalte_vars = $smarty->get_template_vars('invoice');
				$inv_ID = $tempalte_vars['ID'];
				Def($params["subject"], "[Spacial] Invoice reversed (INV $inv_ID)");
				Def($params["template"], "email.invoicereversed.tpl");

				$body = $smarty->fetch($params["template"]);
				$subject = $params["subject"];

				$this->sas_mail($client["email"], $subject, $body, $from_email, "html");
				break;

			case "invoice" :
				$invoiceID = $extrainfo["invoiceID"];
				$email = $extrainfo["email"];
				$paymentURL = PaymentURL("INV", $invoiceID, $entity, "CLI");
				$smarty->assign("paymentURL", $paymentURL);

				require_once(Tacc_api_config::$acc_api_path . "/class.api.invoice.php");
				$inv = new TInvoice_api();
				$inv->api_url = Tacc_api_config::$acc_api_url;

				$inv->Invoice_SmartyInvoice($invoiceID, $smarty);
				$tempalte_vars = $smarty->get_template_vars('invoice');
				$inv_mode = strtoupper($tempalte_vars['invoicemode']);
				$inv_ID = $tempalte_vars['ID'];

				$smarty->assign("info", $extrainfo);
				$body = $smarty->fetch("email.invoice.tpl");
				$subject = "[Spacial] $inv_mode (INV$inv_ID)";

				$email = $extrainfo["email"];
				if (empty($email))
					$email = $client["email"];
				$this->sas_mail($email, $subject, $body, $from_email, "html");
				break;

			case "statement" :
				$paymentURL = PaymentURL("ACC", $client["accountID"], $entity, "CLI");
				$smarty->assign("paymentURL", $paymentURL);

				//create the API class
				require_once(Tacc_api_config::$acc_api_path . "/class.api.account.php");
				$acc = new TAccount_api();
				$acc->api_url = Tacc_api_config::$acc_api_url;

				//Get the data from the accounting system
				$acc->Account_SmartyStatement($client["accountID"], $smarty, $extrainfo["date_begin"], $extrainfo["date_end"], true);

				$body = $smarty->fetch("email.statement.tpl");
				$subject = "[Spacial] Account Statement";

				if (!empty($extrainfo["email"]))
					$email = $extrainfo["email"];
				else
					$email = $client["email"];

				$this->sas_mail($email, $subject, $body, $from_email, "html");
				break;

			case "sass" :
				$verify = $extrainfo["verify"];
				$smarty->assign("verify", $verify);
				$body = $smarty->fetch("email.sass.tpl");
				$subject = "[Spacial] SASS registration information";
				$this->sas_mail($client["email"], $subject, $body, $from_email, "text");
				break;

			case "sassfree" :
				$verify = $extrainfo["verify"];
				$smarty->assign("verify", $verify);
				$body = $smarty->fetch("email.sass.freesession.tpl");
				$subject = "[Spacial] SASS registration information";
				$this->sas_mail($client["email"], $subject, $body, $from_email, "text");
				break;

			case "sass.done" :
				$body = $smarty->fetch("email.sass.done.tpl");
				$subject = "[Spacial] SASS registration completed";
				$this->sas_mail($client["email"], $subject, $body, $from_email, "text");
				break;


			case "merge" :
				$smarty->assign("client2", $extrainfo);
				$body = $smarty->fetch("email.merge.tpl");
				$subject = "[Spacial] Accounts merged";
				$this->sas_mail($client["email"], $subject, $body, $from_email);
				$this->sas_mail($extrainfo["email"], $subject, $body, $from_email);
				break;

			case "paypal-pending" :
				$smarty->assign("paypal", $extrainfo);
				$body = $smarty->fetch("email.paypal-pending.tpl");
				$subject = "[Spacial] Pending transaction";
				$this->sas_mail($client["email"], $subject, $body, $from_email);
				break;

			case "DJSeatExtend" :
				$smarty->assign("products", $extrainfo);
				$body = $smarty->fetch("email.djseat.extend.tpl");
				$subject = "[Spacial] DJ Seat license extention";

				$this->sas_mail($client["email"], $subject, $body, $from_email, "html");
				break;

			case "DJSeatExtendV4" :
				$smarty->assign("entity", $client);
				$body = $smarty->fetch("email.djseat.extendv4.tpl");
				$subject = "[Spacial] DJ Seat license extention";
				$this->sas_mail($client["email"], $subject, $body, $from_email, "html");
				break;

			case "products" :
				$obj_cf = new TClient_Functions($this->db, $paths, $session["entity"]);
				$obj_cf->acc_api_url = Tacc_api_config::$acc_api_url;
				$obj_cf->acc_api_path = Tacc_api_config::$acc_api_path;
				$obj_cf->acc_api_password = Tacc_api_config::$acc_api_password;

				$invoice = $extrainfo["invoice"];
				$invoiceID = $invoice["ID"];
				Def($invoiceID, $invoice["invoiceID"]);
				$products = array();
				if ($invoiceID > 0) {
					$this->db->AddInt($invoiceID);
					$this->db->open("SELECT p.*, cp.* FROM product p, client_product cp WHERE (cp.productID = p.ID) AND (cp.invoiceID = :invoiceID)");
					if ($this->db->num_rows() > 0) {
						while ($product = $this->db->row()) {
							$product["url"] = $obj_cf->BuildDownloadURL($product["filename"], $clientID);

							//Handle special M1 SE case
							if ($product["productID"] == 22) {
								$product["url"] = "http://www.gomusic1.com/Music_Scheduler/Demo/Music_1_For_SAM/music_1_for_sam.html";
								$product["regkey"] = "<small>To be provided by Music1 via seperate email</small>";
							}

							//Add product to list
							$products[] = $product;
						}
					}
				}

				$smarty->assign("invoice", $invoice);
				$smarty->assign("products", $products);

				$body = $smarty->fetch("email.products.tpl");
				$subject = "[Spacial] Order details";

				$this->sas_mail($client["email"], $subject, $body, $from_email, "html");
				break;

			case "m1se_reverse":
			case "m1se" :
				$invoice = $extrainfo["invoice"];
				$invoiceID = $invoice["ID"];
				Def($invoiceID, $invoice["invoiceID"]);
				$products = array();
				if ($invoiceID > 0) {
					$this->db->AddInt($invoiceID);
					$this->db->open("SELECT p.*, cp.* FROM product p, client_product cp WHERE (cp.productID = p.ID) AND (cp.invoiceID = :invoiceID) AND (p.ID IN (22))");
					if ($this->db->num_rows() > 0)
						$products = $this->db->rows();
				}

				$smarty->assign("invoice", $invoice);
				$smarty->assign("products", $products);

				$body = $smarty->fetch("email.$what.tpl");
				$subject = "[Spacial] M1 SE ORDER";

				$this->sas_mail("steve@gomusic1.com", $subject, $body, $from_email, "html");
				break;

			/*
			  case "refund"      :
			  case "fraud"       :
			  case "chargeback"  : $transactionID = $extrainfo;
			  $this->db->openEx("SELECT * FROM transaction WHERE ID = :transID",$transactionID);
			  $transaction = $this->db->row();
			  $smarty->assign("transaction",$transaction);

			  $body = $smarty->fetch("email.transactionreversed.tpl");
			  $subject = "[SpacialAudio] Order reversed";

			  $this->sas_mail($client["email"] , $subject, $body, $from_email, "html");
			  break;
			 */
		}

		$smarty->template_dir = $oldpath1;
		$smarty->compile_dir = $oldpath2;
		$smarty->assign("is_email", false);
	}

	public function Extend_DJSeats($clientID, $trace = false) {
		//Each quarter, extend all DJ Seat licenses for another 3 months
		require_once($this->localpath . "/class.product.php");
		$product = new TProduct($this->db, $this->localpath);

		//Output details to screen
		if ($trace)
			echo "==================== ClientID: $clientID ===========================<br>\n";

		$this->db->openEx("SELECT * FROM client_product WHERE (productID IN (15,21)) AND (clientID = :clientID) ", $clientID);
		if ($this->db->num_rows() > 0) {
			$products = array();
			$client_products = $this->db->rows();
			foreach ($client_products as $client_product) {
				//1. Generate ney key
				$keyinfo = $product->product_regkey($clientID, $client_product["productID"], false);
				$regkey = $keyinfo["key"];
				$date_expire = $keyinfo["date_expire"];

				//2. Update registration key
				$clientproductID = $client_product["ID"];
				$this->db->openEx("UPDATE client_product SET regkey=:regKey, date_expire=:date_expire WHERE (ID = :cpID) ", $regkey, $date_expire, $clientproductID);

				//Save details for email
				$client_product["name"] = "DJ Seat license (SAM Broadcaster)";
				if ($client_product["productID"] == 15)
					$client_product["version"] = "v3.x";
				else
					$client_product["version"] = "v4.x";

				$client_product["regkey"] = $regkey;
				$products[] = $client_product;

				//Output details to screen
				if ($trace)
					echo "client_productID: $clientproductID, RegKey: $regkey, Notes: $client_product[notes] <br>\n";
			}//foreach
			//Send email to client
			$this->client_sendemail($clientID, 'DJSeatExtend', $products);
			if ($trace)
				echo "Sent email to client for " . count($products) . " DJ Seats.<br>\n";
		}//if
	}

	private function sas_mail($to, $subject, $body, $from = "debug@spacialaudio.com", $type = "html", $cc = "") {
		//mail('emailcc@mail.spacialaudio.com',"debug","email being sent to: $to : $subject");

		require_once($this->paths['jaws'] . "/framework/class.email.php");
		$mail = new Temail();

		$bcc = 'isabel@spacialaudio.com'; //Force emails to be sent to kallie for a while
		$mail->email_smtp($to, $subject, $body, $from, $type, $cc, $bcc);
	}

	public function Merge($clientID1, $clientID2) {
		//We can not merge the same client with itself
		if ($clientID1 == $clientID2)
			return;

		$this->db->openEx("SELECT comment FROM client WHERE ID = :clientID", $clientID1);
		if ($this->db->num_rows() <= 0)
			return;
		$client1 = $this->db->row();

		$this->db->openEx("SELECT comment FROM client WHERE ID = :clientID", $clientID2);
		if ($this->db->num_rows() <= 0)
			return;
		$client2 = $this->db->row();
		$balance = $client2["balance"];

		//Merge two client accounts into one
		$this->db->openEx("UPDATE transaction SET clientID = :clientID1 WHERE clientID = :clientID2", $clientID1, $clientID2);
		$this->db->openEx("UPDATE invoice SET clientID = :clientID1 WHERE clientID = :clientID2", $clientID1, $clientID2);
		$this->db->openEx("UPDATE client_product SET clientID = :clientID1 WHERE clientID = :clientID2", $clientID1, $clientID2);

		$comment = $client1["comment"];
		$comment .= "\n==================================\n";
		$comment .= "Client merged with: clientID=$clientID2, Email:$client2[email]";
		$this->db->openEx("UPDATE client SET comment = :comment, balance=balance+$balance WHERE ID = :clientID", $comment, $clientID1);

		$comment = $client2["comment"];
		$comment .= "\n==================================\n";
		$comment .= "Client merged with: clientID=$clientID1,Email:$client1[email]";
		$this->db->openEx("UPDATE client SET comment = :comment, balance=0 WHERE ID = :clientID", $comment, $clientID2);

		//Update details of client2 for use in email
		$client2["comment"] = $comment;
		$client2["balance"] = 0.00;

		//Send email to both clients about the merge
		$this->client_sendemail($clientID1, 'merge', $client2);

		//Return the ID of the remaining client account
		return $clientID1;
	}

	public function Extend_DJSeatsEmail($clientID, $trace = false) {
		$this->client_sendemail($clientID, 'DJSeatExtendV4');
		if ($trace)
			echo "Sent DJ Seat regeneration email to client. <br>\n";
	}

	public function Extend_DJSeat($cpID, $trace = false) {
		//Each quarter, extend all DJ Seat licenses for another 3 months
		require_once($this->localpath . "/class.product.php");
		$product = new TProduct($this->db, $this->localpath);

		//Output details to screen
		if ($trace)
			echo "==================== ClientProductID: $cpID ===========================<br>\n";

		$this->db->openEx("SELECT * FROM client_product WHERE (ID = :cpID) ", $cpID);
		if ($this->db->num_rows() > 0) {
			$client_product = $this->db->row();
			//1. Generate ney key
			$keyinfo = $product->product_regkey($client_product["clientID"], $client_product["productID"], false);
			$regkey = $keyinfo["key"];
			$date_expire = $keyinfo["date_expire"];

			//2. Update registration key
			$this->db->openEx("UPDATE client_product SET regkey=:regKey, date_expire=:date_expire WHERE (ID = :cpID) ", $regkey, $date_expire, $cpID);

			//Save details for email
			$client_product["name"] = "DJ Seat license (SAM Broadcaster)";
			if ($client_product["productID"] == 15)
				$client_product["version"] = "v3.x";
			else
				$client_product["version"] = "v4.x";

			$client_product["regkey"] = $regkey;

			//Output details to screen
			if ($trace)
				echo "client_productID: $cpID, RegKey: $regkey, Notes: $client_product[notes] <br>\n";
			return $client_product;
		}//if
	}

}

?>