<?php
/**
* Created by PhpStorm.
* User: lambasoft
* Date: 8/28/17
* Time: 11:43 PM
*/

defined('BASEPATH') OR exit('No direct script access allowed');

require_once(APPPATH . "/controllers/Auth.php");

use Hybridauth\Hybridauth;
class My_User extends Auth {
    private $socialConfig = [
        //Location where to redirect users once they authenticate with Facebook
        //For this example we choose to come back to this same script
        'callback' => 'https://nooreed.com/login-signup',

        'providers' => [
            'Google' => [
                'enabled' => true,
                'keys'    => [
                    'id' => '524818703253-kmeme4daoldl66ejoukd1jujgs63v9ka.apps.googleusercontent.com',
                    'secret' => 'KucwKr5TQbnjJyhCNln3u6xZ'
                ],
            ],
            'Facebook' => [
                'enabled' => true,
                'keys' => [
                    'id'     => '1976597312619261' , //'1551877084879244', //Required: your Facebook application id
                    'secret' => '85f702c530e0ec69c59d609aac2deb30'//'657bf1cc85ba98e30d80676b42999d94'  //Required: your Facebook application secret
                ],
                'scope' => "email"
            ],

            'Twitter' => [
                'enabled' => true,
                'keys'    => [ 'key' => 'a365X8DHLrqyl0y5hnJAjq1We', 'secret' => 'mFQI3VFJxRqSPIBwkcpxflNsQIwgyOPl3llE1kbNHiItRgvMK1' ],
            ]
        ],
    ];

    public function __construct(){
        parent::__construct();
        $this->output->set_header('Last-Modified: ' . gmdate("D, d M Y H:i:s") . ' GMT');
        $this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
        $this->output->set_header('Pragma: no-cache');
        $this->output->set_header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    }

    public function register(){
        if ($this->ion_auth->logged_in())
        {
            redirect('home', 'refresh');
        }

        $tables = $this->config->item('tables','ion_auth');
        $identity_column = $this->config->item('identity','ion_auth');
        $this->data['identity_column'] = $identity_column;

        // validate form input
        $this->form_validation->set_rules('first_name', $this->lang->line('create_user_validation_fname_label'), 'required|min_length[2]|max_length[42]');
        //$this->form_validation->set_rules('last_name', $this->lang->line('create_user_validation_lname_label'), 'required|min_length[2]|max_length[12]');
        $this->form_validation->set_rules('email', $this->lang->line('create_user_validation_email_label'), 'required|valid_email|is_unique[my_users.email]');
        $this->form_validation->set_rules('password', 'Password', 'required');
        //$this->form_validation->set_rules('password_confirmation', 'Password Confirmation', 'required|matches[password]');
        $this->form_validation->set_rules('social_identifier', 'Social Identifier', 'numeric');
        $this->form_validation->set_rules('social_network', 'Social Network', 'in_list[Facebook,Twitter,Google]');

        if ($this->form_validation->run() == FALSE){
            if(!empty($this->input->post('social_identifier'))){
                $additional_data = array(
                    'email' => $this->input->post('email'),
                    'first_name' => $this->input->post('first_name')." ".$this->input->post('last_name'),
                    'grade' => $this->input->post('grade'),
                    'school' => $this->input->post('school'),
                    'social_identifier'  => $this->input->post('social_identifier'),
                    'social_network'  => $this->input->post('social_network')
                );
                $this->view("social-signup", $additional_data);
            }else{
                $this->view("login-signup", array("activeTab" => "register"));
            }
        }else{

            $email    = strtolower($this->input->post('email'));
            $identity = ($identity_column==='email') ? $email : $this->input->post('identity');
            $password = $this->input->post('password');

            $additional_data = array(
                'first_name' => $this->input->post('first_name')." ".$this->input->post('last_name'),
                'grade' => $this->input->post('grade'),
                'school' => $this->input->post('school'),
                'social_identifier'  => $this->input->post('social_identifier'),
                'social_network'  => $this->input->post('social_network')
            );
            if($this->ion_auth->register($identity, $password, $email, $additional_data)){
                //redirect('home', 'refresh');
                $this->view('login-signup' , array( "registered" => TRUE));
            }else{
                $error = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));

                $this->view("login-signup", array("activeTab" => "register", "error" => $error));
            }
        }

    }

    public function login()
    {
        if ($this->ion_auth->logged_in()) {
            redirect('home', 'refresh');
        }

        //validate form input
        $this->form_validation->set_rules('identity', str_replace(':', '', $this->lang->line('login_identity_label')), 'required');
        $this->form_validation->set_rules('password', str_replace(':', '', $this->lang->line('login_password_label')), 'required');

        if ($this->form_validation->run() == true){
            // check to see if the user is logging in
            // check for "remember me"
            $remember = (bool) $this->input->post('remember');

            if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember)){
                //if the login is successful
                //redirect them back to the home page
                $this->view('login-signup' , array("activeTab" => "login", "logged" => TRUE));
            }
            else{
                // if the login was un-successful
                $this->session->set_flashdata('message', $this->ion_auth->errors());

                $error = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));

                $this->view("login-signup", array("activeTab" => "login", "error" => $error));

            }
        }
        else
        {
            // the user is not logging in so display the login page
            // set the flash data error message if there is one
            $this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');

            $this->data['identity'] = array('name' => 'identity',
                'id'    => 'identity',
                'type'  => 'text',
                'value' => $this->form_validation->set_value('identity'),
            );
            $this->data['password'] = array('name' => 'password',
                'id'   => 'password',
                'type' => 'password',
            );

            $this->_render_page('auth/login', $this->data);
        }
    }

    // log the user out
    public function logout(){
        // log the user out
        $logout = $this->ion_auth->logout();

        // redirect them to the login page
        $this->session->set_flashdata('message', $this->ion_auth->messages());
        //redirect('login-signup', 'refresh');
        redirect($_SERVER["HTTP_REFERER"], 'refresh');
    }


    public function socialRegister($socialNetwork){
        if(!in_array($socialNetwork, array("Facebook", "Twitter","Google")) || $this->ion_auth->logged_in()){
            redirect('home', 'refresh');
        }

        $this->socialConfig['callback'] = "https://nooreed.com/social_callback/{$socialNetwork}";


        $hybridauth = new Hybridauth( $this->socialConfig );
        $adapter = $hybridauth->authenticate( $socialNetwork );
        $isConnected = $adapter->isConnected();

        if($isConnected){
            $userProfile = $adapter->getUserProfile();
            $isValidAccount = $this->ion_auth->login_by_provider($socialNetwork,$userProfile->identifier);
            if($isValidAccount){
                redirect('home', 'refresh');
            }else{
                $additional_data = array(
                    'email' =>  $userProfile->email,
                    'first_name' => $userProfile->firstName,
                    'last_name'  => $userProfile->lastName,
                    "social_network" => $socialNetwork,
                    "social_identifier" => $userProfile->identifier
                );
                $this->view("social-signup", $additional_data);
            }

        }
        return TRUE;
    }


    public function social_callback($socialNetwork){
        if(!in_array($socialNetwork, array("Facebook", "Twitter","Google")) || $this->ion_auth->logged_in()){
            redirect('home', 'refresh');
        }

        $this->socialConfig['callback'] = "https://nooreed.com/social_callback/{$socialNetwork}";
        $hybridauth = new Hybridauth( $this->socialConfig );
        $adapter = $hybridauth->authenticate( $socialNetwork );
        //Returns a boolean of whether the user is connected with Facebook
        $isConnected = $adapter->isConnected();

        if($isConnected){
            //Retrieve the user's profile
            $userProfile = $adapter->getUserProfile();
            $email    = $userProfile->email;
            $additional_data = array(
                'email' => $email,
                'first_name' => $userProfile->firstName,
                'last_name'  => $userProfile->lastName,
                "social_network" => $socialNetwork,
                "social_identifier" => $userProfile->identifier
            );
            $this->view("social-signup", $additional_data);
        }else{
            $this->view("login-signup", array("activeTab" => "register", "error" => "Unable to connect to: {$socialNetwork}"));
        }

    }
}
