<?php

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRequest;

class authModel extends baseModel {
	var $salt = 'supersalt';

	public static $fields = [
		'name', 'email', 'location', 'location_lat','location_lng','location_last_lat', 'location_last_lng',
		'biography', 'website', 'phone','paypal_email','instagram_username', 'linkedin_account',
		'height', 'weight', 'eye_color', 'willing_to_do', 'is_activated', 'specific_fee', 'account_type',
		'category_id', 'contact_name', 'contact_email', 'contact_phone', 'contact_best_time', 'mailing_address',
		'password','virtual_balance','credits'
	];

    // blowfish
    private static $algo = '$2a';
    // cost parameter
    private static $cost = '$10';

    // mainly for internal use
    public static function unique_salt() {
        return substr(sha1(mt_rand()), 0, 22);
    }

    // this will be used to generate a hash
    public static function hash($password) {

        return crypt($password, self::$algo .
            self::$cost .
            '$' . self::unique_salt());
    }
    
    // Generating random Unique MD5 String for user Api key
    private function generateApiKey() {
        return md5(uniqid(rand(), true));
    }

    // this will be used to compare a password against a hash
    public static function check_password($hash, $password) {
        $full_salt = substr($hash, 0, 29);
        $new_hash = crypt($password, $full_salt);
        return ($hash == $new_hash);
    }

	function encodePwd($pwd) {
		$pwd = sha1($pwd . $this->salt);
		
		return $pwd;
	}

	function login($username, $password, $remember = 0) {
		if (!$username || !$password) {
			return 0;
		}

		$this->db->where('email=?', $username);
		//$this->db->where('password=?', $this->encodePwd($password));
		$this->db->where('type=?', 'native');
		$accounts_matched = $this->db->select('users');


		if (count($accounts_matched) >= 1) {
			$account = $accounts_matched[0];
			$password_hash = $account['password'];
			if ($this->check_password($password_hash, $password)) {
				$this->_saveCookie($account, $remember);
				return 1;
			}
		} else {
			return 0;
		}
	}
	
	function loginOLD($username, $password, $remember = 0) {
		if (!$username || !$password) {
			return 0;
		}

		$this->db->where('email=?', $username);
		$this->db->where('password=?', $this->encodePwd($password));
		$this->db->where('type=?', 'native');
		$accounts_matched = $this->db->select('users');


		if (count($accounts_matched) >= 1) {
			$account = $accounts_matched[0];
			$this->_saveCookie($account, $remember);

			return 1;
		} else {
			return 0;
		}
	}	
    
    function square_login($email, $password, $remember = 1) {
        if (!$email || !$password) {
            return 0;
        }

        $this->db->where('email=?', $email);
        $this->db->where('password=?', $this->getEncryptedPassword($password));
        
        $accounts_matched = $this->db->select('square_users');

        if (count($accounts_matched) >= 1) {
            $account = $accounts_matched[0];
            $this->_saveCookie($account, $remember);

            return 1;
        } else {
            return 0;
        }
    }    
    
    function getEncryptedPassword($password) {
        $salt = 'square_salt_users15$';
        $pwd = sha1($password . $salt);
        return $pwd;
    }    
	
	function loginAs($id) 
	{
		$this->db->where('id=?', (int)$id);
		$accounts_matched = $this->db->select('users');	
		
		if (count($accounts_matched) >= 1) {
			$account = $accounts_matched[0];
			$this->_saveCookie($account, false);

			return 1;
		} else {
			return 0;
		}
	}
	
	private function _saveCookie($account, $remember = false)
	{
		if	(empty($account)) {
			return false;
		}
		
		$_SESSION['loggedin'] = 1;
		$_SESSION['user_id']  = $account['id'];
		$_SESSION['user']     = $account;

		if ($remember) {
			$params = session_get_cookie_params();
			setcookie(session_name(), $_COOKIE[session_name()], time() + 60*60*24*30, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
		} else {
			$params = session_get_cookie_params();
			setcookie(session_name(), $_COOKIE[session_name()], 0, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
		}
		
		return true;
	}

	function checkCode($code) {
		if ($code == '') {
			return 0;
		}
		$this->db->where('reset_code=?', $code);
		$u = $this->db->select('users');
		if (!empty($u)) {
			return 1;
		}
	}

	function resetPassword($pwd, $code) {
		if (trim($code) == '') {
			return 0;
		}

		$this->db->where('reset_code=?', $code);
		$this->db->update('users', ['password' => $this->encodePwd($pwd), 'reset_code' => '']);

		if ($this->db->affected_rows()) {
			return 1;
		}
	}

	function preparePasswordReset($email) {
		$this->db->where('email=?', $email);
		$u = $this->db->select_one('users');

		if (empty($u))
			return false;

		$code = md5(time() . $u['id'] . rand(0, 100));

		$this->db->where('id=?', $u['id']);
		$this->db->update('users', ['reset_code' => $code]);

		$u['reset_code'] = $code;

		return $u;
	}

	function availableSlug($slug) {
		$slug = slug($slug);

		$this->db->where('user_slug=?', $slug);
		$this->db->select('users');

		$c = 1;
		while ($this->db->affected_rows() || $slug == 'edit') {
			$c++;
			$slug = slug($slug) . $c;
			$this->db->where('user_slug=?', $slug);
			$this->db->select('users');
		}

		return $slug;
	}

	function register($userdata) {
    	if (!$userdata['email'] || !$userdata['password']) {
			header("Location: /");
			exit;
		}

		$lowercase_email = strtolower($userdata['email']);
		$this->db->where("email=?", $lowercase_email);
		$u = $this->db->select("users");
		if (count($u) > 0) {
			header("Location: /?msg=User+already+exists");
			exit;
		}

		foreach ($userdata as $index => $value) {
			if (!in_array($index, self::$fields)) {
				unset($userdata[$index]);
			}
		}

		$userdata['api_key']  = $this->generateApiKey();
		$userdata['password'] = $this->hash($userdata['password']);
		$userdata['email'] = $lowercase_email;
		$username = substr($lowercase_email, 0, strpos($lowercase_email, '@'));
		$userdata['user_slug'] = $this->availableSlug($username);
		
		// LET'S SPLIT THE NAME INTO THE 2 NAME FIELDS
		$name_string = $userdata['name'];
		$name = explode(" ", $name_string);
		//echo $name_string . "\n";
		//echo $name[0]  . "\n"; // George
		//echo $name[1]  . "\n"; // Washington

		$userdata['first_name']  = $name[0];
		$userdata['last_name'] = $name[1];		
        
		$this->db->insert('users', $userdata);
    		return $this->db->insert_id();
	}

	function registerOLD($userdata) {
    	if (!$userdata['email'] || !$userdata['password']) {
			header("Location: /");
			exit;
		}

		$this->db->where("email=?", $userdata['email']);
		$u = $this->db->select("users");
		if (count($u) > 0) {
			header("Location: /?msg=User+already+exists");
			exit;
		}

		foreach ($userdata as $index => $value) {
			if (!in_array($index, self::$fields)) {
				unset($userdata[$index]);
			}
		}

		$userdata['password'] = $this->encodePwd($userdata['password']);
		$username = substr($userdata['email'], 0, strpos($userdata['email'], '@'));
		$userdata['user_slug'] = $this->availableSlug($username);
        
		$this->db->insert('users', $userdata);
    		return $this->db->insert_id();
	}
    
    // GET USER
    function getUser($uid) {
        $this->db->where("id=?", $uid);
        $user = $this->db->select_one('square_users');

        return $user;
    }    
    
	function getUserInfo($uid){
		$this->db->where("id=?", $uid);
		$user = $this->db->select_one('users');

		return $user;
	}  
 
     // GET CUSTOMER
    function getCustomer($uid) {
        $this->db->where("id=?", $uid);
        $user = $this->db->select_one('square_users');

        return $user;
    }       
    
      // TENDER CUSTOMER PMT
    function tenderPayment($uid,$amt) {
        $this->db->where("id=?", $uid);
        $customer = $this->db->select_one('square_users');
        
        if($customer){
        	$balance = $customer['virtual_balance'];
        	$new_balance = $balance - $amt;
		}
        $this->db->where("id=?", $uid);
		$this->db->update('square_users', ['virtual_balance' => $new_balance]);
        return $new_balance;
    }         
    
	function facebookGetLoginUrl() {
		global $website_options;

		$app_id    = $website_options['facebook_app_id'];
		$app_token = $website_options['facebook_app_token'];

		require_once('3rdparty/facebook/autoload.php');
        FacebookSession::setDefaultApplication($app_id, $app_token);
        $helper = new FacebookRedirectLoginHelper('http://' . $_SERVER['HTTP_HOST'] . '/auth/loginFacebook');
        $url = $helper->getLoginUrl(['public_profile', 'email']);
        return $url;
    }
    function loginFacebook() {
		global $website_options;
		
		$userModel = new userModel();

    	if (!isset($_GET['code'])) {
    		header("Location: " . $this->facebookGetLoginUrl());
    		exit;
    	}

		$app_id    = $website_options['facebook_app_id'];
		$app_token = $website_options['facebook_app_token'];

		require_once('3rdparty/facebook/autoload.php');

		FacebookSession::setDefaultApplication($app_id, $app_token);

		$helper = new FacebookRedirectLoginHelper('http://' . $_SERVER['HTTP_HOST'] . '/auth/loginFacebook');
		try {
		  $session = $helper->getSessionFromRedirect();
		} catch(FacebookRequestException $ex) {
		  // When Facebook returns an error
// 			print_r($ex);
			die("facebook exception has occurred");
		} catch(\Exception $ex) {
		  // When validation fails or other local issues
// 			print_r($ex);
			die("facebook exception has occurred");
		}

		if (!$session) {
			var_dump($session);
			exit;

			echo "<script>alert('Unable to login with Facebook: empty session'); location = '/';</script>";
			exit;
		}

		if($session) {
		  try {
		    $user_profile = (new FacebookRequest(
		      $session, 'GET', '/me'
		    ))->execute()->getGraphObject(GraphUser::className());

		    $info = [];
			$fb_id = $user_profile->getId();
		    $name = $user_profile->getName();
		    $image = "http://graph.facebook.com/$fb_id/picture?type=normal";

		    $this->db->where('type=?', 'facebook');
		    $this->db->where('external_id=?', $fb_id);
		    $user = $this->db->select('users')[0];

		    if (!$user) {
		    	$user = [
		    		'name' => $name,
		    		'image' => $image,
		    		'external_id' => $fb_id,
		    		'user_slug' => $this->availableSlug($name),
		    		'type' => 'facebook',
		    		'location' => $user_profile->getLocation(),
		    		'email' => $user_profile->getProperty("email"),
		    		'password' => 'nopasswd'
		    	];

		    	$this->db->insert('users', $user);
		    	$user['id'] = $this->db->insert_id();

		    	$userModel->assignCard($user['id']);
		    }

		    $_SESSION['loggedin'] = 1;
			$_SESSION['user_id'] = $user['id'];
			$_SESSION['user'] = $user;
		  } catch(FacebookRequestException $e) {
		  	die("facebook exception has occurred");
		    echo "Exception occured, code: " . $e->getCode();
		    echo " with message: " . $e->getMessage();
		  }
		}
	}
}
