<?php

/* *
 * Vinnorokom Facebook Quiz App V.2.1.3
 * Home controller for fontend
 * All font end action controlled by this controller
 * One quiz model class using for fecthing data
 * Laravel authentication http://laravel.com/docs/4.0/security
 *
 */

class HomeController extends BaseController {

    private $apObj;
    private $data = array();
    private $fbdata = array();
    private $default_setting;
    private $group_id;
    private $common;
    private $poll;

    public function __construct() {
        $data = Auth::user(); // Logged user
        $this->data = $data;
        $this->apObj = new Quiz(); // Load Quiz Model Class
        $this->poll = new Poll(); // Load Poll Model Class
        $this->common = new Common();   // Load Common model Class
        $this->default_setting = $this->apObj->getQuizSetting(); // Load default setting method and set to private varible
    }

    /*
     * Home page index
     * Generate Session  Session::regenerate();
     * Put new session into timestamp
     *
     */

    public function index() {
        $data = array();
        Session::regenerate(); // Generate new session
        Session::put('timestamp', ''); // Session clear
        // is user loggedin or not
        $result = array();
        if (Auth::check()) {
            $data = Auth::user();
            $result = $this->apObj->getQuizResultByUser($data['fbid']);
            if (Auth::user()->user_level == 1) {
                return Redirect::to('/admin')->with('message', '<i class="fa fa-alert"></i>To see home page , you must logout from admin panel')->with('class', 'alert-info');
            }
        }
        $poll_limit = 8;
        $poll_id_array = array();
        $poll_list = $this->poll->getOnlyPolls($poll_limit);
        $poll_text = '';
        $blog = '';
        $chart_data = '';

        if (!empty($poll_list)) {
            foreach ($poll_list as $pl) {
                $poll_id_array[] = $pl->poll_id;
            }

            // $rand_keys_poll_id = array_rand($poll_id_array, count($poll_id_array));
            $poll_id = $this->poll->getRandomPollId(); // $poll_id_array[$rand_keys_poll_id[0]]; // $this->poll->getRandomPollId();
            $poll_text = $this->poll->getPollTextById($poll_id);
            $chart_data = $this->getHomepageChartData($poll_id); // Call Chart JSON Data method
            $blog = $this->common->getHomePageBlog();
        }

        $quizzes = $this->apObj->getPublicQuizeGroups();
        $top_scrorer = $this->apObj->getTopScorer(); // Load Top Scorer

        return View::make('user.index', array('data' => $data))
                        ->with('chart_data', $chart_data)
                        ->with('result', $result)
                        ->with('poll_text', $poll_text)
                        ->with('poll_list', $poll_list)
                        ->with('blog', $blog)
                        ->with('quizzes', $quizzes)
                        ->with('top_scrorer', $top_scrorer);
    }

    /*
     * User profile page
     */

    public function loggedInUser() {
        Session::regenerate(); // Generate new session
        Session::put('timestamp', ''); // Session clear
        Session::put('quiz_group', Input::get('quiz_group')); // Set quiz group id
        $data = Auth::user();
        $group_id = Session::get('quiz_group');
        $group_details = $this->apObj->getQuizGroupById($group_id);
        $result = $this->apObj->getQuizResultByUser($data['fbid']);
        $info = $this->apObj->getQuizResultByUserId($data['fbid']);

        # Load user polls
        $polls = $this->poll->getPollsByUser($data['fbid']);

        return View::make('user.user', array('data' => $data))
                        ->with('result', $result)
                        ->with('group_details', $group_details)
                        ->with('info', $info)
                        ->with('polls', $polls);
    }

    /*
     * Facebook login
     * Call Facebook Class
     * get config value Config::get('facebook')
     */

    public function login() {
        #appId and appSecret are stored in config/facebook.php
        $facebook = new Facebook(Config::get('facebook'));

        $params = array(
            'redirect_uri' => url('/login/fb/callback'), // Redirect URL
            'scope' => 'email user_friends', // Application permission
        );

        return Redirect::to($facebook->getLoginUrl($params));
    }

    /*
     *  Logout
     *  Laravel Authentication logout
     *  http://laravel.com/docs/4.0/security
     */

    public function logOut() {
        Auth::logout(); // Log out
        Session::flush(); // Clear all session existing  data

        return Redirect::to('/logout');
    }

    // Call back url
    public function callBack() {
        $code = Input::get('code');
        if (strlen($code) == 0) {
            return Redirect::to('/')->with('message', 'There was an error connecting to Facebook');
        }
        $facebook = new Facebook(Config::get('facebook'));
        $uid = $facebook->getUser();
        if ($uid == 0) {
            return Redirect::to('/')->with('message', 'There was an error');
        }
        $me = $facebook->api('/me');
        $this->fbdata = $me;
        // check if user has been registered already
        $user = User::whereFbid($me['id'])->first();
        if (!$user) {
            // if not, get params and register
            $user = new User();
            $user->name = isset($me['name']) ? $me['name'] : '';
            $user->fbid = isset($me['id']) ? $me['id'] : '';
            $user->email = isset($me['email']) ? $me['email'] : ''; // Handled by null if user not allowed his email
            $user->gender = isset($me['gender']) ? $me['gender'] : '';
            $user->save();
            # If email found send email
            if (isset($me['email'])) {
                # Email address
                $name = isset($me['name']) ? $me['name'] : '';
                # Call email function
                $this->sendEmail(array('to' => $me['email'], 'heading' => 'Registration', 'name' => $name, 'subject' => 'New Registration'));
            }
        }
        Auth::login($user);

        return Redirect::to('/user/user')->with('message', '<i class="fa fa-check"></i> Successfully logged in with Facebook');
    }

    // Facebook Auth
    public function facebookAuth() {
        $input = Input::all();
        $user_id = isset($input['data']['id']) ? $input['data']['id'] : '';
        $this->fbdata = $input;
        $user = User::whereFbid($user_id)->first();
        if (!$user) {
            // if not, get params and register
            $user = new User();
            $user->name = isset($input['data']['name']) ? $input['data']['name'] : '';
            $user->fbid = $user_id;
            $user->email = isset($input['data']['email']) ? $input['data']['email'] : ''; // Handled by null if user not allowed his email
            $user->gender = isset($input['data']['gender']) ? $input['data']['gender'] : '';
            $user->save();
            if (isset($input['data']['email'])) {
                $name = isset($input['data']['name']) ? $input['data']['name'] : '';
                $this->sendEmail(array('to' => $input['data']['email'], 'heading' => 'Registration', 'name' => $name, 'subject' => 'New Registration'));
            }
        }
        Auth::login($user);

        return array('success' => 1, 'msg' => 'Successfully logged in !');
    }

    /*
     * Quiz started
     *
     */

    public function started() {

        // Check User ban permission
        $data = Auth::user();
        if (Auth::user()->status == 0) {
            return Redirect::to('/user/user')->with('message', '<i class="fa fa-exclamation-triangle"></i> You are blocked by Admin! Please contact with admin');
        }
        $group_id = Session::get('quiz_group'); // Get group id from session
        $random = isset($this->default_setting->random_options) ? $this->default_setting->random_options : 0; // if 1 Sort options Randomly
        // $group_id = Input::get('quiz_group'); //isset($this->default_setting->default_group) ? $this->default_setting->default_group : 0; // Get default group Id
        if ($group_id == '') {
            return Redirect::to('/user/user')->with('message', '<i class="fa fa-bullhorn"></i> Please select a quiz group');
        }

        $group_details = $this->apObj->getQuizGroupById($group_id);

        $publish_from = isset($this->default_setting->publish_from) ? $this->default_setting->publish_from : 0; //Publish date from
        $publish_to = isset($this->default_setting->publish_to) ? $this->default_setting->publish_to : 0; //Publish date to
        $valid = 0;

        /* Quiz setting date range checking
         * false return to user page
         */
        /*
          $todate = strtotime(date("Y-m-d H:i:s"));
          $date_begin = strtotime($publish_from);
          $date_end = strtotime($publish_to);

          if ($todate > $date_begin && $todate < $date_end) {
          // is valid date range
          } else {
          return Redirect::to('/user/user')->with('message', '<i class="fa fa-exclamation-triangle"></i> There is no active quiz group in schedule now!');
          }
         */

        $data = $this->data;
        // $quizObj = $this->apObj;
        $n = Input::get('next');
        $nex_quiz = isset($n) ? $n : 0;
        $ans = Input::get('option'); // Quiz option
        $ans = isset($ans) ? $ans : 0;
        $nex_quiz_id = 0;
        $session_id = Session::getId();
        if ($nex_quiz > 0 || $nex_quiz == 0) {
            $nex_quiz_id = $this->apObj->nextQuiz($nex_quiz, $group_id); // Next quiz
            $quiz_id = isset($nex_quiz_id['quiz_data']->id) ? $nex_quiz_id['quiz_data']->id : null;
        }
        // Util::printArr($nex_quiz_id['quiz_data']) ;exit ;
        // Last participate quiz
        $last_participate_quiz = $this->apObj->getLastParticipant($session_id, $data['fbid'], $quiz_id);

        if ($last_participate_quiz > 0) {
            $nex_quiz_id = $this->apObj->nextQuizId($quiz_id, $group_id); // Get next quiz id
            $quiz_id = isset($nex_quiz_id->id) ? $nex_quiz_id->id : null;
        }

        if ($ans > 0) {
            $user_ans = array('ur_ans' => $ans, 'qid' => $n, 'uid' => $data['fbid'], 'session_id' => $session_id);
            $this->apObj->savaQuizData($user_ans);
        }

        if (empty($nex_quiz_id['quiz_data'])) {
            return Redirect::to('/user/result?quiz_group=' . $group_id); // If no questions go to result page
        }

        // Get quiz list
        $getQuiz = $this->apObj->getQuizList($quiz_id, $group_id);
        $getQuizOptions = $this->apObj->getOptionList($random);
        foreach ($getQuizOptions as $op) {
            $option[$op->qid][$op->id] = $op->qtext;
        }

        $info = $this->apObj->getQuizResultByUserId($data['fbid']); // Load user quiz information Pass / fails
        // Load view
        return View::make('user.main', array('data' => $data))
                        ->with('quiz_data', $getQuiz)
                        ->with('options', $option)
                        ->with('nex_quiz_id', $nex_quiz_id)
                        ->with('group_details', $group_details)
                        ->with('info', $info);
        //->with('quiz_group', $get_quiz_group);
    }

    /*
     * Get Quiz list
     * @get session id  Session::getId()
     */

    public function quizResult() {

        // Call object
        $quizObj = $this->apObj;
        $session_id = Session::getId();
        $data = $this->data;
        $user_ans_data = $quizObj->getResult($session_id, $data['fbid']);
        if (empty($user_ans_data)) {
            return Redirect::to('/user/user')->with('message', '<i class="fa fa-exclamation-triangle"></i> There is no active quiz group now!');
        }
        $correct = 0;
        $incorrect = 0;
        $parcent = 0;
        $times = array();
        $total = count($user_ans_data);

        foreach ($user_ans_data as $t) {
            if ($t->true_ans == $t->your_ans) {
                ++$correct;
            }
            $times[] = $t->date;
        }
        # Time calculation
        $maxtime = max($times);
        $mintime = min($times);
        $dteStart = new DateTime($mintime);
        $dteEnd = new DateTime($maxtime);
        $dteDiff = $dteStart->diff($dteEnd); //  date difference

        $incorrect = $total - $correct; // Calculation result
        $parcent = round(($correct / $total) * 100);
        $result['total'] = $total;
        $result['correct'] = $correct;
        $result['incorrect'] = $incorrect;
        $result['parcent'] = $parcent;
        $result['details'] = $user_ans_data;
        $result['time'] = $dteDiff->format('%H:%I:%S'); // date format
        $result['data'] = $data;

        $timestamp = date('Ymd') . date('Him');

        /*
         * Save result data
         *
         */
        $rdata['fid'] = $data['fbid'];
        $rdata['true_ans'] = $correct;
        $rdata['total'] = $total;
        $rdata['false_ans'] = $incorrect;
        $rdata['avg_grade'] = $parcent;
        $rdata['quiz_date'] = date('Y-m-d H:i:s');
        $rdata['timestamp'] = $timestamp;
        $rdata['session_id'] = $session_id;
        $rdata['group_id'] = Input::get('quiz_group'); // isset($this->default_setting->default_group) ? $this->default_setting->default_group : 0; // Get default group Id

        /* Save result data */
        if ((!Session::get('timestamp'))) {
            $save_result_id = $this->apObj->saveResults($rdata);
            Session::put('save_result_id', $save_result_id);
            Session::put('timestamp', $timestamp);
        }
        // If user share this redirect url parameter will get session and user id
        // @update result share status
        $post_id = (Input::get('post_id') != '') ? Input::get('post_id') : 0;
        $share = (Input::get('share') != '') ? Input::get('share') : 0;
        $error_code = (Input::get('error_code') != '') ? Input::get('error_code') : 0; //Get error code from redirect url if failed
        $resultdata = array('is_shared' => 1);

        if ($share > 0 && $error_code == 0) {
            $this->apObj->updateResultShareStatus($resultdata, Session::get('timestamp'), $data['fbid']);
        }

        //
        // Facebook share url
        $get_group_graph_image = $this->apObj->getQuizGroupById($rdata['group_id']);
        $desc = "Participate+$total+quizes+and+correct+$correct+and+wrong+$incorrect ";
        //$image_url = $get_group_graph_image->image_path; //url() . Config::get('facebook.graphimage'); // from Config file Opengraph Image Url
        $param = 'title=' . $data['name'] . '+got+' . $parcent . '% score. +Would+you+like+to+beat+this+score?';
        $url = $this->facebookUrl(Session::get('save_result_id'), Session::get('timestamp'), $data['fbid']); // get facebook share url
        $info = $this->apObj->getQuizResultByUserId($data['fbid']); // Load user quiz information Pass / fails
        return View::make('user.result')->with('result', $result)->with('data', $data)->with('share', $url)->with('info', $info);
    }

    /*
     *  Facebook Share url
     *  @return url
     *
     */

    public function shareFacebook($result_id) {
        $timestamp = Input::get('timestamp');
        $user_id = Input::get('user_id');
        $get_result = $this->common->getResultById($result_id);

        $score = isset($get_result->avg_grade) ? $get_result->avg_grade : ''; // Score grade
        $group_id = isset($get_result->group_id) ? $get_result->group_id : ''; // Get group id ;
        $user_id = isset($get_result->fid) ? $get_result->fid : ''; // Get facebook id
        $user_name = User::where('fbid', $user_id)->first();
        // User name by ID
        $name = isset($user_name->name) ? $user_name->name : '';

        $get_group = $this->apObj->getQuizGroupById($group_id);
        $group_image = isset($get_group->image_path) ? $get_group->image_path : '';
        // Load page setting
        $page_setting = $this->apObj->getPageSetting();
        $title_text = isset($page_setting->custom_share_text) ? $page_setting->custom_share_text : '';
        $result = str_replace(
                array('{name}', '{score}'), array($name, $score), $title_text);
        $details_text = isset($page_setting->custom_details_text) ? $page_setting->custom_details_text : '';

        $getShareData = $this->apObj->facebookDataforSharing($timestamp, $user_id);

        return View::make('user.facebook-page')
                        ->with('data', $getShareData)
                        ->with('title', $result)
                        ->with('details_text', $details_text)
                        ->with('image', $group_image);
    }

    /*
     * Facebook Url
     * @param share
     * @param sessionId
     * @user_id
     * @return Facebook share url
     */

    public function facebookUrl($group_id, $sessionId, $user_id) {
        $app_id = Config::get('facebook.appId');
        $domain = url();
        $url = 'https://www.facebook.com/dialog/share?'
                . "app_id=$app_id"
                . '&href=' . url() . "/share-facebook/$group_id"
                . '&display=touch'
                . "&redirect_uri=$domain/user/result?share=1&ses=$sessionId&user_id=$user_id";

        return $url;
    }

    /*
     * Error page
     * Exception handle by error page
     */

    public function errorPage() {
        return View::make('user.error');
    }

    /* Poll */

    public function polls() {
        $poll_limit = 6;
        $todate = date('Y-m-d'); // Today
        $poll_id = $this->poll->getPollIdByDate($todate); // Poll ID by DATE
        $pollDetails = $this->poll->getOnlyPollTextById($poll_id);

        $poll_text = isset($pollDetails->poll_text) ? $pollDetails->poll_text : '';
        $short_code = isset($pollDetails->short_code) ? $pollDetails->short_code : '';
        $top_scrorer = $this->apObj->getTopScorer(); // Load Top Scorer
        $poll = $this->poll->getAllPollList($poll_limit);

        return View::make('user.poll')->with('poll', $poll)
                        ->with('data', $this->data)
                        ->with('poll_text', $poll_text)
                        ->with('short_code', $short_code)
                        ->with('top_scrorer', $top_scrorer);
    }

    // User vote
    public function userVote() {
        if (isset(Auth::user()->id)) {
            $input = Input::all();
            $input['fbid'] = (string) Auth::user()->fbid;
            $input['ip'] = $_SERVER['REMOTE_ADDR'];
            $input['created_at'] = date('Y-m-d H:i');
            $vote = $this->poll->vote($input);
            if ($vote == 1) {
                return array('success' => 1, 'msg' => '<i class="fa fa-check"></i> Your vote has been accepted!');
            }
            if ($vote == 2) {
                return array('success' => 0, 'msg' => '<i class="fa fa-smile-o"></i> Voting time expired !');
            }
            if ($vote == 0) {
                return array('success' => 0, 'msg' => '<i class="fa fa-smile-o"></i> You have already voted !');
            }
        } else {
            return array('success' => 0, 'msg' => 'Please login!');
        }
    }

    /*  Poll ajax form load by poll_id
     * @param poll_id
     * @return poll_data     *
     */

    public function pollForm($poll_id) {
        $today = date('Y-m-d');
        $poll_text = $this->poll->getPollTextById($poll_id);
        $poll = $this->poll->getPollWithNumber($poll_id, $today);
        if (isset(Auth::user()->id)) {
            $view = View::make('user.vote')->with('poll', $poll)->with('poll_text', $poll_text);
            $view = $view->render();

            return array('success' => 1, 'msg' => $view);
        } else {
            return array('success' => 0, 'msg' => 'Please login !');
        }
    }

    /*
     *  Todays poll load
     */

    public function pollsToday() {
        $todate = date('Y-m-d'); // Today
        $poll_id = $this->poll->getPollIdByDate($todate); // Poll ID by DATE
        $poll_text = $this->poll->getPollTextById($poll_id);
        $short_code = $this->poll->getPollShortCodeById($poll_id);
        $poll = $this->poll->getPollWithNumber($poll_id, $todate);

        return View::make('user.poll-today')->with('poll', $poll)->with('poll_text', $poll_text)->with('short_code', $short_code);
    }

    /*
     *  Poll page load
     */

    public function pollsById($poll_id) {
        $pollDetails = $this->poll->getOnlyPollTextById($poll_id);
        $poll_text = isset($pollDetails->poll_text) ? $pollDetails->poll_text : '';
        $short_code = isset($pollDetails->short_code) ? $pollDetails->short_code : '';
        $poll_image = isset($pollDetails->image_path) ? $pollDetails->image_path : '';
        $poll = $this->poll->getPollWithNumber($poll_id);

        return View::make('user.poll-today')
                        ->with('poll', $poll)
                        ->with('poll_text', $poll_text)
                        ->with('short_code', $short_code)
                        ->with('poll_image', $poll_image);
    }

    /* /*
     *  Polls view more page load by poll_id
     *  @param Poll_id
     */

    public function pollsViewMore($poll_id) {
        $get_next_id = $this->poll->getPollNextId($poll_id);
        if ($get_next_id != 0) {
            $poll_text = $this->poll->getPollTextById($get_next_id);
            $poll = $this->poll->getPollWithNumber($get_next_id);

            $pollDetails = $this->poll->getOnlyPollTextById($get_next_id);
            $poll_text = isset($pollDetails->poll_text) ? $pollDetails->poll_text : '';
            $short_code = isset($pollDetails->short_code) ? $pollDetails->short_code : '';
            $poll_image = isset($pollDetails->image_path) ? $pollDetails->image_path : '';

            $view = View::make('user.poll-today')->with('poll', $poll)
                    ->with('poll_text', $poll_text)
                    ->with('short_code', $short_code)
                    ->with('poll_image', $poll_image);

            $view = $view->render();

            return array('poll_id' => $get_next_id, 'view' => $view);
        } else {
            echo 0;
        }
    }

    /*
     *  Poll Sharing page by short code
     *  @param short_code
     */

    public function pollsShare($short_code) {
        $short_code = trim($short_code); // Removing space
        $poll_id = $this->poll->getPollByShortCode($short_code);

        $pollDetails = $this->poll->getOnlyPollTextById($poll_id);
        $poll_text = isset($pollDetails->poll_text) ? $pollDetails->poll_text : '';
        $short_code = isset($pollDetails->short_code) ? $pollDetails->short_code : '';
        $poll_image = isset($pollDetails->image_path) ? $pollDetails->image_path : '';
        $top_scrorer = $this->apObj->getTopScorer(); // Load Top Scorer
        $poll = $this->poll->getPollWithNumber($poll_id);

        return View::make('user.poll-share')->with('poll', $poll)
                        ->with('poll_text', $poll_text)
                        ->with('data', $this->data)
                        ->with('short_code', $short_code)
                        ->with('poll_image', $poll_image)
                        ->with('top_scrorer', $top_scrorer);
    }

    /* Home page poll chart data
     * @param poll_id
     * @return json chart data
     *
     */

    public function getHomepageChartData($poll_id) {
        $color = array('#F7464A', '#46BFBD', '#FDB45C', '#949FB1', '#4D5360', 'rgb(120, 234, 196)', '#F7464A', '#46BFBD', '#FDB45C', '#949FB1');
        $highlight = array('#FF5A5E', '#5AD3D1', '#FFC870', '#A8B3C5', '#616774', 'rgb(131, 255, 213)', '#FF5A5E', '#5AD3D1', '#FFC870', '#A8B3C5');

        $json_data = array();
        $json_data_arr = array();
        $poll_limit = 2;

        $poll = $this->poll->getOnlyPolls($poll_limit);
        $cnt = 0;
        foreach ($poll as $p) {
            $poll_result = $this->poll->getPollWithNumber($poll_id);

            $c = 0;
            foreach ($poll_result as $op) {
                $json_data[] = array('value' => isset($op->number) ? $op->number : 0,
                    'color' => isset($color[$c]) ? $color[$c] : '#46BFBD',
                    ' highlight' => isset($highlight[$c]) ? $highlight[$c] : '#5AD3D1',
                    'label' => $op->poll_option_text,);

                ++$c;
            }
            $json_data_arr[] = $json_data;
            $json_data = '';
            //Util::printArr( json_encode($json_data))  ;
            ++$cnt;
        }

        return json_encode($json_data_arr[0]);
    }

    /*
     *  Get Page by Slug
     */

    public function pageBySlug($slug) {
        $page_data = $this->apObj->pageLoadBySlug($slug);
        $menu = $this->common->getMenuBlogList();

        return View::make('user.page')->with('page_data', $page_data)->with('menu', $menu);
    }

    /*
     *  Get Blog list
     */

    public function pageGetBlogs() {
        $bloglist = $this->common->getAllBlog();
        $menu = $this->common->getMenuBlogList();

        return View::make('user.blog')->with('blog_data', $bloglist)->with('menu', $menu);
    }

    /*
     * Front end user quiz page
     *
     */

    public function startQuiz($quiz_id = null) {
        $group_id = $quiz_id; // Get group id from session
        $random = isset($this->default_setting->random_options) ? $this->default_setting->random_options : 0; // if 1 Sort options Randomly
        // $group_id = Input::get('quiz_group'); //isset($this->default_setting->default_group) ? $this->default_setting->default_group : 0; // Get default group Id
        $group = $this->apObj->getQuizGroupById($group_id);
        if ($group_id == '') {
            return Redirect::to('/')->with('message', ' Please select a quiz group');
        }

        if (empty($group)) {
            return Redirect::to('/')->with('message', ' Please select a quiz group');
        }
        $question_id = Input::get('question_id');

        $group_details = $this->apObj->getQuizGroupById($group_id);
        $public_quizzes = array();
        $quiz_options = array();

        $quiz = $this->apObj->getPublicQuizzes($group_id, $question_id);
        $quiz_id = isset($quiz->id) ? $quiz->id : 0;
        $quiz_text = isset($quiz->text) ? $quiz->text : '';
        foreach ($this->apObj->getOptionListById($quiz_id) as $option) {
            $quiz_options[$option->id] = $option->qtext;
        }
        # Next Question ID
        $next_id = $this->apObj->nextQuizId($quiz_id, $group_id);
        $next_id = isset($next_id->id) ? $next_id->id : 0;

        $public_quizzes = array(
            'id' => $quiz_id,
            'text' => $quiz_text,
            'options' => $quiz_options,
            'next_id' => $next_id,
        );

        // Util::printArr($public_quizzes);
        //exit;
        # Check validity of quiz
        $publish_from = isset($this->default_setting->publish_from) ? $this->default_setting->publish_from : 0; //Publish date from
        $publish_to = isset($this->default_setting->publish_to) ? $this->default_setting->publish_to : 0; //Publish date to
        $valid = 0;

        /* Quiz setting date range checking
         * false return to user page
         */

        $todate = strtotime(date('Y-m-d H:i:s'));
        $date_begin = strtotime($publish_from);
        $date_end = strtotime($publish_to);

        if ($todate > $date_begin && $todate < $date_end) {
            // is valid date range
        } else {
            return Redirect::to('/quiz')->with('message', '<i class="fa fa-exclamation-triangle"></i> There is no active quiz group in schedule now!');
        }

        // Load view
        return View::make('user.quiz')->with('quiz', $group)->with('question', $public_quizzes);
    }

    /*
     * Start quiz
     */

    public function startQuizPost($group_id) {

        # Current Session ID
        $session_id = Session::getId();
        // Set timestamp null;
        Session::put('timestamp', null);

        $input = Input::all();
        $session_data = Session::get('quiz_data');
        $session_question = array();

        if (!empty($session_data)) {
            foreach ($session_data as $session) {
                $session_question[] = $session['question_id'];
            }
        }
        if (!in_array($input['question_id'], $session_question)) {
            Session::push('quiz_data', $input);
        }

        if ($input['next_id'] == 0) {
            return Redirect::to('/quiz-result');
        }

        return Redirect::to('/quiz/' . $group_id . '?question_id=' . $input['next_id']);
    }

    /*
     *  Quiz result
     */

    public function publicQuizResult() {
        $session_data = Session::get('quiz_data');
        $session_id = Session::getId();
        if (!isset($session_id)) {
            return Redirect::to('/quiz');
        }

        $result = array();
        $rdata = array();
        // Check auth
        if (isset(Auth::user()->fbid)) {
            $user_id = Auth::user()->fbid;
            #Insert temp data
            $this->apObj->insertQuizTempdata($session_data, $user_id);

            $result = $this->apObj->getResult($session_id, $user_id);

            # IF auth user
            # Quiz result saved
            $correct = 0;
            $incorrect = 0;
            $parcent = 0;
            $times = array();
            $total = count($result);

            foreach ($result as $t) {
                if ($t->true_ans == $t->your_ans) {
                    ++$correct;
                }
                $times[] = $t->date;
            }
            # Time calculation
            $maxtime = max($times);
            $mintime = min($times);
            $dteStart = new DateTime($mintime);
            $dteEnd = new DateTime($maxtime);
            $dteDiff = $dteStart->diff($dteEnd); //  date difference

            $incorrect = $total - $correct; // Calculation result
            $parcent = round(($correct / $total) * 100);
            $resultArray['total'] = $total;
            $resultArray['correct'] = $correct;
            $resultArray['incorrect'] = $incorrect;
            $resultArray['parcent'] = $parcent;
            $resultArray['details'] = $result;
            $resultArray['time'] = $dteDiff->format('%H:%I:%S'); // date format


            $timestamp = date('Ymd') . date('Him');

            /*
             * Save result data
             *
             */
            $rdata['fid'] = Auth::user()->fbid;
            $rdata['true_ans'] = $correct;
            $rdata['total'] = $total;
            $rdata['false_ans'] = $incorrect;
            $rdata['avg_grade'] = $parcent;
            $rdata['quiz_date'] = date('Y-m-d H:i:s');
            $rdata['timestamp'] = $timestamp;
            $rdata['group_id'] = $session_data[0]['quiz_id'];
            $rdata['session_id'] = $session_id;
            # Save result data
            /* Save result data */
            if (Session::get('timestamp') != 2015) {
                $save_result_id = $this->apObj->saveResults($rdata);
                Session::put('save_result_id', $save_result_id);
                Session::put('timestamp', 2015);
            }
        }

        return View::make('user.quiz-result')
                        ->with('public_user_quiz', $session_data)
                        ->with('result', $rdata)
                        ->with('full_result', $result);
    }

    // Get started quiz
    public function getStartQuiz($quiz_id) {
        Session::regenerate(); // Regenerate session ID
        Session::put('quiz_data', null); // Set Session data null
        $group_id = $quiz_id;
        $group = $this->apObj->getQuizGroupById($group_id);
        if ($group_id == '') {
            return Redirect::to('/')->with('message', ' Please select a quiz group');
        }

        if (empty($group)) {
            return Redirect::to('/')->with('message', ' Please select a quiz group');
        }
        // Load view
        return View::make('user.get-started')->with('quiz', $group)->with('quiz_id', $quiz_id);
    }

    // Guess number
    public function guessNumber() {
        $page_setting = $this->apObj->getPageSetting();
        if (isset($page_setting->guess_number_status) && $page_setting->guess_number_status == 0) {
            return Redirect::to('/');
        }
        $status = 0;
        $random_number = Session::get('number'); // rand(1,10);
        $user_guess = Input::get('guess');  // User Input
        $try = Session::get('try'); // How many times tried
        $tries = 0; // Try reset
        if (isset($try) && $user_guess > 0) {
            $tries = $try + 1;
            Session::set('try', $tries); // Try increment
        } else {
            Session::set('try', 0);
        }
        // Check number
        if ($user_guess > $random_number) {
            $msg = '<b style="font-size:70px">' . $user_guess . '</b> is greater than system number !';
            $status = 2;
        } elseif ($user_guess < $random_number) {
            $msg = '<b style="font-size:70px">' . $user_guess . '</b> is less  than system number !';
            $status = 2;
        } else {
            $msg = 'Perfect guess ! You would be an astrologer ! ';
            $status = 1;
        }
        // Check number
        if (!$user_guess) {
            $msg = '<i class="fa fa-lightbulb-o"></i> Guess a number and enter !';
            $status = 0;
        }
        // Reset guess number and generate number  ;
        if (Input::get('action') == 'reset') {
            // Get guess number from setting
            $guess_number = $this->apObj->getPageSetting();
            $guess_number = $guess_number->guess_number;
            $guess_number = explode(',', $guess_number);
            // Number start
            $guess_start = isset($guess_number[0]) ? $guess_number[0] : 0;
            // Number end
            $guess_end = isset($guess_number[1]) ? $guess_number[1] : 0;
            // Random number range start end end
            $random_number = rand($guess_start, $guess_end);
            // Put number into session
            Session::put('number', $random_number);
            // ReSet Session number
            Session::set('try', 0);

            return Redirect::to('/guess-number');
        }

        return View::make('user.guess-number')
                        ->with('tries', $tries)
                        ->with('msg', $msg)->with('status', $status);
    }

    # Email send

    public function sendEmail($data) {
        $email_config = $this->common->loadEmailConfiguration();

        try {
            $info = array('host' => $email_config->smtp_address,
                'driver' => $email_config->driver,
                'port' => $email_config->port,
                'from' => array('address' => $email_config->sender_email,
                    'name' => $email_config->sender_name,),
                'username' => $email_config->email_address,
                'password' => $email_config->password,
                'encryption' => 'tls', 'sendmail' => '/usr/sbin/sendmail -bs', 'pretend' => false,);

            Config::set('mail', $info);

            //Util::printArr(  Config::get('mail') ); exit ;
            //$data = array('to'=>'hmarifur@gmail.com','name'=>'Arifur','subject'=>'') ;
            $text = '';
            $load_email_template = $this->common->loadEmailConfiguration();
            $data['body'] = '';
            if (isset($load_email_template->signup_text)) {
                // Replace text
                $data['body'] = str_replace('{name}', $data['name'], $load_email_template->signup_text);
                $data['body'] = str_replace('{url}', url(), $data['body']);
            }

            Mail::send('emails.sign-up', $data, function ($m) use ($data) {
                $m->to($data['to'], $data['heading'])->subject($data['subject']);
            });
        } catch (Exception $e) {
            //  echo $e->getMessage();
        }
    }

}
