<?php

class PBReusableModel_Notifications extends CI_Model {

    const USER_SETTINGS = 'vw_push_tokens_from_settings';
    const PODCASTS = 'taw_feed_podcasts';
    const WRITING = 'taw_feed_writing';
    const VIDEOS = 'taw_feed_videos';
    const NOTIFICATIONS_LOG = 'taw_notifications_log';

    function __construct() {
        parent::__construct();
        $this->load->database();
        $this->load->helper('date');
        $this->load->model('PBReusableModel_Global','globals');
    }

    public function getSentNotifications() {
        $this->load->database();
        $this->db->select('*');
        $this->db->from(self::NOTIFICATIONS_LOG);
        $this->db->where('type=','tawnews');
        $this->db->order_by('sent_date','DESC');
        $query = $this->db->get();
        return $query->result();
    }
    public function debugGetAllUsersSubscribedToPodcastNotifications($type) {
        $this->load->database();
        $this->db->select('user_id,device_token');
        $this->db->from(self::USER_SETTINGS);
        $this->db->where('key',$type);
        $this->db->where('value=','1');
        $query = $this->db->get();
        return $query->result();
    }
    public function getAllUsersSubscribedToBespokeNotifications() {
        $this->load->database();
        $this->db->select('user_id,device_token');
        $this->db->from(self::USER_SETTINGS);
        $this->db->where('key','tawnews');
        $this->db->where('value',1);
        $query = $this->db->get();
        // return "";
        return $query->result();
    }
    public function getAllUsersSubscribedToPodcastNotifications() {
        $this->load->database();
        $this->db->select('user_id,device_token');
        $this->db->from(self::USER_SETTINGS);
        $this->db->where('key','podcasts');
        $this->db->where('value',1);
        $query = $this->db->get();
        // return "";
        return $query->result();
    }
    public function getAllUsersSubscribedToVideoNotifications() {
        $this->load->database();
        $this->db->select('user_id,device_token');
        $this->db->from(self::USER_SETTINGS);
        $this->db->where('key','videos');
        $this->db->where('value=','1');
        $query = $this->db->get();
        // return "";
        return $query->result();
    }
    public function getAllUsersSubscribedToArticleNotifications() {
        $this->load->database();
        $this->db->select('user_id,device_token');
        $this->db->from(self::USER_SETTINGS);
        $this->db->where('key','articles');
        $this->db->where('value=','1');
        $query = $this->db->get();
        // return "";
        return $query->result();
    }

    public function saveSentNotificationsEntry($message_array) {
        $this->load->database();
        $this->db->insert(self::NOTIFICATIONS_LOG,$message_array);
        if($this->db->insert_id()) {
            return $this->db->insert_id();
        } else {
            return 0;
        }
    }

    public function sendNewBespokeNotificationToUser($array) {
        $push_array = $this->input->post();
        // var_dump($push_array);

        $payload_array = array();
        $payload_array['type'] = 'tawnews';
        $payload_array['post_id'] = 0;

        $message_array = array();
        $message_array['title'] = $push_array['title'];
        $message_array['message'] = $push_array['message'];
        $message_array['count'] = count($array);
        $message_array['post_id'] = 0;
        $message_array['type'] = 'tawnews';
        $message_array['sent_date'] = date('Y-m-d H:i:s');
        $this->saveSentNotificationsEntry($message_array);

        $title = $message_array['title'];
        $message = $message_array['message'];

        $this->analytics->recordAction(array(
            'date' => date('Y-m-d H:i:s'),
            'partner_id' => 0,
            'user_id' => 0,
            'type' => 'SentBespokeNotification',
            'variable' => $title,
            'secondary_variable' => $message
        ));

        $extra = array();

        $app_id = "b85c6195-a943-4a17-8f3e-187c7132276b";
        $rest_api_key = "OTNjMTRhOTctMzI0ZS00NzY4LTllMTEtNmIwNmVlNjA3YWM1";
        $heading = array(
            "en" => $title
        );
        $content = array(
            "en" => $message
        );
        $fields = array(
            'app_id' => $app_id,
            'contents' => $content,
            'headings' => $heading,
            'data' => $payload_array,
            'include_player_ids' => $array
        );

        $fields = json_encode($fields);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Authorization: Basic ' . $rest_api_key
        ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $response = curl_exec($ch);
        curl_close($ch);
        // var_dump($response);

        $return["allresponses"] = $response;
        $return = json_encode($return);

    }

    public function sendNewPodcastNotificationToUser($array,$post_id) {

        $this->load->database();
        $this->db->select('*');
        $this->db->from(self::NOTIFICATIONS_LOG);
        $this->db->limit(1);
        $this->db->where('post_id =',$post_id);
        $query = $this->db->get();
        $result = $query->row_array();
        // $result = "";
        // echo "Result";
        // var_dump($result);
        // exit;
        if(!$result) {

            $this->load->database();
            $this->db->select('*');
            $this->db->from(self::PODCASTS);
            $this->db->limit(1);
            $this->db->order_by('id','DESC');
            $query = $this->db->get();
            $result = $query->row_array();

            $payload_array = array();
            $payload_array['type'] = 'podcast';
            $payload_array['post_id'] = $result['post_id'];

            $message_array = array();
            $message_array['title'] = 'New Podcast from The Anfield Wrap';
            $message_array['message'] = 'Listen to '.$result['title'].' now!';
            $message_array['count'] = count($array);
            $message_array['post_id'] = $result['post_id'];
            $message_array['type'] = 'podcast';
            $message_array['sent_date'] = date('Y-m-d H:i:s');
            $this->saveSentNotificationsEntry($message_array);

            $title = $message_array['title'];
            $message = $message_array['message'];

            $this->analytics->recordAction(array(
                'date' => date('Y-m-d H:i:s'),
                'partner_id' => 0,
                'user_id' => 0,
                'type' => 'SentPodcastNotification',
                'variable' => $title,
                'secondary_variable' => $message
            ));

            $chunked_podcast_array = array_chunk($array, 10000, true);

//			foreach($chunked_podcast_array as $chunk) {
//				$send_array = array();
//				foreach($chunk as $subscriber) {
//					array_push($send_array,$subscriber->device_token);
//					// sleep(0.2);
//				}

            $extra = array();

            $app_id = "b85c6195-a943-4a17-8f3e-187c7132276b";
            $rest_api_key = "OTNjMTRhOTctMzI0ZS00NzY4LTllMTEtNmIwNmVlNjA3YWM1";
            $heading = array(
                "en" => $title
            );
            $content = array(
                "en" => $message
            );
            $fields = array(
                'app_id' => $app_id,
                'contents' => $content,
                'headings' => $heading,
                'data' => $payload_array,
                'included_segments' => array("Subscribed Users")
//                    'include_player_ids' => $send_array
            );

            $fields = json_encode($fields);

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Authorization: Basic ' . $rest_api_key
            ));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

            $response = curl_exec($ch);
            curl_close($ch);
//			}


            // var_dump($response);
            error_log(print_r($response, TRUE));
            // return var_dump($response);

            // exit;

            $return["allresponses"] = $response;
            $return = json_encode($return);
        } else {
            return false;
        }
    }

    public function sendNewVideoNotificationToUser($array,$post_id) {
        $this->load->database();
        $this->db->select('*');
        $this->db->from(self::NOTIFICATIONS_LOG);
        $this->db->limit(1);
        $this->db->where('post_id =',$post_id);
        $query = $this->db->get();
        $result = $query->row_array();
        if(!$result) {
            $this->load->database();
            $this->db->select('*');
            $this->db->from(self::VIDEOS);
            $this->db->limit(1);
            $this->db->order_by('id','DESC');
            $query = $this->db->get();
            $result = $query->row_array();

            $payload_array = array();
            $payload_array['type'] = 'video';
            $payload_array['post_id'] = $result['post_id'];

            $message_array = array();
            $message_array['title'] = 'New video from The Anfield Wrap';
            $message_array['message'] = 'Watch '.$result['title'].' now!';
            $message_array['count'] = count($array);
            $message_array['post_id'] = $result['post_id'];
            $message_array['type'] = 'video';
            $message_array['sent_date'] = date('Y-m-d H:i:s');
            // $this->saveSentNotificationsEntry($message_array);
            // return true;
            // exit;
            $title = $message_array['title'];
            $message = $message_array['message'];

            $this->analytics->recordAction(array(
                'date' => date('Y-m-d H:i:s'),
                'partner_id' => 0,
                'user_id' => 0,
                'type' => 'SentVideoNotification',
                'variable' => $title,
                'secondary_variable' => $message
            ));

            $extra = array();

            $app_id = "b85c6195-a943-4a17-8f3e-187c7132276b";
            $rest_api_key = "OTNjMTRhOTctMzI0ZS00NzY4LTllMTEtNmIwNmVlNjA3YWM1";
            $heading = array(
                "en" => $title
            );
            $content = array(
                "en" => $message
            );
            $fields = array(
                'app_id' => $app_id,
                'contents' => $content,
                'headings' => $heading,
                'data' => $payload_array,
                'included_segments' => array("Subscribed Users")
            );

            $fields = json_encode($fields);

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Authorization: Basic ' . $rest_api_key
            ));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

            $response = curl_exec($ch);
            curl_close($ch);
            // var_dump($response);

            $return["allresponses"] = $response;
            $return = json_encode($return);
        } else {
            return false;
        }
    }

    public function sendNewArticleNotificationToUser($array,$post_id) {
        $this->load->database();
        $this->db->select('*');
        $this->db->from(self::NOTIFICATIONS_LOG);
        $this->db->limit(1);
        $this->db->where('post_id =',$post_id);
        $query = $this->db->get();
        $result = $query->row_array();
        if(!$result) {
            $this->load->database();
            $this->db->select('*');
            $this->db->from(self::WRITING);
            $this->db->limit(1);
            $this->db->order_by('id','DESC');
            $query = $this->db->get();
            $result = $query->row_array();

            $payload_array = array();
            $payload_array['type'] = 'article';
            $payload_array['post_id'] = $result['post_id'];

            $message_array = array();
            $message_array['title'] = 'New article from The Anfield Wrap';
            $message_array['message'] = 'Read '.$result['title'].' now!';
            $message_array['count'] = count($array);
            $message_array['post_id'] = $result['post_id'];
            $message_array['type'] = 'article';
            $message_array['sent_date'] = date('Y-m-d H:i:s');
            // $this->saveSentNotificationsEntry($message_array);
            // return true;
            // exit;
            $title = $message_array['title'];
            $message = $message_array['message'];

            $this->analytics->recordAction(array(
                'date' => date('Y-m-d H:i:s'),
                'partner_id' => 0,
                'user_id' => 0,
                'type' => 'SentArticleNotification',
                'variable' => $title,
                'secondary_variable' => $message
            ));

            $extra = array();

            $app_id = "b85c6195-a943-4a17-8f3e-187c7132276b";
            $rest_api_key = "OTNjMTRhOTctMzI0ZS00NzY4LTllMTEtNmIwNmVlNjA3YWM1";
            $heading = array(
                "en" => $title
            );
            $content = array(
                "en" => $message
            );
            $fields = array(
                'app_id' => $app_id,
                'contents' => $content,
                'headings' => $heading,
                'data' => $payload_array,
//	            'include_player_ids' => $array
                'included_segments' => array("Subscribed Users")

            );

            $fields = json_encode($fields);

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Authorization: Basic ' . $rest_api_key
            ));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

            $response = curl_exec($ch);
            curl_close($ch);
            // var_dump($response);

            $return["allresponses"] = $response;
            $return = json_encode($return);
        } else {
            return false;
        }
    }

    public function sendNewPodcastNotificationToUsers($post_id = NULL) {
        $podcast_subscribers = $this->getAllUsersSubscribedToPodcastNotifications();
        if($podcast_subscribers) {
            // $chunked_podcast_Array = array_chunk($podcast_subscribers, 10000, true);
            $response = $this->sendNewPodcastNotificationToUser($podcast_subscribers,$post_id);
            return $array;
        } else {
            return 9; // Zero subscribers
        }
        return;
    }

    public function sendNewVideoNotificationToUsers($post_id) {
        $video_subscribers = $this->getAllUsersSubscribedToVideoNotifications();
        if($video_subscribers) {

            $chunked_video_Array = array_chunk($video_subscribers, 10000, true);
//			foreach($chunked_video_Array as $chunk) {
//				$array = array();
//				foreach($chunk as $subscriber) {
//					array_push($array,$subscriber->device_token);
//					// sleep(0.2);
//				}

            $response = $this->sendNewVideoNotificationToUser(array(),$post_id);
//			}

            $this->load->database();
            $this->db->select('*');
            $this->db->from(self::VIDEOS);
            $this->db->limit(1);
            $this->db->order_by('id','DESC');
            $query = $this->db->get();
            $result = $query->row_array();

            $message_array = array();
            $message_array['title'] = 'New video from The Anfield Wrap';
            $message_array['message'] = 'Watch '.$result['title'].' now!';
            $message_array['count'] = count($array);
            $message_array['post_id'] = $result['post_id'];
            $message_array['type'] = 'video';
            $message_array['sent_date'] = date('Y-m-d H:i:s');
            $this->saveSentNotificationsEntry($message_array);


            return $array;
        } else {
            return 9; // Zero subscribers
        }
    }

    public function sendNewArticleNotificationToUsers($post_id) {
        $article_subscribers = $this->getAllUsersSubscribedToArticleNotifications();
        // var_dump($article_subscribers);
        if($article_subscribers) {
            // foreach($podcast_subscribers as $subscriber) {
            //     echo $subscriber->user_id." is subscribed";
            // }

//			$chunked_article_Array = array_chunk($article_subscribers, 10000, true);
            $array = array();
            $this->sendNewArticleNotificationToUser($array,$post_id);


            $this->load->database();
            $this->db->select('*');
            $this->db->from(self::WRITING);
            $this->db->limit(1);
            $this->db->order_by('id','DESC');
            $query = $this->db->get();
            $result = $query->row_array();

            $message_array = array();
            $message_array['title'] = 'New article from The Anfield Wrap';
            $message_array['message'] = 'Read '.$result['title'].' now!';
            $message_array['count'] = count($array);
            $message_array['post_id'] = $result['post_id'];
            $message_array['type'] = 'article';
            $message_array['sent_date'] = date('Y-m-d H:i:s');
            $this->saveSentNotificationsEntry($message_array);

            return $array;
        } else {
            return 9; // Zero subscribers
        }
    }

    public function sendNewBespokeNotificationToUsers() {
        $bespoke_subscribers = $this->getAllUsersSubscribedToBespokeNotifications();
        if($bespoke_subscribers) {
            $array = array();
            foreach($bespoke_subscribers as $subscriber) {
                array_push($array,$subscriber->device_token);
            }
            $response = $this->sendNewBespokeNotificationToUser($array);
            return $array;
        } else {
            return 9; // Zero subscribers
        }
    }
}
