<?php

require_once('database.php');
require_once('fb.php');

class Schedules{

    private $user_id = 0;
    private $is_admin = 0;
    private $max_pages = 0;
    private $fb_user_id = 0;

    private $db;

    private $facebook;

    function __construct($user = array()){
        $this->db = db::Instance();
        $this->facebook = new Facebook();

        if(!empty($user['id']))
            $this->user_id = $user['id'];

        if(!empty($user['is_admin']))
            $this->is_admin = $user['is_admin'];

        if(!empty($user['fb_pages_limit']))
            $this->max_pages = $user['fb_pages_limit'];

        if(!empty($user['fb_pages_limit']))
            $this->fb_user_id = $user['fb_user_id'];
    }

    public function add($data, $fb_user_name, $fb_token, $id = 0){
        if($this->user_id == 0 || $this->fb_user_id == 0){
            $result['errors'] = "General Error.";
            return $result;
        }

        $pages              = empty($data['pages']) ? array() : $data['pages'];
        $condition_type     = empty($data['condition_type']) ? 0 : $data['condition_type'];
        $posts              = empty($data['posts']) ? array() : $data['posts'];
        $keyword            = empty($data['keyword']) ? '' : $data['keyword'];
        $add_condition      = empty($data['add_condition_type']) ? 0 : $data['add_condition_type'];
        $add_keyword        = empty($data['keyword']) ? '' : $data['keyword'];
        $comment            = empty($data['comment']) ? '' : $data['comment'];
        $datefrom           = empty($data['datefrom']) ? '' : $data['datefrom'];
        $timefrom           = empty($data['timefrom']) ? '' : $data['timefrom'];
        $is_repeat          = empty($data['is_repeat']) ? 0 : $data['is_repeat'];
        $repeat_frequency   = empty($data['repeat_frequency']) ? 0 : $data['repeat_frequency'];
        $until_date         = empty($data['until_date']) ? '' : $data['until_date'];
        $until_time         = empty($data['until_time']) ? '' : $data['until_time'];
        $weekdays           = empty($data['frequency_weekly']) ? array() : $data['frequency_weekly'];
        $repeat_interval    = empty($data['repeat_interval']) ? 0 : $data['repeat_interval'];
        $is_auto_delete     = empty($data['is_auto_delete']) ? 0 : $data['is_auto_delete'];
        $delete_interval    = empty($data['delete_interval']) ? 0 : $data['delete_interval'];
        $delete_type        = empty($data['delete_type']) ? 0 : $data['delete_type'];
        $delete_date        = empty($data['delete_date']) ? '' : $data['delete_date'];
        $delete_time        = empty($data['delete_time']) ? '' : $data['delete_time'];


        $result['data']     = $data;
        $result['errors']   = array();

        if(count($pages) == 0){
            $result['errors'] = "At least one fan page should be chosen";
            return $result;
        }

        if(count($pages) > $this->max_pages){
            $result['errors'] = "You can choose maximum ".$this->max_pages." pages";
            return $result;
        }

        if($datefrom == '' || $timefrom == ''){
            $result['errors'] = 'A valid date and time is required.';
            return $result;
        }

        if($condition_type == 2 && count($posts) == 0){
            $result['errors'] = "At least one post should be chosen.";
            return $result;
        }

        if($condition_type == 3 && $keyword == ''){
            $result['errors'] = "Keyword is required.";
            return $result;
        }

        if($condition_type != 3 && $add_condition == 2 && $add_keyword == ''){
            $result['errors'] = "Keyword is required.";
            return $result;
        }

        if($comment == ''){
            $result['errors'] = "Comment can not be empty.";
            return $result;
        }

        $timestamp = $this->timestamp();

        $datetime_from = $this->unix_time($datefrom, $timefrom);

        if($timestamp > ($datetime_from + 300)){
            $result['errors'] = "The start date can not be in the past.";
            return $result;
        }

        if($is_repeat == 1 && ($until_date == '' || $until_time == '')){
            $result['errors'] = 'A valid date and time is required.';
            return $result;
        }

        if($is_repeat == 1){
            $datetime_until = $this->unix_time($until_date, $until_time);
        }else{
            $datetime_until = $datetime_from;
        }

        if($datetime_until < $datetime_from){
            $result['errors'] = "The end date can not be less than start date.";
            return $result;
        }

        if($repeat_interval < 0) $repeat_interval = 0;
        if($delete_interval < 0) $delete_interval = 0;

        if($is_auto_delete == 1 && $delete_type == 2 && ($delete_date == '' || $delete_time == '')){
            $result['errors'] = 'A valid date and time is required.';
            return $result;
        }

        if($is_auto_delete == 1 && $delete_type == 2){
            $datetime_delete = $this->unix_time($delete_date, $delete_time);
        }else{
            $datetime_delete = $datetime_from;
        }

        if($datetime_delete < $datetime_from){
            $result['errors'] = "The delete date can not be less than start date.";
            return $result;
        }

        if($is_repeat == 1 && $repeat_frequency == 3 && count($weekdays) == 0){
            $result['errors'] = "Weekdays should be chosen.";
            return $result;
        }

        $ins_data['user_id']            = $this->user_id;
        $ins_data['fb_user_id']         = $this->fb_user_id;
        $ins_data['fb_user_name']       = $fb_user_name;
        $ins_data['fb_token']           = $fb_token;
        $ins_data['source_type']        = $data['source_type'];
        $ins_data['pages']              = json_encode($pages);
        $ins_data['posts']              = json_encode($posts);
        $ins_data['condition_type']     = $condition_type;
        $ins_data['comment']            = $comment;
        $ins_data['keyword']            = empty($keyword) ? $add_keyword : $keyword;
        $ins_data['start_timestamp']    = $datetime_from;
        $ins_data['end_timestamp']      = $datetime_until;
        $ins_data['is_repeat']          = $is_repeat;
        $ins_data['repeat_frequency']   = $repeat_frequency;
        $ins_data['repeat_weekdays']    = json_encode($weekdays);
        $ins_data['repeat_interval']    = $repeat_interval;
        $ins_data['auto_delete']        = $is_auto_delete;
        $ins_data['delete_type']        = $delete_type;
        $ins_data['delete_interval']    = $delete_interval;
        $ins_data['delete_timestamp']   = $datetime_delete;
        $ins_data['next_set_timestamp'] = $datetime_from;
        $ins_data['add_condition']      = $add_condition;
        $ins_data['changed_at']         = $this->timestamp('Europe/London');
        $ins_data['status']             = 1;

        if($id == 0) {
            $ins_data['created_at']         = $this->timestamp('Europe/London');
            $this->db->insert(DB_TABLE_PREFIX . 'schedules', $ins_data);
        }else{
            $this->db->update(DB_TABLE_PREFIX.'schedules',$ins_data,$id);
        }

        $result['success'] = true;
        return $result;
    }

    public function unix_time($date, $time)
    {
        if(!empty($date) && !empty($date))
        {
            $date = explode('/', $date);
            if(count($date) == 3)
            {
                return $this->to_unix_time($date[2].'-'.$date[0].'-'.$date[1].' '.$time);
            }
            else
            {
                return 0;
            }
        }
        else
        {
            return 0;
        }
    }

    private function to_unix_time($datestr = '')
    {
        if ($datestr == '')
        {
            return FALSE;
        }

        $datestr = trim($datestr);
        $datestr = preg_replace("/\040+/", ' ', $datestr);

        if ( ! preg_match('/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}\s[0-9]{1,2}:[0-9]{1,2}(?::[0-9]{1,2})?(?:\s[AP]M)?$/i', $datestr))
        {
            return FALSE;
        }

        $split = explode(' ', $datestr);

        $ex = explode("-", $split['0']);

        $year  = (strlen($ex['0']) == 2) ? '20'.$ex['0'] : $ex['0'];
        $month = (strlen($ex['1']) == 1) ? '0'.$ex['1']  : $ex['1'];
        $day   = (strlen($ex['2']) == 1) ? '0'.$ex['2']  : $ex['2'];

        $ex = explode(":", $split['1']);

        $hour = (strlen($ex['0']) == 1) ? '0'.$ex['0'] : $ex['0'];
        $min  = (strlen($ex['1']) == 1) ? '0'.$ex['1'] : $ex['1'];

        if (isset($ex['2']) && preg_match('/[0-9]{1,2}/', $ex['2']))
        {
            $sec  = (strlen($ex['2']) == 1) ? '0'.$ex['2'] : $ex['2'];
        }
        else
        {
            // Unless specified, seconds get set to zero.
            $sec = '00';
        }

        if (isset($split['2']))
        {
            $ampm = strtolower($split['2']);

            if (substr($ampm, 0, 1) == 'p' AND $hour < 12)
                $hour = $hour + 12;

            if (substr($ampm, 0, 1) == 'a' AND $hour == 12)
                $hour =  '00';

            if (strlen($hour) == 1)
                $hour = '0'.$hour;
        }

        return mktime($hour, $min, $sec, $month, $day, $year);
    }

    public function timestamp($gmt_zone = 0)
    {
        $user_id = empty($_SESSION['far_user_id']) ? 0 : (int)$_SESSION['far_user_id'];

        if(empty($gmt_zone) && $user_id)
        {
            $user_tmp = $this->db->selectOne("SELECT timezone FROM ".DB_TABLE_PREFIX."users WHERE id='".$user_id."'");
            $gmt_zone = empty($user_tmp['timezone']) ? 0 : $user_tmp['timezone'];
        }

        if($gmt_zone == '0'){
            $gmt_zone = "Europe/London";
        }

        $timezone = new DateTimeZone($gmt_zone);
        $offset   = $timezone->getOffset(new DateTime("now"));

        return strtotime(gmdate("M d Y H:i:s", time())) + $offset;
    }

    public function get_schedules_list2($datefrom = '', $dateinto = '', $limit = 0, $data_exists = array())
    {
        if($limit == 0) $limit = LOAD_SCHEDULE_POSTS;

        $where_date = '';
        if(!empty($datefrom) && !empty($dateinto)){
            $where_date = " AND s.created_at >='".$datefrom."' AND s.created_at <= '".$dateinto."'";
        }

        $all_posts  = array();
        $all_pages  = array();
        $res_pages  = array();

        $res_count = 0;
        $schedules = $this->db->select("SELECT s.*, u.name FROM ".DB_TABLE_PREFIX."schedules s JOIN ".DB_TABLE_PREFIX."users u ON u.id = s.user_id WHERE (s.user_id = '".$this->user_id."' OR '".$this->is_admin."' <> '0') ".$where_date." ORDER BY s.id DESC");

        if(!empty($schedules))
            foreach($schedules as $key => $schedule) {
                if($res_count >= $limit) break;

                $fan_pages = json_decode(html_entity_decode($schedule['pages']));

                if(!empty($fan_pages)) {
                    $res_pages = array();

                    foreach ($fan_pages as $fan_page) {
                        $tmp_page = null;

                        if(empty($all_pages[$fan_page])) {
                            $add_fields = ($schedule['source_type'] == 1) ? 'likes,name' : 'name';
                            $page_info = $this->facebook->get_object_info($fan_page, $schedule['fb_token'],$add_fields);
                            $name = "FB Error!";
                            if (!empty($page_info->name))
                                $name = $page_info->name;

                            $tmp_page['name'] = $name;
                            $tmp_page['id'] = empty($page_info->id) ? 0 : $page_info->id;
                            $tmp_page['likes'] = empty($page_info->likes) ? 0 : $page_info->likes;
                            $all_pages[$fan_page]['name']   = $tmp_page['name'];
                            $all_pages[$fan_page]['id']     = $tmp_page['id'];
                            $all_pages[$fan_page]['likes']  = $tmp_page['likes'];
                        }else{
                            $tmp_page['name']   = $all_pages[$fan_page]['name'];
                            $tmp_page['id']     = $all_pages[$fan_page]['id'];
                            $tmp_page['likes']  = $all_pages[$fan_page]['likes'];
                        }

                        if($schedule['condition_type'] == 2){
                            $posts = json_decode(html_entity_decode($schedule['posts']));
                        }else{
                            $posts = $this->db->select("SELECT DISTINCT(post_id) as post_id FROM ".DB_TABLE_PREFIX."schedules_queue WHERE schedule_id = '".$schedule['id']."'");
                        }

                        $first_post = 1;
                        if(!empty($posts)){
                            foreach($posts as $post){
                                if($res_count >= $limit) break;

                                if(!empty($data_exists[$schedule['id']][$fan_page]) && in_array($post,$data_exists[$schedule['id']][$fan_page])){
                                    $first_post = 0;
                                    continue;
                                }

                                $tmp_post = null;
                                if($schedule['condition_type'] != 2){$post = $post['post_id'];}
                                if(empty($all_posts[$post])) {
                                    $can_comment = true;
                                    $check = $this->db->select("SELECT * FROM ".DB_TABLE_PREFIX."schedules_queue WHERE schedule_id = '".$schedule['id']."' AND can_comment = 0 AND post_id = '".$post."'");
                                    if(!empty($check)) $can_comment = false;

                                    $post_info = $this->facebook->get_object_info($post, $schedule['fb_token'], 'message,picture,created_time');
                                    $comments_count = $this->facebook->get_object_comments_info($post, $schedule['fb_token']);
                                    $likes = $this->facebook->get_object_likes_info($post, $schedule['fb_token']);

                                    $comm_count = empty($comments_count->summary->total_count) ? 0 : $comments_count->summary->total_count;
                                    $likes_count = empty($likes->summary->total_count) ? 0 : $likes->summary->total_count;
                                    $created = empty($post_info->created_time) ? '' : $post_info->created_time;
                                    $tmp_post['message']        = empty($post_info->message) ? '' : $post_info->message;
                                    $tmp_post['picture']        = empty($post_info->picture) ? 'https://graph.facebook.com/'.$post.'/picture' : $post_info->picture;
                                    $tmp_post['title']          = strlenchar($tmp_post['message'],80);
                                    $tmp_post['comments']       = $comm_count;
                                    $tmp_post['likes']          = $likes_count;
                                    $tmp_post['created']        = $created;
                                    $tmp_post['can_comment']    = $can_comment;

                                    $all_posts[$post]['message']    = $tmp_post['message'];
                                    $all_posts[$post]['picture']    = $tmp_post['picture'];
                                    $all_posts[$post]['title']      = $tmp_post['title'];
                                    $all_posts[$post]['comments']   = $tmp_post['comments'];
                                    $all_posts[$post]['likes']      = $tmp_post['likes'];
                                    $all_posts[$post]['created']    = $tmp_post['created'];
                                    $all_posts[$post]['can_comment']= $tmp_post['can_comment'];

                                }else{
                                    $tmp_post['message']        = $all_posts[$post]['message'];
                                    $tmp_post['picture']        = $all_posts[$post]['picture'];
                                    $tmp_post['title']          = $all_posts[$post]['title'];
                                    $tmp_post['comments']       = $all_posts[$post]['comments'];
                                    $tmp_post['likes']          = $all_posts[$post]['likes'];
                                    $tmp_post['created']        = $all_posts[$post]['created'];
                                    $tmp_post['can_comment']    = $all_posts[$post]['can_comment'];
                                }

                                $count = $this->db->selectOne("SELECT COUNT(1) as `count` FROM ".DB_TABLE_PREFIX."schedules_queue s JOIN ".DB_TABLE_PREFIX."completed c ON c.queue_id = s.id WHERE s.post_id = '".$post."' AND s.schedule_id = '".$schedule['id']."'");

                                $tmp_post['completed']  = $count['count'];
                                $tmp_post['id']         = $post;
                                $tmp_post['is_first']   = $first_post;
                                $first_post             = 0;

                                $res_count++;
                                $tmp_page['posts'][] = $tmp_post;
                            }

                        }

                        if(empty($posts) && !empty($data_exists[$schedule['id']][$fan_page])) continue;

                        if(empty($posts)) $res_count++;

                        if(!empty($posts) && empty($tmp_page['posts'])) continue;

                        $res_pages[] = $tmp_page;
                    }
                }

                if(!empty($res_pages))
                    $schedules[$key]['fan_pages'] = $res_pages;
                else
                    unset($schedules[$key]);
            }

        //echo"<!-- time end: ".time()." -->";

        //echo"<pre>";print_r($schedules);die();
        //echo $limit.'<br>'.$res_count;echo"<pre>";print_r($schedules);die();
        return $schedules;
    }

    public function delete_schedule($sid)
    {
        $schedule = $this->db->selectOne("SELECT * FROM ".DB_TABLE_PREFIX."schedules WHERE id = '".$sid."'");
        if(empty($schedule))
            return false;

        if($schedule['user_id'] != $this->user_id && !$this->is_admin)
            return false;

        $this->db->delete(DB_TABLE_PREFIX."schedules",$sid);

        return true;
    }

    public function delete_page($sid, $pid)
    {
        $schedule = $this->db->selectOne("SELECT * FROM ".DB_TABLE_PREFIX."schedules WHERE id = '".$sid."'");
        if(empty($schedule))
            return false;

        if($schedule['user_id'] != $this->user_id && !$this->is_admin)
            return false;

        $fan_pages = json_decode(html_entity_decode($schedule['pages']));
        if(!empty($fan_pages))
            foreach($fan_pages as $key => $page){
                if($page == $pid) {
                    unset($fan_pages[$key]);
                }
            }

        $upd_data['pages'] = json_encode($fan_pages);
        $this->db->update(DB_TABLE_PREFIX.'schedules',$upd_data,$sid);

        return true;

    }

    public function get_schedule($id)
    {
        $schedule = $this->db->selectOne("SELECT * FROM ".DB_TABLE_PREFIX."schedules WHERE id = '".$id."'");
        if(empty($schedule))
            return false;

        if($schedule['user_id'] != $this->user_id && !$this->is_admin)
            return false;

        return $schedule;
    }

    public function update_schedule($id, $data)
    {
        $schedule = $this->db->selectOne("SELECT * FROM ".DB_TABLE_PREFIX."schedules WHERE id = '".$id."'");
        if(empty($schedule))
            return false;

        if($schedule['user_id'] != $this->user_id && !$this->is_admin)
            return false;

        $this->db->update(DB_TABLE_PREFIX.'schedules',$data,$id);

        return true;
    }
}