<?php
//login contact
//login user

class SignIn {
    private $db;

    public function __construct()
    {
        $this->db = new Database;
    }

    //login user
    public function logInUser($username, $password) {

        $this->db->query('SELECT * FROM users WHERE username = :username');

        $this->db->bind(':username', $username);

        //tries to get info from db
        if($row = $this->db->single()) {
            $hashed_password = $row->user_password;
            //verifies password with encryped pass from database
            if(password_verify($password, $hashed_password)) {
                return $row;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    //login contact
    public function logInContact($username, $password) {

        $this->db->query('SELECT * FROM contacts WHERE contact_username = :username');

        $this->db->bind(':username', $username);

        //tries to get info from db
        if($row = $this->db->single()) {
            $hashed_password = $row->contact_password;
            //verifies password with encryped pass from database
            if(password_verify($password, $hashed_password)) {
                return $row;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    //call this function if user/contact successfully logged in
    public function setToken($id, $type, $ip) {
        try {
            //try creating random token else throw error
            if($token = bin2hex(random_bytes(32))) {
                //hashing password
                $this->db->query('INSERT INTO auth(token, ip, expiry, user_id, contact_id, company_id) VALUES (:token, :ip, NOW() + INTERVAL 1 DAY, :userId, :contactId, :companyId)');

                $this->db->bind(':token', $token);
                $this->db->bind(':ip', $ip);

                switch ($type) {
                    case 'contact';
                    $this->db->bind('userId', null);
                    $this->db->bind('contactId', $id->contact_id);
                    $this->db->bind('companyId', $id->company_id);
                    break;
                    case 'user';
                    $this->db->bind('userId', $id->user_id);
                    $this->db->bind('contactId', null);
                        $this->db->bind('companyId', null);
                }
                //inserts token with expiry and ip to database, return token on success or false on failure
                if ($this->db->execute()) {
                    return $token;
                } else {
                    return false;
                }
            } else {
                throw new Exception('Sorry, something went wrong! Please try again');
            }
        } catch (Exception $error) {
            echo json_encode(['error' => $error->getMessage()]);
        }
            }

    }