<?php

class unsubscribeModel extends baseModel {
    
    public $tableName = 'unsubscribe';
    
	function square_login($email, $password, $remember = 0) {
		if (!$email || !$password) {
			return 0;
		}
		
		$this->db->where('email=?', $email);
		//$this->db->where('password=?', $this->encodePwd($password));
		$this->db->where('type=?', 'native');
		$accounts_matched = $this->db->select('users');
		
//		print_r($accounts_matched);
//		exit;

		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 square_loginOLD($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('users');

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

            return 1;
        } else {
            return 0;
        }
    } 
    
	function pincode_login($pin_code)
	{
		if (!$pin_code) {
			return 3;
		} 

		$this->db->where('pin_code=?', $pin_code);

		$accounts_matched = $this->db->select('users');

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

			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;
		$_SESSION['user']['usertype']     = $account['usertype'];

        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('recovery_code=?', $code);
        $u = $this->db->select('users');
        if (!empty($u)) {
            return 1;
        } 
    }

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

        $this->db->where('recovery_code=?', $code);
        
        // NEW
		$this->db->update('users', ['password' => $this->hash($pwd), 'recovery_code' => '']);
		// OLD
        //$this->db->update('users', ['password' => $this->getEncryptedPassword($pwd), 'recovery_code' => '']);
		//$this->db->update('users', ['password' => $this->getEncryptedPassword($pwd), 'address2' => 'Worked']);


		$updated = $this->db->affected_rows();

		if($updated = 1){
			return 1;
		} else {
			//echo "Ooopsie...";
			header("Location: " . get('siteroot') . 'auth/forgot?msg=' . urlencode("Oooops! Something went wrong. Please try again or contact Tech Support on our Contact page."));
		}
		/*
        if ($this->db->affected_rows()) {
            return 1;
        } else { 
			echo "Ooops";
		}*/
    }

    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', ['recovery_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];
		$userdata['given_name']  = $name[0];
		$userdata['family_name'] = $name[1];

		$this->db->insert('users', $userdata);
		return $this->db->insert_id();
    }

    function registerOLD($userdata) {
		//print_r($userdata);
		//exit;
//    	if (!$userdata['given_name'] || !$userdata['email'] || !$userdata['password']) {
//            header("Location: /dash/register?oops");
//            exit;
//        }

        $this->db->where("email=?", $userdata['email']);
        $u = $this->db->select("users");
        if (count($u) > 0) {
            header("Location: /auth/register?msg=That+User+Account+already+exists");
            exit;
        }
		/*
        foreach ($userdata as $index => $value) {
            if (!in_array($index, self::$fields)) {
                unset($userdata[$index]);
            }
        }*/
		$userdata['ref'] = $userdata['refcode'];
		//$encrypted_pwd = getEncryptedPassword($new_password);
        $userdata['password'] = $this->getEncryptedPassword($userdata['password']);
        $userdata['token'] = sha1($userdata['email'] . "9Tv". time());
        
        //$username = substr($userdata['email'], 0, strpos($userdata['email'], '@'));
        //$userdata['given_name'] = $username;
		
        //$userdata['user_slug'] = $this->availableSlug($username);
    
        $this->db->insert('users', $userdata);
       return $this->db->insert_id();
    }
    
	function subscribe($subscriberdata) {
		if (!$subscriberdata['email']) {
			header("Location: /");
			exit;
		}

		$this->db->where("email=?", $subscriberdata['email']);
		$u = $this->db->select("subscribers");
		if (count($u) > 0) {
			header("Location: /useralreadyexists");
			exit;
		}
        
		$subscriberdata['code'] = mt_rand(1,99999);	
        //$subscriberdata['interestedin'] = $_POST['interestedin'];
		
		$this->db->insert('subscribers', $subscriberdata);
		
		//mail("sillystats@gmail.com", "Subscriber Alert3!", "You have a new Subscriber!", "From: ThinApp <contact@getthinapp.com>");
	}	    
    
    // GET USER
    function getUser($uid) {
        $this->db->where("id=?", $uid);
        $user = $this->db->select_one('users');

        return $user;
    }    
    
}