<?php

require_once('config.php');

check_user();

$action = '';

$result = array();
if(isset($_REQUEST['action_function'])){
    $action = $_REQUEST['action_function'];
}

if($action == 'new_user'){
    if(!check_admin()){
        $result['status'] = 0;
        echo json_encode($result);
        die();
    }

    $user_data['title']     = "Add User";
    $user_data['uid']       = base64_encode(0);
    $result['html']         = load_view('templates/set_user.php',$user_data);
    $result['status']       = 1;
}

if($action == 'edit_user'){
    if(!check_admin() || empty($_POST['uid'])){
        $result['status'] = 0;
        echo json_encode($result);
        die();
    }

    $user_id = base64_decode($_POST['uid']);

    require_once('classes/user.php');
    $user_class = new User();

    $user_data              = $user_class->getUserSettings($user_id);
    $result['tmp'] = $user_data;
    $user_data['title']     = "Edit User";
    $user_data['uid']       = base64_encode($user_id);
    $result['html']         = load_view('templates/set_user.php',$user_data);
    $result['status']       = 1;
}

if($action == 'delete_user'){
    $user_id = base64_decode($_POST['uid']);

    if(!check_admin()){
        $result['status'] = 0;
        echo json_encode($result);
        die();
    }

    require_once('classes/user.php');
    $user_class = new User();

    if(DEMO_VERSION && $user_class->is_admin() < 2)
    {
        $result['message'] = DEMO_ERROR;
        $result['status'] = 2;

        echo json_encode($result);
        die();
    }

    if($user_id == $user_class->userid()){
        $result['message'] = "You can not delete yourself.";
        $result['status'] = 2;
    }else{
        $user_class->delete_user($user_id);
        $result['status'] = 1;
    }
}

if($action == 'change_user_status')
{
    $user_id = base64_decode($_POST['uid']);

    if(!check_admin()){
        $result['status'] = 0;
        echo json_encode($result);
        die();
    }

    require_once('classes/user.php');
    $user_class = new User();

    if(DEMO_VERSION && $user_class->is_admin() < 2)
    {
        $result['message'] = DEMO_ERROR;
        $result['status'] = 2;

        echo json_encode($result);
        die();
    }

    if($user_id == $user_class->userid()){
        $result['message'] = "You can not change your status.";
        $result['status'] = 2;
    }else{
        $user_class->change_status($user_id);
        $result['status'] = 1;
    }

}

if($action == 'save_user'){
    $user_id = base64_decode($_POST['uid']);

    if(!check_admin()){
        $result['status'] = 0;
        echo json_encode($result);
        die();
    }

    require_once('classes/user.php');
    $user_class = new User();

    $username   = empty($_POST['username']) ? '' : $_POST['username'];
    $email      = empty($_POST['email']) ? '' : $_POST['email'];
    $is_admin   = empty($_POST['usertype']) ? 0 : (int)$_POST['usertype'];
    $password   = empty($_POST['password']) ? '' : $_POST['password'];
    $rpassword  = empty($_POST['rpassword']) ? '' : $_POST['rpassword'];
    $fb_app     = empty($_POST['fb_app']) ? 0 : (int)$_POST['fb_app'];
    $fb_pages   = empty($_POST['fb_pages']) ? 0 : (int)$_POST['fb_pages'];
    $status     = empty($_POST['status']) ? 0 : 1;

    $error = 0;

    if($username == ''){
        $error = 1;
        $message = "Field name is required.";
    }

    if($email == '' && $error == 0){
        $error = 1;
        $message = "Field email is required.";
    }

    if($error == 0 && !FILTER_VAR($email, FILTER_VALIDATE_EMAIL)){
        $error = 1;
        $message = "E-mail is not valid";
    }

    if($error == 0 && !$user_class->check_email($email,true,$user_id)){
        $error = 1;
        $message = "E-mail already in use.";
    }

    if($password == '' && $error == 0 && $user_id == 0){
        $error = 1;
        $message = "Password is empty.";
    }

    if($password != $rpassword && $error == 0 && $user_id == 0){
        $error = 1;
        $message = "Passwords mismatch.";
    }

    if($error == 0 && $user_id != 0 && ($password != '' || $rpassword != '')){
        if($password != $rpassword){
            $error = 1;
            $message = "Passwords mismatch.";
        }
    }

    if($error == 0){
        $user_data['name']              = $username;
        $user_data['email']             = $email;
        $user_data['is_admin']          = $is_admin;
        $user_data['allow_fb_app']      = $fb_app;
        $user_data['fb_pages_limit']    = $fb_pages;
        $user_data['status']            = $status;
        if($user_id == 0){
            $user_data['password']      = sha1($password);
        }elseif($password != ''){
            $user_data['password']      = sha1($password);
        }

        $user_class->set_user($user_data, $user_id);

        $result['status'] = 1;
    }else{
        $result['status']   = 2;
        $result['message']  = $message;
    }

}

if($action == 'get_posts'){
    $pages = array();
    if(!empty($_POST['pages'])) $pages = $_POST['pages'];

    require_once('classes/user.php');
    require_once('classes/fb.php');
    $user_class = new User();
    $fb_class = new Facebook();
    $user = $user_class->get_user();

    $posts_res = array();
    if(!empty($pages))
        foreach($pages as $page_id) {
            $posts = $fb_class->getPagePosts($page_id, $user['fb_token']);
            if(!empty($posts))
                foreach($posts as $post){
                    $tmp = array();
                    $tmp['id']          = $post->id;

                    $link = explode('_',$post->id);

                    $tmp['link'] = 'https://www.facebook.com/' . (!empty($link[0]) ? $link[0] : "") . '/posts/' . (!empty($link[1]) ? $link[1] : "");

                    if(!empty($post->message))
                        $tmp['message']     = $post->message;
                    elseif(!empty($post->story))
                        $tmp['message']     = $post->story;
                    else
                        $tmp['message']     = "";

                    if(isset($post->picture))
                        $tmp['picture']     = $post->picture;
                    else
                        $tmp['picture']     = "https://graph.facebook.com/"  .$post->id. "/picture";

                    $tmp['from']            = !empty($post->from->name) ? $post->from->name : "";

                    $posts_res[] = $tmp;
                }
        }

    $result = "";

    if(!empty($posts_res))
        foreach($posts_res as $post){
            $result .= '<div class="col-sm-6">
                                <div class="selectBox post-box">
                                        <input type="checkbox" class="checkbox" name="posts[]" value="'.$post['id'].'" />
                                        <a href="#" class="img"><img style="width: 100%; height: 100%;" src="'.$post['picture'].'" alt=""></a>
                                        <div class="details">
                                            <span>by: ' . $post['from'] . '</span><br>
                                            <a href="'.$post['link'].'" target="_blank" title="'.$post['message'].'">'.strlenchar($post['message'], 80).'</a>
                                        </div>
                                </div>
                            </div>';
        }

    echo $result;
    die();
}

if($action == 'delete_schedule'){
    $sid = empty($_POST['sid']) ? 0 : $_POST['sid'];
    $sid = base64_decode($sid);

    require_once('classes/schedules.php');
    require_once('classes/user.php');

    $user_class = new User();

    if(DEMO_VERSION && $user_class->is_admin() < 2){
        echo json_encode(array('status' => 2, 'message' => DEMO_ERROR));
        die();
    }

    $user = $user_class->get_user();
    $schedule_class = new Schedules($user);

    if($schedule_class->delete_schedule($sid))
        echo json_encode(array('status' => 1));
    else
        echo json_encode(array('status' => 2, 'message' => 'You can not delete this schedule. Access denied.'));

    die();
}

if($action == 'edit_schedule')
{
    $sid = empty($_POST['sid']) ? 0 : $_POST['sid'];
    $sid = base64_decode($sid);

    require_once('classes/schedules.php');
    require_once('classes/user.php');

    $user_class = new User();
    $user = $user_class->get_user();
    $schedule_class = new Schedules($user);

    $schedule = $schedule_class->get_schedule($sid);
    if(!$schedule){
        echo json_encode(array('status' => 2, 'message' => 'You can not edit this schedule. Access denied.'));
        die();
    }

    if(isset($_SESSION['new_data'])){
        unset($_SESSION['new_data']);
    }

    $new_data['step0']                      = $schedule['source_type'];
    $new_data['step1']['pages']             = json_decode(html_entity_decode($schedule['pages']));
    $new_data['step2']['condition_type']    = $schedule['condition_type'];
    $new_data['step2']['posts']             = json_decode(html_entity_decode($schedule['posts']));
    $new_data['step3']['add_condition']     = $schedule['add_condition'];
    $new_data['edit_id']                    = $sid;

    $_SESSION['new_data'] = $new_data;

    echo json_encode(array('status' => 1, 'url' => baseUrl('dashboard.php')));
    die();
}

if($action == 'delete_page'){
    $sid = empty($_POST['sid']) ? 0 : (int)$_POST['sid'];
    $pid = empty($_POST['pid']) ? 0 : $_POST['pid'];

    require_once('classes/schedules.php');
    require_once('classes/user.php');

    $user_class = new User();
    $user = $user_class->get_user();
    $schedule_class = new Schedules($user);

    if($schedule_class->delete_page($sid,$pid))
        echo json_encode(array('status' => 1));
    else
        echo json_encode(array('status' => 0));

    die();
}

if($action == 'change_comment')
{
    $sid = isset($_POST['sid']) ? (int)$_POST['sid'] : 0;
    if($sid == 0) {
        echo json_encode(array('status' => 0));
        die();
    }

    require_once('classes/schedules.php');
    require_once('classes/user.php');

    $user_class = new User();
    $user = $user_class->get_user();
    $schedule_class = new Schedules($user);

    $schedule = $schedule_class->get_schedule($sid);
    if(!$schedule) {
        echo json_encode(array('status' => 0));
        die();
    }

    $data['title']      = "Edit Comment";
    $data['comment']    = $schedule['comment'];
    $data['id']         = $sid;
    $result['html']     = load_view('templates/re_comment.php',$data);
    $result['status']   = 1;
}

if($action == 'save_new_comment')
{
    $sid = isset($_POST['sid']) ? (int)$_POST['sid'] : 0;
    $comment = isset($_POST['comment']) ? $_POST['comment'] : '';

    if($sid == 0){
        echo json_encode(array('status' => 2, 'error' => "Scheduler not found."));
        die();
    }

    if($comment == ""){
        echo json_encode(array('status' => 2, 'error' => "Comment can not be empty."));
        die();
    }

    require_once('classes/schedules.php');
    require_once('classes/user.php');

    $user_class = new User();
    $user = $user_class->get_user();
    $schedule_class = new Schedules($user);

    if(!$schedule_class->update_schedule($sid,array('comment' => $comment))){
        echo json_encode(array('status' => 2, 'error' => "Scheduler not found."));
        die();
    }

    echo json_encode(array('status' => 1));
    die();
}

if($action == 'next_step0')
{
    $post_type = empty($_POST['post_type']) ? 0 : (int)$_POST['post_type'];

    if(isset($_SESSION['new_data'])){
        unset($_SESSION['new_data']);
    }

    if($post_type != 1 && $post_type != 2){
        echo json_encode(array('status' => 2, 'message' => 'Please, select where do you want to schedule comment.'));
        die();
    }

    $new_data['step0']      = $post_type;
    $_SESSION['new_data']   = $new_data;

    $result['status'] = 1;
}

if($action == 'next_step1')
{
    $pages = empty($_POST['pages']) ? array() : $_POST['pages'];
    if(count($pages) == 0){
        echo json_encode(array('status' => 2, 'message' => 'Select Fan Page.'));
        die();
    }

    require_once('classes/user.php');

    $user_class = new User();
    $user = $user_class->get_user();

    if(count($pages) > $user['fb_pages_limit']){
        $p = 'page';
        if($user['fb_pages_limit'] > 0)
            $p = 'pages';
        echo json_encode(array('status' => 2, 'message' => 'You can select maximum '.$user['fb_pages_limit'].' '.$p.'.'));
        die();
    }

    if(!isset($_SESSION['new_data'])){
        echo json_encode(array('status' => 1));
        die();
    }

    $new_data = $_SESSION['new_data'];

    $new_data['step1']['pages'] = $pages;
    $_SESSION['new_data'] = $new_data;

    echo json_encode(array('status' => 1));
    die();
}

if($action == 'next_step2')
{
    $condition_type = empty($_POST['condition']) ? 0 : (int)$_POST['condition'];
    if($condition_type < 1 || $condition_type > 3){
        echo json_encode(array('status' => 2, 'message' => 'Select Condition.'));
        die();
    }

    if(!isset($_SESSION['new_data'])){
        echo json_encode(array('status' => 1));
        die();
    }

    $new_data = $_SESSION['new_data'];
    $new_data['step2']['condition_type'] = $condition_type;

    $_SESSION['new_data'] = $new_data;

    echo json_encode(array('status' => 1));
    die();
}

if($action == 'next_step3')
{
    $add_condition = empty($_POST['add_condition']) ? 0 : (int)$_POST['add_condition'];
    if($add_condition < 1 || $add_condition > 2){
        echo json_encode(array('status' => 2, 'message' => 'Select Additional Option.'));
        die();
    }

    if(!isset($_SESSION['new_data'])){
        echo json_encode(array('status' => 1));
        die();
    }

    $new_data = $_SESSION['new_data'];
    $new_data['step3']['add_condition'] = $add_condition;

    $_SESSION['new_data'] = $new_data;

    echo json_encode(array('status' => 1));
    die();
}

if($action == 'next_step31')
{
    $posts = empty($_POST['posts']) ? array() : $_POST['posts'];

    if(!isset($_SESSION['new_data'])){
        echo json_encode(array('status' => 1));
        die();
    }

    if(count($posts) == 0){
        echo json_encode(array('status' => 2, 'message' => 'Select Posts.'));
        die();
    }

    $new_data = $_SESSION['new_data'];
    $new_data['step2']['posts'] = $posts;

    $_SESSION['new_data'] = $new_data;

    echo json_encode(array('status' => 1));
    die();
}

if($action == 'next_step4')
{
    $keyword = empty($_POST['keyword']) ? '' : $_POST['keyword'];
    $comment = empty($_POST['comment']) ? '' : $_POST['comment'];

    if(!isset($_SESSION['new_data'])){
        echo json_encode(array('status' => 1));
        die();
    }

    $new_data = $_SESSION['new_data'];

    $condition      = empty($new_data['step2']['condition_type']) ? 0 : $new_data['step2']['condition_type'];
    $add_condition  = empty($new_data['step3']['add_condition']) ? 0 : $new_data['step3']['add_condition'];

    if(trim($keyword) == '' && ($condition == 3 || $add_condition == 2)){
        echo json_encode(array('status' => 2, 'message' => 'Enter keyword.'));
        die();
    }

    if(trim($comment) == ''){
        echo json_encode(array('status' => 2, 'message' => 'Enter comment.'));
        die();
    }


    $new_data['step4']['keyword'] = $keyword;
    $new_data['step4']['comment'] = $comment;

    if($condition == 3){
        $new_data['step3'] = array();
    }

    $_SESSION['new_data'] = $new_data;

    echo json_encode(array('status' => 1));
    die();
}

if($action == 'next_step5')
{
    if(!isset($_SESSION['new_data'])){
        echo json_encode(array('status' => 1));
        die();
    }

    require_once('classes/user.php');
    require_once('classes/schedules.php');

    $user_class = new User();
    $user = $user_class->get_user();
    $schedule_class = new Schedules($user);

    if(DEMO_VERSION && $user_class->is_admin() < 2){
        echo json_encode(array('status' => 2, 'message' => DEMO_ERROR));
        die();
    }

    $new_data = $_SESSION['new_data'];

    $data['datefrom']           = empty($_POST['datefrom']) ? '' : $_POST['datefrom'];
    $data['timefrom']           = empty($_POST['timefrom']) ? '' : $_POST['timefrom'];
    $data['is_repeat']          = empty($_POST['is_repeat']) ? 0 : $_POST['is_repeat'];
    $data['is_auto_delete']     = empty($_POST['auto_delete']) ? 0 : $_POST['auto_delete'];
    $data['until_date']         = empty($_POST['untildate']) ? '' : $_POST['untildate'];
    $data['until_time']         = empty($_POST['untiltime']) ? '' : $_POST['untiltime'];
    $data['delete_date']        = empty($_POST['deletedate']) ? '' : $_POST['deletedate'];
    $data['delete_time']        = empty($_POST['deletetime']) ? '' : $_POST['deletetime'];
    $data['repeat_interval']    = empty($_POST['repeat_delay']) ? 0 : $_POST['repeat_delay'];
    $data['delete_interval']    = empty($_POST['delete_delay']) ? 0 : $_POST['delete_delay'];
    $data['repeat_frequency']   = empty($_POST['repeat_type']) ? 0 : $_POST['repeat_type'];
    $data['delete_type']        = empty($_POST['delete_type']) ? 0 : $_POST['delete_type'];
    $data['frequency_weekly']   = empty($_POST['weekdays']) ? array() : $_POST['weekdays'];

    if($data['repeat_frequency'] == 3 && count($data['frequency_weekly']) == 0){
        echo json_encode(array('status' => 2, 'message' => 'Choose weekdays.'));
        die();
    }

    $data['source_type']        = $new_data['step0'];
    $data['pages']              = $new_data['step1']['pages'];
    $data['condition_type']     = empty($new_data['step2']['condition_type']) ? 0 : $new_data['step2']['condition_type'];
    $data['posts']              = empty($new_data['step2']['posts']) ? array() : $new_data['step2']['posts'];
    $data['keyword']            = empty($new_data['step4']['keyword']) ? '' : $new_data['step4']['keyword'];
    $data['add_condition_type'] = empty($new_data['step3']['add_condition']) ? 0 : $new_data['step3']['add_condition'];
    $data['comment']            = empty($new_data['step4']['comment']) ? '' : $new_data['step4']['comment'];

    $sid = 0;
    if(!empty($new_data['edit_id'])){
        if($schedule_class->get_schedule($new_data['edit_id'])){
            $sid = $new_data['edit_id'];
        }
    }

    $result = $schedule_class->add($data,$user['fb_user_name'],$user['fb_token'], $sid);

    if(isset($result['success']) && $result['success']){
        unset($_SESSION['new_data']);
        echo json_encode(array('status' => 1, 'url' => baseUrl('schedule.php')));
        die();
    }else{
        echo json_encode(array('status' => 2, 'message' => $result['errors']));
        die();
    }
}

if($action == 'load_more_posts')
{
    $offset = empty($_POST['offset']) ? 0 : (int)$_POST['offset'];
    if(!isset($_SESSION['new_data'])){
        echo json_encode(array('status' => 2));
        die();
    }

    $new_data = $_SESSION['new_data'];

    if(!isset($new_data['step1']['pages'])){
        echo json_encode(array('status' => 2));
        die();
    }

    $pages = $new_data['step1']['pages'];
    if(empty($pages)){
        echo json_encode(array('status' => 2));
        die();
    }

    require_once('classes/user.php');
    require_once('classes/fb.php');
    $user_class = new User();
    $fb         = new Facebook();
    $user       = $user_class->get_user();

    $all_posts = empty($_SESSION['new_data']['all_posts']) ? array() : $_SESSION['new_data']['all_posts'];
    $posts_res = array();
    $offset += LOAD_POSTS;
    $only_owners = $new_data['step0'] == 1;

    foreach($pages as $page_id){
        $posts = $fb->getObjectPosts($page_id, $user['fb_token'], $offset, $only_owners, true, true);
        if(!empty($posts))
            foreach($posts as $post){
                if(in_array($post->id, $all_posts)) continue;

                $tmp = array();
                $tmp['id']          = $post->id;

                $link = explode('_',$post->id);

                $tmp['link'] = 'https://www.facebook.com/' . (!empty($link[0]) ? $link[0] : "") . '/posts/' . (!empty($link[1]) ? $link[1] : "");

                if(!empty($post->message))
                    $tmp['message']     = $post->message;
                elseif(!empty($post->story))
                    $tmp['message']     = $post->story;
                else
                    $tmp['message']     = "";

                if(isset($post->picture))
                    $tmp['picture']     = $post->picture;
                else
                    $tmp['picture']     = "https://graph.facebook.com/"  .$post->id. "/picture";

                $tmp['from']            = !empty($post->from->name) ? $post->from->name : "";

                if(!empty($post->comments->summary)){
                    $tmp['comments'] = $post->comments->summary->total_count;
                }else{
                    $tmp['comments'] = 0;
                }

                if(!empty($post->likes->summary)){
                    $tmp['likes'] = $post->likes->summary->total_count;
                }else{
                    $tmp['likes'] = 0;
                }

                /*
                $comments_count     = $fb->get_object_comments_info($post->id, $user['fb_token']);
                $likes_count        = $fb->get_object_likes_info($post->id, $user['fb_token']);
                $tmp['comments']    = empty($comments_count->summary->total_count) ? 0 : $comments_count->summary->total_count;
                $tmp['likes']       = empty($likes_count->summary->total_count) ? 0 : $likes_count->summary->total_count;
                */

                $tmp['created']     = empty($post->created_time) ? '' : $post->created_time;

                $posts_res[] = $tmp;
                $all_posts[] = $post->id;
                if(count($posts_res) >= LOAD_POSTS) break;
            }
    }

    $status = (count($posts_res) == 0) ? 2 : 1;
    $_SESSION['new_data']['all_posts'] = $all_posts;
    $pages_posts = $posts_res;

    $html = load_view('templates/table_posts.php',$pages_posts);
    echo json_encode(array('status' => $status, 'offset' => $offset, 'html' => $html, 'all_posts' => $all_posts, 'res_posts' => $posts_res));
    die();
}

if($action == 'load_more_schedules')
{
    require_once('classes/user.php');
    require_once('classes/schedules.php');
    $user_class = new User();
    $user = $user_class->get_user();
    $schedule_class = new Schedules($user);

    $offset = empty($_REQUEST['offset']) ? 0 : (int)$_REQUEST['offset'];
    $datefrom = '';
    $dateinto = '';
    if(!empty($_SESSION['schedule_page']['dates']))
    {
        $datefrom = $_SESSION['schedule_page']['dates']['datefrom'];
        $dateinto = $_SESSION['schedule_page']['dates']['dateinto'];
    }

    $result_schedules = array();
    if(!empty($_SESSION['schedule_page']['schedules']))
    {
        $result_schedules = $_SESSION['schedule_page']['schedules'];
    }
    //echo"<pre>";print_r($result_schedules);

    $offset = $offset + LOAD_SCHEDULE_POSTS;
    $schedules_data['schedules'] = $schedule_class->get_schedules_list2($datefrom, $dateinto, LOAD_SCHEDULE_POSTS, $result_schedules);

    $status = 2;

    if(!empty($schedules_data['schedules']))
        foreach($schedules_data['schedules'] as $schedule)
        {
            if(!empty($schedule['fan_pages']))
                foreach($schedule['fan_pages'] as $fan_page)
                {
                    if(!empty($result_schedules[$schedule['id']][$fan_page['id']])){

                    }else {
                        $result_schedules[$schedule['id']][$fan_page['id']] = array();
                    }

                    $status = 1;
                    if(!empty($fan_page['posts']))
                        foreach($fan_page['posts'] as $post)
                        {
                            $result_schedules[$schedule['id']][$fan_page['id']][] = $post['id'];
                        }
                }
        }

    //echo"<pre>";print_r($result_schedules);die();
    $_SESSION['schedule_page']['schedules'] = $result_schedules;

    $html = load_view('templates/table_schedules.php',$schedules_data);
    echo json_encode(array('status' => $status, 'offset' => $offset, 'html' => $html));
    die();
}

if($action == 'load_more_groups')
{
    $offset = empty($_POST['offset']) ? 0 : (int)$_POST['offset'];
    if(!isset($_SESSION['new_data'])){
        echo json_encode(array('status' => 2));
        die();
    }

    $new_data = $_SESSION['new_data'];
    $schedule_groups['data'] = array();

    require_once('classes/user.php');
    require_once('classes/fb.php');
    $user_class = new User();
    $fb         = new Facebook();
    $user       = $user_class->get_user();

    $all_groups = empty($_SESSION['new_data']['all_groups']) ? array() : $_SESSION['new_data']['all_groups'];

    $groups_res = array();
    $offset += LOAD_GROUPS;

    $limit = $user['fb_pages_limit'];
    $saved_groups = $fb->load_user_groups($user['id']);
    if($limit > $offset)
        $limit = $offset;

    $limit = $limit - count($saved_groups);

    $fb_groups = array();
    if($limit > 0) {
        $fb_groups = $fb->get_groups_list($user['fb_user_id'], $user['fb_token'], $offset);
    }

    if(empty($saved_groups)){
        if(!empty($fb_groups['data']))
            foreach($fb_groups['data'] as $group)
            {
                if(!in_array($group['id'],$all_groups)) {
                    $schedule_groups['data'][$group['id']] = array('id' => $group['id'], 'name' => $group['name'], 'closed' => $group['closed']);
                    $all_groups[] = $group['id'];
                }

                if(count($schedule_groups['data']) >= $offset) break;
            }
    }
    else{
        foreach($saved_groups as $group)
        {
            if(!in_array($group->id,$all_groups) && $group_info = $fb->check_group_access($group->id,$user['fb_token'])){
                $schedule_groups['data'][$group_info['id']] = array('id' => $group_info['id'],'name' => $group_info['name'], 'closed' => $group_info['closed']);
                $all_groups[] = $group->id;
            }

            if(count($schedule_groups['data']) >= $offset) break;
        }

        if(!empty($fb_groups['data']))
            foreach($fb_groups['data'] as $group)
            {
                if(!in_array($group['id'],$all_groups)) {
                    $schedule_groups['data'][$group['id']] = array('id' => $group['id'], 'name' => $group['name'], 'closed' => $group['closed']);
                    $all_groups[] = $group['id'];
                }

                if(count($schedule_groups['data']) >= $offset) break;
            }
    }

    $status = (empty($schedule_groups['data']) || count($schedule_groups['data']) == 0) ? 2 : 1;
    $_SESSION['new_data']['all_groups'] = $all_groups;

    $html = load_view('templates/load_groups.php',$schedule_groups);
    echo json_encode(array('status' => $status, 'offset' => $offset, 'html' => $html));
    die();
}

echo json_encode($result);
die();


function load_view($template, $params)
{
    ob_start();
    $data = $params;
    include($template);
    $view = ob_get_contents();
    ob_clean();

    return $view;
}