<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class auth_facebook_model extends CI_Model
{

    protected $facebook_client = null;

    public function __construct()
    {
        parent::__construct();
        $this->load->model('ciext/core_model');
        $this->load->library('ciext/configurator');
    }

    public function get_auth_link()
    {
        return $this->get_facebook_client()->getRedirectLoginHelper()->getLoginUrl('http://www.imtop2.r-team.com.ua/ajax/auth_facebook/auth_facebook_site/auth', [
                    'email',
                    'public_profile',
        ]);
    }

    public function auth()
    {
        $result = false;

        // get token
        $token = $this->get_facebook_client()->getRedirectLoginHelper()->getAccessToken();

        if (isset($token)) {
            $response = $this->get_facebook_client()->get('/me?fields=id,email,first_name,last_name,picture', $token->getValue());

            $user_info = $response->getGraphUser();

            if (!empty($user_info)) {
                // register customer
                if (!$this->is_facebook_user_exist($user_info->getId())) {
                    $this->register_facebook_user($user_info);
                }
                // auth customer
                $user = $this->get_user_by_facebook_id($user_info->getId());
                if (isset($user['id_acl_user'])) {
                    $this->session->set_userdata('id_user', $user['id_acl_user']);
                    $result = true;
                }
            }
        }

        return $result;
    }

    /**
     * @param string $facebook_user_id
     * @return bool
     */
    protected function is_facebook_user_exist($facebook_user_id)
    {
        return (!empty($this->get_user_by_facebook_id($facebook_user_id))) ? true : false;
    }

    /**
     * @param string $facebook_user_id
     * @return array
     */
    protected function get_user_by_facebook_id($facebook_user_id)
    {
        // prepare data
        $facebook_user_id = $this->db->escape_str($facebook_user_id);

        $id_lan = $this->core_model->get_lang_id();

        $user = $this->db->
                select('u.id_acl_user, u.login, u.photo, u.email, ut.name, ut.surname')->
                join('acl_user_translate ut', 'ut.id_acl_user=u.id_acl_user AND ut.id_lan=' . $id_lan, 'left')->
                join('acl_user_facebook uf', 'uf.id_acl_user=u.id_acl_user', 'left')->
                where('uf.facebook_user_id', $facebook_user_id)->
                get('acl_user u')->
                row_array();

        return $user;
    }

    /**
     * @param object $user_info
     */
    protected function register_facebook_user($user_info)
    {
        $user = $this->get_user_by_login($user_info->getEmail());
        $id_lan = $this->core_model->get_lang_id();

        // load picture
        if (!empty($user_info->getPicture()->getUrl())) {
            $picture_name = 'facebook_' . $user_info->getId() . '.jpg';
            file_put_contents($this->get_app_path() . '/assets/uploads/userinfo/' . $picture_name, file_get_contents($user_info->getPicture()->getUrl()));
        }

        // create new user
        if (empty($user)) {
            $this->db->insert('acl_user', array(
                'login'       => $user_info->getEmail(),
                'password'    => $this->rt_user->password_hash($this->get_user_pass()),
                'photo'       => (!empty($picture_name)) ? $picture_name : '',
                'email'       => $user_info->getEmail(),
                'id_acl_role' => 0,
                'registered'  => date('Y-m-d'),
                'confirmed'   => 1,
                'active'      => 1
            ));
            // get user id
            $user_id = $this->db->insert_id();

            $this->db->insert('acl_user_translate', array(
                'id_acl_user' => $user_id,
                'name'        => $user_info->getFirstName(),
                'surname'     => $user_info->getLastName(),
                'id_lan'      => $id_lan,
            ));

            $this->db->insert('acl_user_facebook', array(
                'id_acl_user'      => $user_id,
                'facebook_user_id' => $user_info->getId(),
            ));
        } else {
            // update existing user
            $this->db->insert('acl_user_facebook', array(
                'id_acl_user'      => $user['id_acl_user'],
                'facebook_user_id' => $user_info->getId(),
            ));
        }
    }

    /**
     * @return \Facebook\Facebook
     */
    protected function get_facebook_client()
    {
        if (is_null($this->facebook_client)) {
            if (session_id() == '') {
                session_start();
            }

            // load facebook api
            require_once $this->get_app_path() . 'vendor/autoload.php';

            $this->facebook_client = new Facebook\Facebook([
                'app_id'                  => $this->get_config_data('app_id'),
                'app_secret'              => $this->get_config_data('app_secret'),
                'default_graph_version'   => 'v2.6',
                'persistent_data_handler' => 'session'
            ]);
        }

        return $this->facebook_client;
    }

    /**
     * @param string $login
     * @return array
     */
    protected function get_user_by_login($login)
    {
        $user = $this->db->
                        select('id_acl_user')->
                        where('login', $login)->
                        get('acl_user')->row_array();

        return $user;
    }

    /**
     * @return string
     */
    protected function get_user_pass()
    {
        return $this->rt_user->password_hash('facebook user pass ' . time());
    }

    /**
     * @return string
     */
    public function get_app_path()
    {
        return dirname(dirname(dirname(dirname(BASEPATH)))) . '/';
    }

    /**
     * @param string $key
     * @return mixed
     */
    public function get_config_data($key)
    {
        $conf = new configurator('auth_facebook');

        return $conf->item($key);
    }

}
