<?php 

/** 
 *    SSO MODULE - iCrew v4. 
 *
 *    This module was made for authenticating external applications 
 *    using iCrew user's credentials. The module will return the pilot's 
 *    preliminary details such as email, ID, stats etc. 
 *
 *    You are to store that data in a session variable. 
 *    NEVER CACHE THEM! 
 *
 *    @author Leonard Selvaraja 
 *    @version 1.0 
 *    @date 15/03/2022
 * 
 * 
 * 
 *    endpoints: 
 *         /index | GET
 *         /login | POST | var: email, password
 *         /logout | GET
**/


class SSO extends CodonModule {


    // PLEASE SET THE TRUSTED URLS IN THE CONSTRUCT METHOD
    
    /**
     * __construct - build the class with the trusted urls array.
     *
     * @return void
     */
    public function __construct()
    {   
        $this->trusted_urls = array(
            'localhost',
            'flyvua.test',
            'theanswer.vuainc.org',
        );

        $this->version = '1.0';
    }
    
    /**
     * index - We're just displaying a casual message that 
     * the SSO module belongs to the current VA. 
     *
     * @return void
     */
    public function index() {
        return $this->json('SSO Module v'. $this->version .' for '. SITE_NAME);
    }

    
    /**
     * check_if_request_has_come_from_a_trusted_website
     * I think the function name is pretty self explanatory.
     *
     * @param  mixed $url
     * @return bool
     */
    protected function check_if_request_has_come_from_a_trusted_website($url) {        
        if(in_array($url, $this->trusted_urls)) {
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * json - converts the given data into a json encoded data,
     *  and sets the header to support JSON.
     *
     * @param  mixed $data
     * @return void
     */
    protected function json($data) {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($data);
    }
    
    /**
     * base_url - to find out where the SSO request is coming from. 
     *
     * @param  mixed $atRoot
     * @param  mixed $atCore
     * @param  mixed $parse
     * @return string
     */
    protected function base_url($atRoot = false, $atCore = false, $parse = false){
        if (isset($_SERVER['HTTP_HOST'])) {
            $http = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
            $hostname = $_SERVER['HTTP_HOST'];
            $dir =  str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);

            $core = preg_split('@/@', str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(dirname(__FILE__))), NULL, PREG_SPLIT_NO_EMPTY);
            $core = $core[0];

            $tmplt = $atRoot ? ($atCore ? "%s://%s/%s/" : "%s://%s/") : ($atCore ? "%s://%s/%s/" : "%s://%s%s");
            $end = $atRoot ? ($atCore ? $core : $hostname) : ($atCore ? $core : $dir);
            $base_url = sprintf( $tmplt, $http, $hostname, $end );
        }

        // else $base_url = 'http://localhost/';

        if ($parse) {
            $base_url = parse_url($base_url);
            if (isset($base_url['path'])) if ($base_url['path'] == '/') $base_url['path'] = '';
        }

        return $base_url;
    }
    
    /**
     * validate - Validate the Username and password. Just 
     * check if they're not empty.
     *
     * @param  mixed $user
     * @param  mixed $password
     * @return bool|json
     */
    protected function validate($user, $password) {
        
        $error = false;

		$response['POST'] = $this->post;
        $response['GET'] = $this->get;

        if($user == '') {
            $response['message'] = 'E-mail / User ID cannot be blank';
            $response['code'] = 500;
            $error = true;
        } else if($password == '') {
            $response['message'] = 'Password cannot be blank';
            $response['code'] = 500;
            $error = true;
        }


        if($error != false) {
            return $this->json($response);
        } else {
            return true;
        }                
    }
    
    /**
     * login - The main login method. 
     * 
     * @param string $user 
     * @param string $password
     * @return void
     */
    public function login() {     
                                
        $response = array();                                
        // Check the origin URL        
        $url = $this->base_url(true, true, true)['host'];        
        
        // die($url);

        // Check if the request is coming from a trusted URL.         
        if(!$this->check_if_request_has_come_from_a_trusted_website($url)) {
            $response['message'] = 'Whoops! You have performed a request from an un-authorized URL. Please contact system administrator';
            $response['code'] = 201;
            return $this->json($response);
        }
        
        // $response['POST'] = $this->post;
        // $response['GET'] = $this->get;

        $user = $this->post->email;
        $password = $this->post->password;        

        $validation = $this->validate($user, $password);

        if($validation) {
            $processLogin = Auth::ProcessLogin($user, $password);
		
            if(!$processLogin) {
                // Login failed. 
                $response['message'] = Auth::$error_message;
                $response['code'] = 500;
            } else {
                // Login successful. 
                $response['message'] = 'Successfully authenticated';
                $response['code'] = 200;
                $response['data'] = array(
                    'token' => base64_encode(Auth::$pilot->email),
                    'session' => Auth::$session_id,
                    'pilotdata' => Auth::$pilot,
                    
                );                
            }
            
            return $this->json($response);
        }       
                
    }
    
    /**
     * logout - this is a phpvms default logout option. 
     * Altough, I think this would be obsolete. 
     *
     * @return json
     */
    public function logout() {
        Auth::LogOut();
        return $this->json(array(
            'message' => 'Successfully logged out',
            'code' => 200,
        ));
    }

}

?>