<?php

namespace User\Common;

/**
 * Class SSOHelper
 * @package Home\Common
 */
class SSOHelper
{
    const BASE_SSO_LOGIN_URL = 'http://pro.izhida.cn/sso_login';
    const BASE_SSO_TICKET_URL = 'http://pro.izhida.cn/sso_ticket';

    public static function check_login($app, $redirect_back_url = '')
    {
        if (empty($redirect_back_url)) {
            $redirect_back_url = self::get_url();
        }

        if (session('sso_auth_user') && session('sso_auth_timestamp') > time()) {
            return true;
        }
        $callback_url = self::get_callback_url();
        $sso_url = self::BASE_SSO_LOGIN_URL . '?' . http_build_query(array(
                'cb' => $callback_url,
                'app' => $app,
                'state' => $redirect_back_url,
            ));
        redirect($sso_url);
        return false;
    }

    public static function check_ticket($ticket)
    {
        vendor('Requests.Requests');
        \Requests::register_autoloader();
        $url = SSOHelper::BASE_SSO_TICKET_URL;
        $response = \Requests::request($url, null, array('ticket' => $ticket));
        $result = json_decode($response->body, true);
        var_dump($result);
        if (empty($result) || $result['errcode'] != 0) {
            exit('login failed');
        }
        return array($result['data']['user'], $result['data']['state']);
    }

    private static function get_url()
    {
        $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
        $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
        $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
        $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
        return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
    }

    private static function get_callback_url()
    {
        $callback_url = C('SSO_CALLBACK_URL');
        if (!empty($callback_url)) {
            return $callback_url;
        }
        $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
        $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
        $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
        $relate_url = isset($_SERVER['REQUEST_URI'])
            ? $_SERVER['REQUEST_URI']
            : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . '' : $path_info);
        return $sys_protocal . $_SERVER['HTTP_HOST'] . '/User/sso_broker';

    }
}