<?php
if(stripos($_SERVER['SCRIPT_NAME'],"/admin/")===false?false:true){
	include_once("../connect.php");
	include_once("functions.php");
	//include_once("../session.php");
}else{
	include_once("connect.php");
	include_once("functions.php");

	//include_once("session.php");
}

class Payment {
	public $PaymentID, $Customer, $PaymentDate, $CPD, $CPDDate, $Invoices, $Credits, $CashAmount, $CheckAmount, $Checks, $Salesman, $Subtotal, $TotalDiscount, $TotalTax, $InvoiceSubtotal, $InvoiceTax, $InvoiceDiscount, $TotalCredits, $CreditSubtotal, $CreditTax, $CreditDiscount, $TotalToApply, $TotalToPay, $ProcessDate, $Processed, $Loaded, $Notes, $Void, $VoidID ,$VoidReason, $VoidDate, $VoidUser, $Reminder;
	public function __construct($ID) {
		$query = "SELECT * FROM PAYMENT_HEAD WHERE ID = $ID";
		global $con;
		//error_log("Query class creation: " . $query);
		$result = mysqli_query($con, $query);
		$row = mysqli_fetch_array($result);
		$this->PaymentID = $row['ID'];
		$this->OfflineID = $row['OfflineID'];
		$this->Customer = new Customer($row['AccountNumber']);
		$this->PaymentDate = $row['PaymentDate'];
		$this->CPD = $row['CPD'];
        $this->CPDDate = $row['CPDDate'];
        $this->CashAmount = $row['CashAmount'];
        $this->CheckAmount = $row['CheckAmount'];
		$this->Salesman = new Salesman($row['SalesmanID']);
		$this->ProcessDate = $row['ProcessDate'];
		$this->Processed = $row['Processed'];
		$this->Loaded = $row['Loaded'];
		$this->Notes = $row['Notes'];
		$this->Void = $row['Void'];
		if($row['Void']){
			$query = "SELECT * FROM PAYMENT_VOID WHERE PaymentID = " . $row['ID'];
			$result = mysqli_query($con, $query);
			$row2 = mysqli_fetch_array($result);
			$this->VoidID = $row2['ID'];
			$this->VoidReason = $row2['Reason'];
			$this->VoidDate = $row2['VoidDate'];
			$this->VoidUser = $row2['User'];
		}
		$this->Invoices = array();
		$query = "SELECT * FROM PAYMENT_DETAIL WHERE PaymentID = $ID";
		$result = mysqli_query($con, $query);
		$this->Subtotal = 0;
		$this->TotalDiscount = 0;
		$this->TotalTax = 0;
		$this->TotalTax1 = 0;
		$this->TotalTax2 = 0;
		$this->TotalToApply = 0;
		$this->TotalToPay = 0;
		$this->TotalCredits = 0;
		while($row = mysqli_fetch_array($result)){
			$invoice = new Invoice($row['InvoiceID']);

			$invoice->PartialPayment = intval($row['PartialPayment']);
			if($row['PartialPayment'] && $row['PaymentAmount'] > 0){
				$invoice->Subtotal = $row['SubtotalAmount'];
				$invoice->Discount = 0;
				$this->InvoiceDiscount += $invoice->Discount;
				$invoice->Tax = 0;
				$this->InvoiceTax += $invoice->Tax;
				$this->InvoiceSubtotal += $row['PaymentAmount'];
			}else{
				$invoice->Subtotal = $row['SubtotalAmount'];
				$this->InvoiceSubtotal += $row['SubtotalAmount'];
				$invoice->Discount = $row['DiscountAmount'];
				$this->InvoiceDiscount += $invoice->Discount;
				$this->TotalTax1 += $invoice->Tax1Total;
				$this->TotalTax2 += $invoice->Tax2Total;
				$invoice->Tax = $row['TaxAmount'];
				$this->InvoiceTax += $invoice->Tax;
			}
			$invoice->Total = $row['SubtotalAmount'] - $row['DiscountAmount'] + $row['TaxAmount'];
			$invoice->PaymentAmount = $row['PaymentAmount'];
			$this->Subtotal += $invoice->Subtotal;
			if($invoice->PartialPayment){
				$this->TotalToApply += $row['PaymentAmount'];
			}else{
				$this->TotalDiscount += $invoice->Discount;
				$this->TotalTax += $invoice->Tax;
				$this->TotalToApply += $row['SubtotalAmount'] + $row['TaxAmount'];
			}
			$this->TotalToPay += $row['PaymentAmount'];

			array_push($this->Invoices, $invoice);
			unset($invoice);
		}

		$this->Credits = array();

		$this->Checks = array();
		$query = "SELECT * FROM PAYMENT_CHECK WHERE PaymentID = $ID";
		$result = mysqli_query($con, $query);
		while($row = mysqli_fetch_array($result)){
			$check = (object) array();
			$check->CheckNumber = $row['CheckNumber'];
			$check->Amount = $row['Amount'];
			array_push($this->Checks, $check);
			unset($check);
		}
	}
	public function getPaymentReconciliation(){
		global $con;
		$query = "SELECT * FROM PAYMENT_SALESMAN_RECONCILE_DETAIL WHERE PaymentID = " . $this->PaymentID;

		$result = mysqli_query($con, $query);
		$row = mysqli_fetch_array($result);
		return $row['ReconcileID'];

	}
	public function getTokenKey(){
		$realKey = md5($this->PaymentID . "PaymentWestingPR");
		$realKey = substr($realKey, -16);
		return $realKey;
	}
	public function ProcessPayment(){

		global $con;

		$query = "UPDATE PAYMENT_HEAD SET ProcessDate = DATE_ADD(NOW(), INTERVAL -4 HOUR), Processed = TRUE, ProcessUser = '" . $_SESSION['Username'] . "' WHERE id = " . $this->PaymentID;
		$result = mysqli_query($con,$query);
		$query = "SELECT ProcessDate FROM PAYMENT_HEAD WHERE id = " . $this->PaymentID;
		$result = mysqli_query($con,$query);
		$row = mysqli_fetch_array($result);
		return $row['ProcessDate'];

	}
	public function ReceiveCPD(){
		global $con;

		$query = "UPDATE PAYMENT_HEAD SET CPDReceiptDate = DATE_ADD(NOW(), INTERVAL -4 HOUR), CPDReceipt = TRUE WHERE id = " . $this->PaymentID;

		$result = mysqli_query($con,$query);
		//var_dump($result);
		$query = "SELECT CPDReceiptDate FROM PAYMENT_HEAD WHERE id = " . $this->PaymentID;
		$result = mysqli_query($con,$query);
		//var_dump($result);
		$row = mysqli_fetch_array($result);
		$this->ProcessPayment();
		return $row['CPDReceiptDate'];

	}
	public function FlagLoadedReceipt(){
		global $con;
		$query = "UPDATE PAYMENT_HEAD SET Loaded = TRUE WHERE id = " . $this->PaymentID;
		$result = mysqli_query($con,$query);
		echo "executed";
	}
	public function VoidPayment($reason){
		global $con;

		$reason = mysqli_real_escape_string($con,$reason);
		//var_dump($reason);
		if(trim($reason) == ""){
			die("Invalid Reason");
		}
		$query = "UPDATE PAYMENT_HEAD SET CashAmount = 0, CheckAmount = 0, ProcessDate = DATE_ADD(NOW(), INTERVAL -4 HOUR), Processed = 1, Void = TRUE WHERE id = " . $this->PaymentID . ";";
		$query .= "UPDATE PAYMENT_DETAIL SET InvoiceID = CONCAT(InvoiceID,'V'), PartialPayment = 0, SubtotalAmount = 0, DiscountAmount = 0, TaxAmount = 0, PaymentAmount = 0, Reference = '' WHERE PaymentID = " . $this->PaymentID . ";";
		$query .= "UPDATE PAYMENT_CREDIT SET CreditNumber = CONCAT(CreditNumber,'V'), Subtotal = 0, Discount = 0, Tax = 0, Total = 0, Reference = '' WHERE PaymentID = " . $this->PaymentID . ";";
		$query .= "INSERT PAYMENT_VOID (PaymentID, Reason, User, VoidDate) VALUES (" . $this->PaymentID . ", '$reason', '" . $_SESSION['Username'] . "', DATE_ADD(NOW(), INTERVAL -4 HOUR));";

		if(!mysqli_multi_query($con, $query)){
			$data['result'] = false;
			$data['error'] = mysqli_error($con);
			$data['sql'] = $query;

			echo json_encode($data);
		}else{
			$data['result'] = "true";
			echo json_encode($data);
		}
		//echo $query;
		//include_once("functions.php");
		event_log($_SESSION['Username'],"PAYMENT VOID", "Payment Void \n\nPayment ID: " . $this->PaymentID . " \nCustomer: " . $this->Customer->AccountNumber . " - " . $this->Customer->Name . "\nUser: " . $_SESSION['User'] . "\nReason: " . $reason);
	}
	public function GetVoidDetails(){
		global $con;
		$data['PaymentID'] = $this->PaymentID;
		$data['VoidDate'] = $this->VoidDate;
		$data['VoidReason'] = $this->VoidReason;
		$data['VoidUser'] = $this->VoidUser;
		//var_dump($this);
		echo json_encode($data);
	}
	public function GetReminderData(){
		global $con;
		$query = "SELECT * FROM PAYMENT_REMINDER WHERE PaymentID = " . $this->PaymentID;
		$result = mysqli_query($con, $query);
		if(mysqli_num_rows($result)){
			$this->isReminder = true;
			$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
			$this->Reminder = new stdClass();
			$this->Reminder->Reason = $row['Reason'];
			$this->Reminder->NextVisitDate = $row['NextVisitDate'];
			$this->Reminder->Notes = $row['Notes'];
		}else{
			$this->isReminder = false;
			$this->Reminder = new stdClass();
			$this->Reminder->Notes = NULL;
		}


	}
	public function SendPaymentEmail() {
		$config = include("./config.php");
		global $root;


		$to = $config['PaymentEmail'];
		$subject = "Payment Receipt #" . $this->PaymentID . " from {$this->Customer->Name}";
		//$key = md5($orderID . "EJAS");
		//$key = substr($key, -16);

		require_once './assets/PHPMailerAutoload.php';

		$results_messages = array();

		$mail = new PHPMailer(true);
		$mail->CharSet = 'utf-8';

		$mail->isMail();
		$mail->addReplyTo($config['PaymentFromEmail']);
		$mail->From       = $config['PaymentFromEmail'];
		$mail->FromName   = $config['FromEmailName'];
		//para enviar email a info.
		$mail->addAddress($to);

		//para enviar email al vendedor
		if ($this->Customer->Salesman->Email != "" || $this->Customer->Salesman->Email != null) {
			$mail->addCC($this->Customer->Salesman->Email);
		}

		//Enviar Email del cliente
		$customerEmail = $this->Customer->Email;
		if ($customerEmail != "" || $customerEmail != null) {
			$mail->addCC($customerEmail);
		}

		$mail->Subject  = $subject;
		$title = $config["FromEmailName"];
		$body =
		'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
		<html>
		<head>
		  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		  <title>' . $title . '</title>
		</head>
		<body>
		  <div style="width: 640px; font-family: Arial, Helvetica, sans-serif; font-size: 16px;">
			<img src="'.$root.'/img/'. $config['SmallLogo'] .'" style="width: 150px;" />
			<p>' . $this->Customer->Name . ' <br />
			Account Number: ' . $this->Customer->AccountNumber . '<br />
			Total: ' . moneyFormat($this->CashAmount + $this->CheckAmount) . ' <br />
			Notes: ' . $this->Notes . '<br />
			<a href="' . $root . '/mod.php?p=payment&a=view&id=' . $this->PaymentID . '&key=' .  $this->getTokenKey(). '">View Payment #' . $this->PaymentID . '</a>
			</p>
			<div align="center">

			</div>

		  </div>
		</body>
		</html>';
		$mail->WordWrap = 78;
		$mail->msgHTML($body, dirname(__FILE__), true); //Create message bodies and embed images
		//$mail->addAttachment('images/phpmailer_mini.png','phpmailer_mini.png');  // optional name
		//$mail->addAttachment('images/phpmailer.png', 'phpmailer.png');  // optional name

		$privatekeyfile = 'dkim_private.key';
		//Make a new key pair
		//(2048 bits is the recommended minimum key length -
		//gmail won't accept less than 1024 bits)
		$pk = openssl_pkey_new(
			array(
				'private_key_bits' => 2048,
				'private_key_type' => OPENSSL_KEYTYPE_RSA
			)
		);
		openssl_pkey_export_to_file($pk, $privatekeyfile);

		$mail->DKIM_domain = 'westingpr.com';
		$mail->DKIM_private = $privatekeyfile;
		$mail->DKIM_selector = 'phpmailer';
		$mail->DKIM_passphrase = ''; //key is not encrypted
		$mail->send();
		unlink($privatekeyfile);
	}

	public function SendPaymentReminderEmail() {
		$config = include("./config.php");
		global $root;


		$to = $config['PaymentEmail'];
		$subject = "Payment Reminder #" . $this->PaymentID . " for {$this->Customer->Name}";
		//$key = md5($orderID . "EJAS");
		//$key = substr($key, -16);

		require_once './assets/PHPMailerAutoload.php';

		$results_messages = array();

		$mail = new PHPMailer(true);
		$mail->CharSet = 'utf-8';

		$mail->isMail();
		$mail->addReplyTo($config['PaymentFromEmail']);
		$mail->From       = $config['PaymentFromEmail'];
		$mail->FromName   = $config['FromEmailName'];
		$mail->addAddress($to);

		if ($this->Customer->Salesman->Email != "" || $this->Customer->Salesman->Email != null) {
			$mail->addCC($this->Customer->Salesman->Email);
		}

		//$customerEmail = $this->Customer->Email;
		if ($this->Customer->Email != "" || $this->Customer->Email != null) {
			$mail->addCC($this->Customer->Email);
		}
		$this->getReminderData();
		$mail->Subject  = $subject;
		$title = $config["FromEmailName"];
		$body =
		'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
		<html>
		<head>
		  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		  <title>' . $title . '</title>
		</head>
		<body>
		  <div style="width: 640px; font-family: Arial, Helvetica, sans-serif; font-size: 16px;">
			<img src="'.$root.'/img/'. $config['SmallLogo'] .'" style="width: 150px;" />
			<p>' . $this->Customer->Name . ' <br />
			Account Number: ' . $this->Customer->AccountNumber . '<br />
			Notes: ' . $this->Reminder->Notes . '<br />
			<a href="' . $root . '/mod.php?p=payment&a=viewReminder&id=' . $this->PaymentID . '&key=' .  $this->getTokenKey(). '">View Payment Reminder #' . $this->PaymentID . '</a>
			</p>
			<div align="center">

			</div>

		  </div>
		</body>
		</html>';
		$mail->WordWrap = 78;
		$mail->msgHTML($body, dirname(__FILE__), true); //Create message bodies and embed images
		//$mail->addAttachment('images/phpmailer_mini.png','phpmailer_mini.png');  // optional name
		//$mail->addAttachment('images/phpmailer.png', 'phpmailer.png');  // optional name

		$privatekeyfile = 'dkim_private.key';
		//Make a new key pair
		//(2048 bits is the recommended minimum key length -
		//gmail won't accept less than 1024 bits)
		$pk = openssl_pkey_new(
			array(
				'private_key_bits' => 2048,
				'private_key_type' => OPENSSL_KEYTYPE_RSA
			)
		);
		openssl_pkey_export_to_file($pk, $privatekeyfile);

		$mail->DKIM_domain = 'westingpr.com';
		$mail->DKIM_private = $privatekeyfile;
		$mail->DKIM_selector = 'phpmailer';
		$mail->DKIM_passphrase = ''; //key is not encrypted
		$resultReturn = $mail->send();
		unlink($privatekeyfile);
		return $resultReturn;
	}



}



class SalesmanReconciliation{

	public function __construct($ID) {
		global $con;
		$query = "SELECT * FROM PAYMENT_SALESMAN_RECONCILE_HEAD WHERE ReconcileID = " . mysqli_real_escape_string($con,$ID) . ";";
		$result = mysqli_query($con, $query);
		$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
		foreach($row as $key => $value){
			$this->$key = $value;
		}
		//var_dump($row);
		$this->Payments = [];
		$query = "SELECT * FROM PAYMENT_SALESMAN_RECONCILE_DETAIL WHERE ReconcileID = " . mysqli_real_escape_string($con,$ID) . ";";
		$result = mysqli_query($con, $query);
		while($row = mysqli_fetch_array($result)){
			array_push($this->Payments,$row['PaymentID']);
		}
	}
}

class PaymentDeposit{
	public $DepositID;
	public function __construct($ID) {
		global $con;
		$query = "SELECT * FROM PAYMENT_DEPOSIT_HEAD WHERE DepositID = $ID";
		$result = mysqli_query($con, $query);
		$row = mysqli_fetch_array($result);
		foreach($row as $key => $value){
			$this->$key = $value;
		}
		switch($this->Depositor){
			case "athmovil":
				$this->DepositorName = "ATH Movil";
				break;
			case "transfer":
				$this->DepositorName = "Wire Transfer";
				break;
			case "other":
				$this->DepositorName = "Other (see Notes)";
				break;
			default:
				$query = "SELECT * FROM ((SELECT Username, FullName FROM SALESMAN) UNION (SELECT Username, FullName FROM ADMINISTRATOR)) T WHERE Username LIKE '" . $this->Depositor . "';";
				$result = mysqli_query($con, $query);
				if(mysqli_num_rows($result)){
					$row = mysqli_fetch_array($result);
					$this->DepositorName = $row['FullName'];
				}
				$this->DepositorName = $this->Depositor;
				break;
		}
		$this->CashPayments = array();
		$query = "SELECT * FROM PAYMENT_DEPOSIT_DETAIL WHERE DepositID = " . $ID;
		$result = mysqli_query($con, $query);
		while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
			$pmt = new Payment($row['PaymentID']);
			$obj = new stdClass();
			$obj->Payment = $pmt;
			$obj->Customer = $pmt->Customer->Name;
			$obj->CashAmount = $pmt->CashAmount;
			if($obj->CashAmount != 0)
			array_push($this->CashPayments,$obj);
		}
		$this->Checks = array();
		$query = "SELECT PAYMENT_CHECK.*, AccountNumber, `Name` FROM PAYMENT_DEPOSIT_DETAIL JOIN PAYMENT_CHECK USING (PaymentID) JOIN PAYMENT_HEAD ON(PAYMENT_HEAD.`ID` = PAYMENT_CHECK.PaymentID) LEFT JOIN CUSTOMER USING(AccountNumber)  WHERE DepositID = $ID";
		$result = mysqli_query($con, $query);
		while($row = mysqli_fetch_array($result)){
			$pmt = new Payment($row['PaymentID']);
			$check = new stdClass();
			$check->Payment = $pmt;
			$check->CustomerName = $row['Name'];
			$check->Number = $row['CheckNumber'];
			$check->Amount = $row['Amount'];
			array_push($this->Checks, $check);
		}
	}

}

?>
