<?php

/* *
 * Vinnorokom Facebook Quiz App V.2.1.3
 * Admin controller
 */

class AdminController extends BaseController {
    /* --------------------
     * Private variables
      -------------------- */

    private $apObj;
    private $poll;
    private $common;
    private $upload;

    /*
     *  Construct  Quiz model
     *  Load classes and set to private variables
     */

    public function __construct() {
        $this->apObj = new Quiz();
        $this->poll = new Poll();
        $this->common = new Common();
        $this->upload = new Upload();
    }

    /* Dashboard
     * @return $dashboard_data to view
     *  */

    public function dashboard() {
        $group_id = Input::get('group');
        $today = date('Y-m-d');
        $graph_date = Input::get('graph_date');
        if ($graph_date) {
            $today = $graph_date;
        }
        $dashboard_data = $this->apObj->dashBoard();
        $recent_data = $this->apObj->getRecentQuiz($group_id);
        $graph_data = $this->apObj->dailyQuizGraph($today);
        $hr = array();
        $count = array();

        foreach ($graph_data as $i) {
            $hr[] = $i->h;
            $count[] = $i->cnt;
        }

        $hours = json_encode($hr); // Graph hours
        $count = json_encode($count); // Graph count per hour
        $group_list = $this->apObj->getActiveQuizGroup();

        return View::make('admin.dashboard')->with('dashboard_data', $dashboard_data)
                        ->with('recent_data', $recent_data)
                        ->with('group_list', $group_list)->with('hours', $hours)
                        ->with('count', $count)
                        ->with('graph_date', $today)->with('active', 1);
    }

    /* Manage quiz
     * @return $get_quiz_group
     * @return $quizList
     */

    public function manageQuiz() {
        $group_id = Input::get('group_id');
        $get_quiz_group = $this->apObj->getAllQuizGroup();
        $quizList = $this->apObj->getAllQuizList($group_id);

        return View::make('admin.manage-quiz')->with('quiz_list', $quizList)->with('quiz_group', $get_quiz_group)->with('active', 3);
    }

    /*
     * Add new Quiz
     *
     */

    public function addNewQuiz() {
        $data = Input::except('_token');

        // Demo
        // return json_encode(array('success' => 0, 'msg' => 'This is not possible for demo mode !')); // Failed
        $quiz['text'] = $data['quiz'];
        $quiz['group_id'] = $data['quiz_group'];
        $quiz_id = DB::table('user_quiz')->insertGetId($quiz); // Insert quiz and get quiz id
        $option['qtext'] = $data['option_text'];
        $option['qid'] = $quiz_id;
        $ans_id = 0;
        for ($k = 0; $k < count($data['option_text']); ++$k) {
            if ($k != $data['addoptn']) {
                $qoptn = array('qtext' => $data['option_text'][$k], 'qid' => $quiz_id);
                $this->apObj->insertQuizOptionGetId($qoptn);
            } else {
                $idata = array('qtext' => $data['option_text'][$k], 'qid' => $quiz_id);
                $ans_id = $this->apObj->insertQuizOptionGetId($idata);
            }
        }
        if ($this->apObj->updateQuizById($quiz_id, $ans_id)) {
            return json_encode(array('success' => 1, 'msg' => '<i class="fa fa-check"></i> Question added successfully!')); // Success
        } else {
            return json_encode(array('success' => 0, 'msg' => 'Failed!')); // Failed
        }
    }

    /* Quiz insert update delete */

    public function login() {
        return View::make('admin.login');
    }

    // User logout
    public function logout() {
        Auth::logout();
        Session::flush();

        return Redirect::to('/admin-login');
    }

    /*
     * Admin login check
     * @return array success = 1
     */

    public function adminLogin() {
        $user = Input::get('username');
        $password = Input::get('password');
        if (Auth::attempt(array('email' => $user, 'password' => $password, 'user_level' => 1), true)) {
            return array('success' => 1);  // Success
        } else {
            return array('success' => 0); // Failed
        }
    }

    /*
     *  Delete quiz
     *  @return array success = 1
     */

    public function quizDelete() {
        if ($this->apObj->quizDelete(Input::get('q_id'))) {
            return array('success' => 1, 'msg' => '<i class="fa fa-check"></i> Question deleted successfully!');   // Success
        } else {
            return array('success' => 0, 'msg' => '<i class="fa fa-times"></i> Failed!'); // Failed
        }
    }

    /*
     *  Edit quiz
     *  @param @quiz_id
     *  @return $get_quiz_option
     *  @return $get_quiz
     */

    public function editQuiz($quiz_id) {
        $get_quiz_option = $this->apObj->getOptionListById($quiz_id);
        $get_quiz_group = $this->apObj->getAllQuizGroup();
        $get_quiz = $this->apObj->getQuizListById($quiz_id);

        return View::make('admin.edit-quiz')
                        ->with('quiz_id', $quiz_id)
                        ->with('quiz', $get_quiz)
                        ->with('quiz_group', $get_quiz_group)
                        ->with('quiz_option', $get_quiz_option);
    }

    /*
     * Update Quiz
     * @return  status array()
     */

    public function updateQuiz() {
        //return array('success' => 0, 'msg' => 'This is not possible for demo mode !'); // Failed
        $input = Input::except('_token');
        if ($input['quiz_group'] == 0) {
            return array('success' => 0, 'msg' => '<span class="text-danger"><i class="fa fa-times"></i> Please select quiz group !</span>');
        }
        $data = $this->apObj->updateQuizOptions($input);
        if ($data) {
            return array('success' => 1, 'msg' => '<i class="fa fa-check"></i> Question updated successfully!'); // Success
        } else {
            return array('success' => 0, 'msg' => '<i class="fa fa-times"></i>  Not updated !'); // Failed
        }
    }

    /*
     *  Add, Update , Delete quiz
     * @return array success = 1
     */

    public function addNewGroup() {
        $groupList = $this->apObj->getQuizGroup();

        return View::make('admin.add-new-group')->with('group_list', $groupList)->with('active', 2);
    }

    /*
     * Add new group
     * @return status array()
     */

    public function postAddNewGroup() {
        // return array('success' => 0, 'msg' => 'This is not possible for demo mode !'); // Failed
        $input = Input::except('_token');
        $data = DB::table('user_quiz_group')->insert($input);
        if ($data) {
            return array('success' => 1); // Success
        } else {
            return array('success' => 0); // Failed
        }
    }

    /*
     * Delete group name
     *
     */

    public function deleteGroupName() {
        //return array('success' => 0, 'msg' => 'This is not possible for demo mode !'); // Failed
        $input = Input::get('g_id');
        $this->apObj->deleteGroupName($input);

        return array('success' => 1, 'msg' => '<i class="fa fa-check"></i> Group deleted successfully!');
    }

    /*
     * Edit group
     * @param $group_id
     */

    public function editGroup($group_id) {
        $data = $this->apObj->getQuizGroupById($group_id);

        return View::make('admin.edit-group')->with('group', $data);
    }

    /*
     * Update group
     * @return status array()
     */

    public function updateGroup() {
        /// return array('success' =>0, 'msg' => 'This is not possible for demo mode !'); // Failed
        $group = Input::except('_token');
        $status = Input::get('status');
        $is_public = Input::get('is_public');
        $group['status'] = isset($status) ? 1 : 0;
        $group['is_public'] = isset($is_public) ? 1 : 0;
        if ($this->apObj->updateQuizGroup($group)) {
            return array('success' => 1, 'msg' => '<i class="fa fa-check"></i> Group updated successfully!'); // Success
        } else {
            return array('success' => 0, 'msg' => '<i class="fa fa-times"></i>  Not updated !'); // Failed
        }
    }

    /*
     *  Quiz  setting
     *
     */

    public function quizSetting() {
        // Get facebook sharing custom text
        $custom_facebook_text = $this->common->getCustomText();
        // All data from user_quiz_setting table
        $get_quiz_group = $this->apObj->getAllQuizGroup();
        // Get Quiz setting
        $get_setting = $this->apObj->getQuizSetting();
        // Get Quiz schedule list by pagination
        $get_schedule_quiz = $this->apObj->getQuizSchedulePaginate();

        return View::make('admin.quiz-setting')
                        ->with('quiz_group', $get_quiz_group)
                        ->with('setting', $get_setting)
                        ->with('schedule_quiz', $get_schedule_quiz)
                        ->with('custom_facebook_text', $custom_facebook_text)->with('active', 6);
    }

    /*
     * Save quiz setting
     * @input form inputs  $input
     */

    public function saveQuizSetting() {
        //return array('success' =>1, 'msg' => 'This is not possible for demo mode !'); // Failed
        $input = Input::except('_token');
        $from_date = $input['from_date'];
        $to_date = $input['to_date'];
        $datetime1 = new DateTime($from_date);
        $datetime2 = new DateTime($to_date);
        $interval = $datetime1->diff($datetime2); // Get date difference
        $random_options = isset($input['random_options']) ? 1 : 0;

        if ($interval->format('%R%a') < 0) {
            return array('success' => 0, 'msg' => ' Invalid date selection');
        }

        // Update data array
        $data = array('default_group' => $input['quiz_group'],
            'publish_from' => $from_date,
            'publish_to' => $to_date,
            'random_options' => $random_options,);
        if ($this->apObj->updateQuizSetting($data)) {
            return array('success' => 1, 'msg' => ' Successfully saved !');
        } else {
            return array('success' => 0, 'msg' => 'This group has already been scheduled !');
        }
    }

    /*
     * Page setting
     *
     */

    public function pageSetting() {
        $get_page_setting = $this->apObj->getPageSetting(); // Get page default settings
        return View::make('admin.page-setting')->with('setting', $get_page_setting)->with('active', 8);
    }

    /*
     * Save page setting
     * @input get inputs value  $input
     */

    public function savePageSetting() {
        //return array('success' => 0, 'msg' => 'This is not possible for demo mode !'); // Failed
        $input = Input::except('_token');
        // Modal footer image link add
        $ajax_modal = isset($input['add_image_link']) ? $input['add_image_link'] : 0;
        if ($ajax_modal == 1) {
            if ($this->common->addFooterImageLink($input)) {
                echo 'Link added successfully';
                exit;
            } else {
                echo 'Now image found ! Please upload footer Image';
                exit;
            }
        }
        //$upload = new Upload(); // Load Upload class
        $hfile = $_FILES['header_img']; // Image files
        $ffile = $_FILES['footer_img']; // Image files
        $header_img = isset($input['header_img_name']) ? $input['header_img_name'] : '';
        $footer_img = isset($input['footer_img_name']) ? $input['footer_img_name'] : '';
        $validextensions = array('jpeg', 'jpg', 'png'); // Valid image file extention
        $path = 'public/images/';
        /*
         * Method uploadFile
         * @param file
         * @param extension array
         * @param file upload path
         *
         * @return file name
         */
        if (!empty($hfile['name'])) {
            $header_img = $this->upload->uploadFile($hfile, $validextensions, $path); // Upload header file and get file name
        }
        if (!empty($ffile['name'])) {
            $footer_img = $this->upload->uploadFile($ffile, $validextensions, $path); // Upload header file and get file name
        }
        // Update data array
        $data = array('header_image' => $header_img, // Update data array
            'footer_image' => $footer_img,
            'site_name' => $input['site_name'], // Site name
            'site_title' => $input['site_title'], // Site Title
            'welcome_text' => $input['welcome_text'], // Welcome text
            'facebook' => $input['facebook'], // facebook address
            'google' => $input['google'], // Google Address
            'linkedin' => $input['linkedin'], // Linked in address
                //'analytics_code' => $input['analytic_code']
        );

        if ($this->apObj->updatePageSetting($data)) {
            return array('success' => 1, 'msg' => ' Updated successfully! ');
        } else {
            return array('success' => 0, 'msg' => ' Sorry there is problem while updating ! ');
        }
    }

    /*
     *  Get users list
     *
     */

    public function getUsersList() {
        $group_id = Input::get('group_id');
        $users = $this->common->getUsersByGroupId($group_id);

        return View::make('admin.users-list')->with('users', $users)->with('active', 10);
    }

    /*
     * User details by user id
     * @param user fb id
     * @return user quiz result details
     *
     */

    public function getUsersQuizResult($user_id) {
        $data = $this->apObj->getUserResultDataById($user_id);

        return View::make('admin.users-result-list')->with('data', $data)->with('active', 10);
    }

    /*
     *  Block user
     *  @return array success =1
     */

    public function blockUser() {
        //return array('success' =>1, 'msg' => 'This is not possible for demo mode !'); // Failed
        $uid = Input::get('uid');
        if ($this->apObj->blockUser($uid)) {
            return array('success' => 1, 'msg' => ' Updated successfully! ');
        } else {
            return array('success' => 0, 'msg' => ' Sorry there is problem while updating ! ');
        }
    }

    /*
     * Password reset and change
     */

    public function resetPassPage() {
        return View::make('admin.password-reset')->with('active', 0);
    }

    /*
     * Reset password form post
     */

    public function resetPass() {
        //return Redirect::to('/admin/reset-pass')->with('message', '<i class="fa fa-times"></i>This is not possible for demo mode!')->with('class', 'alert-danger');
        $inputs = Input::except('_token');

        if ($inputs['new_password'] != $inputs['again_new_password']) {
            return Redirect::to('/admin/reset-pass')
                            ->with('message', '<i class="fa fa-times"></i> New password verification is not matching ! try again !')->with('class', 'alert-danger');
        }
        $old_pass = Hash::make($inputs['old_password']);
        $user_email = Auth::user()->email;
        $new_pass = Hash::make($inputs['new_password']);

        if (Hash::check($inputs['old_password'], Auth::user()->password)) {
            $userPass = User::where('email', $user_email)->first();
            if ($userPass) {
                DB::table('users')->where('email', $user_email)->update(array('password' => $new_pass));

                return Redirect::to('/admin/reset-pass')->with('message', '<i class="fa fa-check"></i>Password changed successfully!')->with('class', 'alert-success');
            }
        } else {
            return Redirect::to('/admin/reset-pass')
                            ->with('message', '<i class="fa fa-times"></i> Old password not matched!')
                            ->with('class', 'alert-danger');
        }
    }

    /*
     * Export csv file
     */

    public function exportToCsv() {
        //return Redirect::to('/admin')->with('message','This is not possible for demo mode !')->with('class','alert-danger'); // Failed
        $filename = date('YmdHis'); // File name as datetime string

        /* call exportCsvFile  from Util class
         * @param header
         * @param data array
         * @param header exception
         * @param filename
         * @return data csv format
         *
         * * */
        $group_id = Input::get('group_id');
        $headers = array('id', 'fbid', 'name', 'email', 'gender', 'created_at', 'status'); // CSV header
        $user = Util::exportCsvfile($headers, $this->common->userExport($group_id), $exceptions = array());
        /* Content type * */
        $headers = array(
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $filename . '.csv"',
        );

        return Response::make(rtrim($user, "\n"), 200, $headers);
    }

    /* New updated */

    /* Schedule delete */

    public function scheduleDelete() {
        $schdule_id = Input::get('schedule_id');
        $result = $this->apObj->scheduleDelete($schdule_id);
        if ($result) {
            return array('success' => 1, 'msg' => '<i class="fa fa-check"></i> Quiz Schedule deleted successfully ! ');
        } else {
            return array('success' => 0, 'msg' => ' Failed to delete ! ');
        }
    }

    /* Manage poll */

    public function managePolls() {
        $poll = '';
        $poll_potions = '';
        if (Input::get('action') == 'edit') {
            $poll_id = Input::get('poll_id');
            $poll = $this->poll->getOnlyPollTextById($poll_id);
            $poll_potions = $this->poll->getPollOptionsById($poll_id);
        }
        $polls = $this->poll->getPollsWithPagination();

        return View::make('admin.manage-poll')
                        ->with('polls', $polls)
                        ->with('poll', $poll)
                        ->with('poll_options', $poll_potions)->with('active', 4);
    }

    /* Form submit poll save */

    public function savePoll() {
        $inputs = Input::except('_token');
        $poll_data = array();
        $option_data = array();

        $poll_data['is_featured'] = isset($inputs['is_featured']) ? 1 : 0;
        $poll_data['short_code'] = Util::getNonce();
        $poll_data['poll_text'] = $inputs['poll_text'];
        $poll_data['image_path'] = isset($inputs['image_name']) ? $inputs['image_name'] : null;
        if ($inputs['poll_text'] == '') {
            return array('success' => 0, 'msg' => '<i class="fa fa-close"></i> Please enter valid poll!');
        }

        $nextDate = Util::getNextDayDate($inputs['voting_last_date']);
        $poll_data['voting_last_date'] = isset($inputs['voting_last_date']) ? $inputs['voting_last_date'] : $nextDate;
        $option_data = $inputs['option_text'];
        $polls = $this->poll->savePoll($poll_data, $option_data);
        if ($polls) {
            return array('success' => 1, 'msg' => '<i class="fa fa-check"></i> Poll added successfully !');
        } else {
            return array('success' => 0, 'msg' => '<i class="fa fa-close"></i> Can not save poll ');
        }
    }

    /* Media manager page load */

    public function mediaManager() {
        $file_list = $this->common->getAllMediaFilesPagination();

        return View::make('admin.media-manager')->with('files', $file_list)->with('active', 5);
    }

    public function saveMediaFile() {
        $hfile = $_FILES['file']; // Image files
        // $upload = new Upload();
        $path = 'public/media/';
        $file_name = '';
        /*
         * Method uploadFile
         * @param file
         * @param extension array
         * @param file upload path
         *
         * @return file name
         */

        $validextensions = array('jpeg', 'jpg', 'png'); // Valid image file extention
        if (!empty($hfile['name'])) {
            if ($file_name = $this->upload->uploadFile($hfile, $validextensions, $path)) {
                
            } else {
                return array('success' => 0, 'msg' => ' Sorry there is problem while uploading ! ');
            }
        }
        $file_type = $hfile['type'];
        // Update data array
        $data = array('file_name' => $file_name,
            'file_type' => $file_type,
            'uploaded_at' => date('Y-m-d H:i'),
            'uploaded_by' => Auth::user()->id,
        );
        if ($file_name != '' && $this->apObj->uploadMedia($data) === true) {
            return array('success' => 1, 'msg' => ' Upload successfully! ');
        } else {
            return array('success' => 0, 'msg' => ' Sorry there is problem while uploading file ! ');
        }
    }

    /*
     * Delete media file by file name
     * $file_name contains file name
     * unlink php function using for deleting a file
     */

    public function deleteMediaFile() {
        $file_name = Input::get('file_name');
        $path = 'public/media/';
        $d = unlink($path . $file_name);
        if ($d === true && $this->common->deleteFileByFileName($file_name) === true) {
            return array('success' => 1, 'msg' => 'Successfully deleted !');
        } else {
            return array('success' => 0, 'msg' => ' File delete process failed !');
        }
    }

    /*
     * Change poll Status
     * @param poll_id
     * @status
     *
     */

    public function changePollStatus($poll_id, $status) {
        $status = ($status == 1) ? 0 : 1;
        if ($this->poll->changePollStatusById($poll_id, $status)) {
            return Redirect::to('/admin/manage-poll')->with('class', 'alert-success')->with('message', 'Status changed successfully!');
        }
    }

    /*
     * Change Poll Feature
     * @param poll_id
     * @param status
     */

    public function changePollFeature($poll_id, $status) {
        $status = ($status == 1) ? 0 : 1;
        if ($this->poll->changePollFeatureStatusById($poll_id, $status)) {
            return Redirect::to('/admin/manage-poll')->with('class', 'alert-success')->with('message', 'Poll featured status changed successfully!');
        }
    }

    /*
     * Delete a poll by poll_id
     * @param poll_id
     */

    public function deletePoll($poll_id) {
        if ($this->poll->deletePollById($poll_id)) {
            return Redirect::to('/admin/manage-poll')->with('class', 'alert-success')->with('message', 'Poll deleted successfully !');
        }
    }

    /*
     * Load Ajax media files
     *
     */

    public function loadAjaxMediaFiles() {
        $imageData = $this->common->getAllMediaFiles();
        $view = View::make('admin.load-ajax-media-file')->with('files', $imageData);

        return array('success' => 1, 'msg' => $view->render());
    }

    /*
     * Edit poll by Id
     * @param poll_id
     *
     */

    public function editPoll($poll_id) {
        $poll = $this->poll->getOnlyPollTextById($poll_id);
        $poll_potions = $this->poll->getPollOptionsById($poll_id);
        $view = View::make('admin.edit-poll-form')->with('poll', $poll)->with('poll_options', $poll_potions);

        return $view->render();
    }

    /*
     * Update poll
     */

    public function updatePoll() {
        $inputs = Input::except('_token');
        $poll = array();
        $poll_id = $inputs['poll_id'];
        $poll['poll_text'] = $inputs['poll_text'];
        $poll['image_path'] = $inputs['image_name'];
        //$poll['is_featured'] = isset($inputs['is_featured']) ? $inputs['is_featured'] : 0;
        $poll['voting_last_date'] = $inputs['voting_last_date'];

        $this->poll->updatePollById($poll_id, $poll);

        if (!isset($inputs['option_text'])) {
            return Redirect::to('/admin/manage-poll?poll_id=' . $poll_id . '&action=edit')->with('message', 'You should have at least poll options! ')->with('class', 'alert-danger');
        }

        $option_text = $inputs['option_text'];

        $poll_opt_array = array(); // Poll Option Array
        $new_opt_array = array(); // New Option Array
        $new_opt_id_array = array(); // New option ID Array
        $get_options_by_id = $this->poll->getPollOptionsById($poll_id);
        foreach ($get_options_by_id as $opid) {
            $poll_opt_array[] = $opid->poll_option_id; // Put all poll option id in a array
        }
        $poll_opt_text = array();
        $poll_option_insert_data = array();
        foreach ($option_text as $opt => $key) {
            if (in_array($opt, $poll_opt_array)) { // Check If user remove poll option
                $poll_opt_text['poll_option_text'] = $key;
                $this->poll->updatePollOptionsById($opt, $poll_opt_text); // If existing id match poll option will be update
            } else {
                $poll_option_insert_data['poll_id'] = $poll_id;
                $poll_option_insert_data['poll_option_text'] = $key;
                $this->poll->saveNewPollOption($poll_option_insert_data);
                // $this->poll->deletePollOptionById($opt); // If not match
            }
            $new_opt_id_array[] = $opt;
        }
        foreach ($get_options_by_id as $o) {
            if (in_array($o->poll_option_id, $new_opt_id_array)) {
                
            } else {
                $this->poll->deletePollOptionById($o->poll_option_id);
            }
        }

        return Redirect::to('/admin/manage-poll?poll_id=' . $poll_id . '&action=edit')->with('message', 'Poll Updated successfully ! ')->with('class', 'alert-success');
    }

    /*
     * Home page slider image upload
     *
     */

    public function homePageSliderUpload() {
        $inputs = Input::except('_token');
        $slider_img = isset($inputs['image_name']) ? $inputs['image_name'] : 0;
        $home_page_slider = isset($inputs['home_page_slider']) ? $inputs['home_page_slider'] : 0;
        if ($home_page_slider == 0) {
            return Redirect::to('/admin/page-setting')->with('class', 'alert-danger')->with('message', ' Slider image change failed !');
        }
        array_push($home_page_slider, $slider_img);
        $sliderData = array('home_page_slider' => serialize($home_page_slider));
        $this->common->updateSlider($sliderData);

        return Redirect::to('/admin/page-setting')->with('class', 'alert-success')->with('message', 'Slider image added successfully !');
    }

    /*
     * Manage page
     */

    public function managePages() {
        // Ajax Load Parent menu
        $page_type = array(1 => 'Page', 2 => 'Blog');

        if (Input::get('sub_menu') == 2) {
            $pages = $this->common->loadParentPages();
            $html = '';
            $html .= '<label>Submenu Page</label> <select name="parent_id" class="form-control input-sm">';
            foreach ($pages as $p) {
                $html .= '<option value="' . $p->page_id . '">' . $p->page_name . '</option>';
            }
            $html .= '</select>';
            echo $html;
            exit;
        }

        // If url get page then new page
        $publish = Input::get('publish');
        if ($publish == 'yes') {
            $page_id = Input::get('page_id');
            $page_data = $this->common->chagePageStatus($page_id);

            return Redirect::to('/admin/manage-pages');
        }

        // If user get page id  edit mode
        if (Input::get('page_id')) {
            $page_data = $this->common->loadPageById(Input::get('page_id'));

            return View::make('admin.manage-pages')->with('page_data', $page_data)->with('active', 7);
        }

        // If url get page then new page
        if (Input::get('page') == 'new') {
            return View::make('admin.manage-pages')->with('active', 7);
        }

        $page_list = $this->common->allPageList();

        return View::make('admin.pages-list')->with('all_pages', $page_list)->with('page_type', $page_type)->with('active', 7);
    }

    /*
     *   Add or Create new page form post
     */

    public function addNewPage() {
        $inputs = Input::except('_token');
        $inputs['slug'] = Util::toAscii($inputs['page_name']);

        // Update page data
        $page_id = isset($inputs['page_id']) ? $inputs['page_id'] : 0;
        if ($page_id > 0) {
            DB::table('user_pages')->where('page_id', $page_id)->update($inputs);

            return Redirect::to("/admin/manage-pages?page_id=$page_id");
        }
        // Inset New page data

        $inputs['created_at'] = date('Y-m-d');
        $page_id = DB::table('user_pages')->insertGetId($inputs);

        return Redirect::to("/admin/manage-pages?page_id=$page_id");
    }

    /* /*
     *  Page delete
     */

    // @param page_id
    public function deletePage($page_id) {
        if ($this->common->deletePage($page_id)) {
            return array('success' => 1, 'msg' => 'Successfully page deleted !');
        } else {
            return array('success' => 0, 'msg' => ' Failed to delete page !');
        }
    }

    /* /*
     *  Facebook custome share text and details text
     */

    public function saveCustomText() {
        $inputs = Input::except('_token');
        if ($this->common->saveCustomText($inputs)) {
            return array('success' => 1, 'msg' => 'Saved successfully ! ');
        } else {
            return array('success' => 10, 'msg' => 'Save failed  ! ');
        }
    }

    /*
     * Update analytics code
     */

    public function updateAnalytics() {
        return View::make('admin.analytics-code')->with('active', 9);
    }

    /*
     * Save analytics code
     */

    public function saveAnalytics() {
        $data = array();
        $inputs = Input::except('_token');
        $data['page_id'] = isset($inputs['page_id']) ? $inputs['page_id'] : 0;
        $data['analytics_code'] = isset($inputs['analytics_code']) ? $inputs['analytics_code'] : '';
        $this->common->updateAnalyticsCode($data);

        return Redirect::to('/admin/analytics-code')->with('class', 'alert-success')->with('message', 'Analytics code updated successfully');
    }

    /*
     * Guess a number setting
     */

    public function guessNumberSetting() {
        if (Input::get('action') == 'guess_number_status') {
            return $this->toggleOnOff();
        }

        return View::make('admin.guess-number-setting')->with('active', 11);
    }

    /* Guess number setting */

    public function saveNumberSetting() {
        $input = Input::all();
        $number = $input['start'] . ',' . $input['end'];

        $data['guess_number'] = $number;

        if ($this->common->updateGuessNumber($data)) {
            return Redirect::to('/admin/guess-number-setting')->with('msg', 'Updated successfully ! ')->with('class', 'alert-success');
        } else {
            return Redirect::to('/admin/guess-number-setting')->with('msg', 'Updated failed ! ')->with('class', 'alert-danger');
        }
    }

    /* Email config settings */

    public function emailSetting() {
        # Load information
        $info = $this->common->loadEmailConfiguration();

        return View::make('admin.email-setting')->with('active', 12)->with('info', $info);
    }

    /* Email Config save */

    public function emailConfigSetting() {
        $input = Input::all();
        $input['sender_email'] = $input['email_address'];

        if ($this->common->updateEmail($input)) {
            return Redirect::to('/admin/email-setting')->with('msg', 'Configuration saved successfully ! ')->with('class', 'alert-success');
        } else {
            return Redirect::to('/admin/email-setting')->with('msg', 'Cofiguration save failed  ! ')->with('class', 'alert-danger');
        }
    }

    /* Guess number toggle on/off */

    public function toggleOnOff() {
        return array('status' => $this->common->guessNumberStatus());
    }

    /* Email Sign up text */

    public function signUptextUpdate() {
        $input = Input::all();
        if ($this->common->updateEmail($input)) {
            return Redirect::to('/admin/email-setting')->with('msg', 'Successfully updated!')->with('class', 'alert-success');
        } else {
            return Redirect::to('/admin/email-setting')->with('msg', 'Update failed !')->with('class', 'alert-danger');
        }
    }

}
