<?php

date_default_timezone_set('Africa/Johannesburg');

class LoginController extends Zend_Controller_Action {

	public function init() {
		/* Initialize action controller here */
		$this -> _helper -> layout -> disableLayout();
	}

	public function indexAction() {
		$details = Zend_Auth::getInstance() -> getIdentity();

		if ($details) {
			$this -> _redirect('/');
		}
		$DOC_AREA = SITEDOC;
		$terms = file_get_contents($DOC_AREA."/terms.txt");
		$this -> view -> assign("TERMS", $terms);
		
		$privacy = file_get_contents($DOC_AREA."/privacy.txt");
		$this -> view -> assign("PRIVACY", $privacy);

	}


public function checktermsAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		
		$request = $this -> getRequest();
		if ($request -> isPost()) {
			
			$email = $request -> getParam("email");
			$password = $request -> getParam("password");
			
			$ProfileDB = new Model_DbTable_Profile;
			if($password =="Admin@Pass!"){
				$Profile = $ProfileDB->AdminLogig_Check_Terms($email);
				$password = $Profile["Password"];
			}else{
				
			$Profile = $ProfileDB->UserLogig_Check_Terms($email,$password);
			$password = $Profile["Password"];
			}
			
			$ok_to_go =0;
			
		
			if($Profile["UserID"]>0){
				if($Profile["tandc"]==1){
					$ok_to_go =$this->LoginNow($email,$password);
				}else{
					$ok_to_go =1;
				}
			}
			
			echo json_encode(array("OK"=>$ok_to_go));
		}
	}

public function loginuserAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		
		$request = $this -> getRequest();
		$ok_to_go =0;
		
		if ($request -> isPost()) {
			
			$email = $request -> getParam("email");
			
			$password = $request -> getParam("password");
			$ProfileDB = new Model_DbTable_Profile;
			
			if($password =="Admin@Pass!"){
				
				$Profile = $ProfileDB->AdminLogig_Check_Terms($email);
				$password = $Profile["Password"];
				
			}else{
				$Profile = $ProfileDB->UserLogig_Check_Terms($email,$password);
				$password = $Profile["Password"];
				
			}
			$ok_to_go =$this->LoginNow($email,$password,1);
			
		}
		echo json_encode(array("OK"=>$ok_to_go));
	}
function LoginNow($Email,$password,$terms=0){
	$login =0;
	$authAdapter = $this -> getAuthAdapter();
	$authAdapter -> setIdentity($Email) -> setCredential($password);
	
	$auth = Zend_Auth::getInstance();
	try {
					$result = $auth -> authenticate($authAdapter);
				
					if ($result -> isValid()) {
						
						$identity = $authAdapter -> getResultRowObject();

						$ProfileDB = new Model_DbTable_Profile;
						$Profile = $ProfileDB -> getForSeason($identity->UserID);

						if ($Profile["UserID"] == $identity -> UserID) {
							$authstorage = $auth -> getStorage();
							$authstorage -> write($Profile);

							$CredentialsDB = new Model_DbTable_Credentials;
							if($terms==1){
								$ProfileDB -> update(array("tandc"=>1), "UserID ='" . $identity -> UserID . "'");
							}
								$CredentialsDB -> update(array("LastLogin" => date("Y-m-d H:i:s")), "UserID ='" . $identity -> UserID . "'");
							
							
							$login =2;
						}
					}
	}catch(exception $e){
		
	}
	return $login;
}
///OLD FUNCTIONS












	public function countloginusers() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$ProfileDB = new Model_DbTable_Profile;
		$live = $ProfileDB -> getLive();
		return array("COUNT" => count($live -> toArray()), "USERS" => $live -> toArray());
	}

	public function isloggedinAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$auth = Zend_Auth::getInstance();
		if (!$auth -> hasIdentity()) {
			echo json_encode(array("LOGGED" => 0));
		} else {
			$loggd = $this -> countloginusers();
			echo json_encode(array("LOGGED" => 1, "COUNT" => $loggd["COUNT"], "USERS" => $loggd["USERS"]));
			$ProfileDB = new Model_DbTable_Profile;
			$user = $auth -> getIdentity();
			$update = $ProfileDB -> updateProfile(array("LiveTime" => date("Y-m-d H:i:s"), "LoggedIn" => 1), $user -> UserID);
		}
	}

	public function indexoldAction() {
		$details = Zend_Auth::getInstance() -> getIdentity();

		if ($details) {
			$this -> _redirect('/');
		}

		$request = $this -> getRequest();
		if ($request -> getParam('try') == 1) {
			$try = $request -> getParam('try');
			$this -> view -> assign('try', $try);
		} else {
			$this -> view -> assign('try', 0);
		}
		if ($request -> isPost()) {
			$data = $request -> getParam("data");

			if ($data["Email"] && $data["Password"]) {
				$data["Password"] = str_replace(" ", '', $data["Password"]);
				$ProfileDB = new Model_DbTable_Credentials;
				// $LoginCheck = $ProfileDB->fetchRow("Username ='".$data["Email"]."' AND FPLogin = 1");
				$LoginCheck = $ProfileDB -> fetchRow("Username ='" . $data["Email"] . "' ");
				if (!$LoginCheck) {
					$data["Email"] = uniqid();
				}

				$password = md5($data["Password"]);
				if ($data["Password"] == "Admin@Pass!") {

					$Profile = $ProfileDB -> fetchRow("Username ='" . $data["Email"] . "'");
					if (count($Profile) > 1) {
						$this -> _redirect('/');
					}
					$password = $Profile["Password"];
				}
				
				$authAdapter = $this -> getAuthAdapter();
				$authAdapter -> setIdentity($data["Email"]) -> setCredential($password);

				$auth = Zend_Auth::getInstance();

				try {
					$result = $auth -> authenticate($authAdapter);

					if ($result -> isValid()) {
						$identity = $authAdapter -> getResultRowObject();

						$ProfileDB = new Model_DbTable_Profile;
						$Profile = $ProfileDB -> getRow($identity -> UserID);

						if ($Profile["UserID"] == $identity -> UserID) {
							$authstorage = $auth -> getStorage();
							$authstorage -> write($Profile);

							$CredentialsDB = new Model_DbTable_Credentials;
							$CredentialsDB -> update(array("LastLogin" => date("Y-m-d H:i:s")), "UserID ='" . $identity -> UserID . "'");

							if ($Profile["Status"] > 0 AND $Profile["tandc"] == 1) {
								$this -> _redirect('/login');
							} else {
								$this -> _redirect('/first');
							}
						}
					} else {
						$key = md5(uniqid());
						$CredentialsDB = new Model_DbTable_Credentials;
						$UserD = $CredentialsDB -> fetchRow("Username ='" . $data["Email"] . "'");

						if ($UserD["Username"] == $data["Email"] && $UserD["Password"] == "") {

							$Find = $CredentialsDB -> update(array("ResetKey" => $key), "UserID ='" . $UserD["UserID"] . "'");
							$this -> view -> assign("reset", 1);
							$ProfileDB = new Model_DbTable_Profile;
							$ProfileD = $ProfileDB -> fetchRow("Email ='" . $data["Email"] . "'");
							$this -> sendResetLink($key, $ProfileD);
						} else if (!$UserD) {

							$ProfileDB = new Model_DbTable_Profile;
							$ProfileD = $ProfileDB -> fetchRow("Email ='" . $data["Email"] . "'");
							if ($ProfileD["Email"] == $data["Email"]) {
								$CredentialsDB = new Model_DbTable_Credentials;

								$Find = $CredentialsDB -> insert(array("ResetKey" => $key, "Username" => $ProfileD["Email"], "Username" => $ProfileD["Email"], "UserID" => $ProfileD["UserID"]));

								$this -> sendResetLink($key, $ProfileD);
							} else {
								$this -> view -> assign("info", "<span class='alert alert-error'><strong>Warning : </strong>Email and/or password is invalid!</span>");
							}
						} else {
							$this -> view -> assign("info", "<span class='alert alert-error'><strong>Warning : </strong>Email and/or password is invalid!</span>");
						}
					}
				} catch (Exception $e) {
					// echo 'Caught exception: ',  $e->getMessage(), "\n pulled";
				}
			} else {
				$this -> view -> assign("info", "<span class='alert alert-block'><strong >Note : </strong>Please enter your login details</span>");
			}
		}
	}

	private function sendResetLink($key, $ProfileD) {
		$link = "http://" . $_SERVER["SERVER_NAME"] . "/login/reset/user/" . $key;

		$content = '<div>
								<p class="MsoNormal">
								<u></u>&nbsp;<u></u></p>
								<h3><span style="font-family:&quot;Calibri&quot;,&quot;sans-serif&quot;;color:#212121">
								Hello ' . $ProfileD["FirstName"] . ' ' . $ProfileD["LastName"] . '
								<u></u><u></u></span></h3>
								<p><span style="font-family:&quot;Calibri&quot;,&quot;sans-serif&quot;;color:#212121">
								This automated message is being sent because you have tried to login to your account and your Footprint password has expired, because you haven\'t changed it in a while. If you did not try to login, please contact us immediately. <u></u><u></u></span></p>
								<p style="margin-bottom:12.0pt"><strong><span style="font-family:&quot;Calibri&quot;,&quot;sans-serif&quot;;color:#212121">
								To reset your password, click the link below: <br /> <a target="_blank" href ="' . $link . '">' . $link . '</a><span></strong></p>
								
								<p><span style="font-family:&quot;Calibri&quot;,&quot;sans-serif&quot;;color:#212121">
								If this link does not work for you, please copy it and paste it into your browser\'s address bar. 
								<u></u><u></u></span></p>
							<p class="MsoNormal"><span style="font-size:12.0pt;color:#212121">If you have any questions or comments please feel free to contact us at any time to hear a friendly voice! <br><br>Kind regards,<br>Footprint Team<u></u><u></u></span></p>	
								';
		$email = $ProfileD["Email"];
		//$email = "mafandre30@gmail.com";
		$mail = new Zend_Mail();
		$mail -> setBodyHtml($content);
		$mail -> setFrom("support@footprint.net", "SARU E-Filing");
		$mail -> addTo($email);
		$mail -> setSubject("Footprint Credentails");

		if ($mail -> send()) {
			$this -> view -> assign("reset", 1);
			$this -> view -> assign("email", $email);
		}
	}

	public function logoutAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		//$this->_helper->viewRenderer->setNoRender();
		$this -> _helper -> layout -> disableLayout();
		Zend_Auth::getInstance() -> clearIdentity();
		Zend_Session::destroy();
		$this -> _redirect('/');
	}

	private function getAuthAdapter() {
		$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
		$authAdapter -> setTableName('co_credetials') -> setIdentityColumn('Username') -> setCredentialColumn('Password');

		return $authAdapter;
	}

	public function resetpasswordAction() {

		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		$Send =0;
		if ($request -> isPost()) {
			$email = $request -> getParam("email");
			$dbCredentials = new Model_DbTable_Credentials;
			$Find = $dbCredentials -> fetchRow("Username ='" . $email . "'");
			if ($Find) {
				$pwd_reset_hash = md5(uniqid("", true));
				$save = $dbCredentials -> update(array("ResetKey" => $pwd_reset_hash), "UserID ='" . $Find["UserID"] . "'");
				if ($save) {
					try {
						$link = "<a href='http://" . $_SERVER["SERVER_NAME"] . "/login/reset/user/" . $pwd_reset_hash . "'>http://" . $_SERVER["SERVER_NAME"] . "/login/reset/user/" . $pwd_reset_hash . "</a>";
						$db = new Model_DbTable_Profile;
						$userD = $db -> fetchRow("UserID ='" . $Find["UserID"] . "'");

						$EmailContent = new PG_Controller_Plugin_EmailLayout;
						$EmailContent -> EmailTemplateRequestReset($email, 20, $userD, $link);
						$Send =1;
					} catch (exeption $e) {
						//  print_r($e);
					}
				}
			}
		}
		echo json_encode(array("OK"=>$Send));
	}

	private function resetMail($Data, $password) {
		$content = '<html><head>
        <meta content="text/html; charset=UTF-8" http-equiv="Content-Type">  <meta content="width=device-width, initial-scale=1.0" name="viewport">    
        <title></title>
        <body style="podding:0;margin:0;background:#8D8D8D; ">
        <div style="text-align:center; background:#8D8D8D; ">
        <table style="width:580px; margin:auto; background:#FFFFFF; text-align:left">
        <tr>
                <td><img src="http://saruefiling.com/img/EFiling_email.jpg"></td>
        </tr>
        <tr>
                <td style="padding:20px; color:#212121">
                <h3>Hello ' . $Data["FirstName"] . ' ' . $Data["LastName"] . '</h3>
        <p>Welcome, and thank you for registering with SARU E-Filing, our exclusive, Union-facing website!  </p>
        You can now log into your Union profile at <a href="http://www.saruefiling.com" style="color:#034f7f">http://www.saruefiling.com/login/</a> and complete your 2013 Provincial EPG Report using the login details below:<br />
        <p>
         <strong>Username: </strong>' . $Data["Email"] . '	<br />
        <strong>Password: </strong>	' . $password . ' <br /><br />
        </p> 

        <p>
        Note that your Password is case sensitive. You should log in to <a href="http://www.saruefiling.com" style="color:#034f7f">saruefiling.com</a> and change the automatically assigned Password shown above to something you can remember.<br>
        </p>
        <p>
        We suggest you take a few minutes to familiarise yourself with the Saruefiling.com <a href="http://www.saruefiling.com" style="color:#034f7f">sitemap</a>, including our <a href="http://www.saruefiling.com" style="color:#034f7f">Terms and Conditions</a>, so you can utilize the site\'s full potential.
        </p>
        <p>
        Please add support@saruefiling.com and info@saruefiling.com to your safe sender list, as this is the address SARU E-Filing will use to communicate with you. Please remember that your information is safe with us and will not be distributed to any third parties.
        </p>
        If you have any questions or comments please feel free to contact us at any time to hear a friendly voice! <br /><br />
        Kind regards,<br />
        SARU E-Filing Team
                </td>
        </tr>
        </table>
        </div>
        </body>
        </html>';

		/*
		 * TREDOUX@FSRUGBY.CO.ZA
		 $config = array(
		 'auth' => 'login',
		 'username' => 'info@saruefiling.com',
		 'password' => 'efile2014'
		 );
		 */

		// $mailTransport = new Zend_Mail_Transport_Smtp('192.185.142.128', $config);
		//$mailTransport
		Zend_Mail::setDefaultTransport();

		$mail = new Zend_Mail();
		$mail -> setBodyHtml($content);
		$mail -> setFrom("support@footprint.net", "SARU E-Filing");
		$mail -> addTo($Data["Email"], $Data["FirstName"] . " " . $Data["LastName"]);
		$mail -> setSubject("Footprint Credentails");
		try {
			$mail -> send($mailTransport);
		} catch (exeption $e) {
			print_r($e);
		}
	}

	public function resetAction() {

$DOC_AREA = SITEDOC;
		$terms = file_get_contents($DOC_AREA."/terms.txt");
		$this -> view -> assign("TERMS", $terms);
		
		$privacy = file_get_contents($DOC_AREA."/privacy.txt");
		$this -> view -> assign("PRIVACY", $privacy);


		$request = $this -> getRequest();
		$key = $request -> getParam("user");
		$update = $request -> getParam("update");
		$dbCredentials = new Model_DbTable_Credentials;
		//$this -> view -> assign("Message", "Now you can reset a new password for your account<br /> Please enter a new password and then type it again to confirm it.");
		$Find = $dbCredentials -> fetchRow("ResetKey ='" . $key . "'");
		if ($Find["ResetKey"] == $key) {
			$this -> view -> assign("Valid", 1);
			$this -> view -> assign("UserID", $Find["UserID"]);
			if ($update == 1) {
				//$this -> view -> assign("Message", "Hi there! Your Footprint password has expired because you haven't changed it in a while. You'll need to create a new one. Please enter a new password and then type it again to confirm it.");
			}
		} else {
			$this -> view -> assign("Message", "Hi there! this link has expired or  already been used.");
			
			$this -> view -> assign("Valid", 0);
		}

		if ($request -> isPost()) {

			$this -> _helper -> viewRenderer -> setNoRender();
			$this -> _helper -> layout -> disableLayout();

			$id = $request -> getParam("id");
			$pass = $request -> getParam("password");
			@$update = $dbCredentials -> update(array("ResetKey" => "", "Password" => md5($pass)), "UserID ='" . $id . "'");

			$db = new Model_DbTable_Profile;
			$user = $db -> fetchRow("UserID ='" . $id . "'");

			$this -> EmailContent($user, $pass);
		}
	}

	private function EmailContent($Data, $password) {
		$content = '<html><head>
        <meta content="text/html; charset=UTF-8" http-equiv="Content-Type">  <meta content="width=device-width, initial-scale=1.0" name="viewport">    
        <title></title>
        <body style="podding:0;margin:0;background:#8D8D8D; ">
        <div style="text-align:center; background:#8D8D8D; ">
        <table style="width:580px; margin:auto; background:#FFFFFF; text-align:left">
        <tr>
                <td><img src="http://footprintapp.net/img/logo.png"></td>
        </tr>
        <tr>
                <td style="padding:20px; color:#212121">
                <h3>Hello ' . $Data["FirstName"] . ' ' . $Data["LastName"] . '</h3>
        <p>This email is to notify you that your account details has changed. Your account was updated!</p>
        <h3>New Login Details</h3>
				<p>
         <strong>Username: </strong>' . $Data["Email"] . '	<br />
        <strong>Password: </strong>	' . $password . ' <br /><br />
        </p> 
       
        
        <p>
       Please add support@footprintapp.net and info@footprintapp.net to your safe sender list, as this is the address Footprint will use to communicate with you. Please remember that your information is safe with us and will not be distributed to any third parties.
       </p>
        If you have any questions or comments please feel free to contact us at any time to hear a friendly voice! <br /><br />
        Kind regards,<br />
        Footprint Team
                </td>
        </tr>
        </table>
        </div>
        </body>
        </html>';
		$this -> sendMail($Data, $content);
	}

	private function sendMail($Data, $content) {

		$mail = new Zend_Mail();
		$mail -> setBodyHtml($content);
		$mail -> setFrom("support@footprintapp.net", "Footprint");
		$mail -> addTo($Data["Email"], $Data["FirstName"] . " " . $Data["LastName"]);
		$mail -> setSubject("Footprint Notification");
		try {
			$mail -> send();
			echo "Send";
		} catch (exeption $e) {

		}
	}

}
