<?php

class PBReusableModel_Wordpress extends CI_Model {

	const PODCASTS = 'taw_feed_podcasts';
	const WRITING = 'taw_feed_writing';
	const PARTNERS = 'auth_partners';
	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_Security','appsecurity');
        // $this->load->model('PBReusableModel_Analytics','analytics');
        // $this->load->model('PBReusableModel_Partners','partners');
        // $this->load->model('PBReusableModel_Global','globals');
		// $this->load->model('PBReusableModel_Wallet','wallet');
		// $this->load->model('PBReusableModel_Notifications','notifications');
    }

	/* WRITING START ******************************************************************/

	public function insertWritingFeedContentFromWordpress($article) {
		// var_dump($data->data);
		// foreach($post as $podcast) {
			// echo "id - ".$podcast->id;
			$article_array = array();
			$article_array['post_id'] = $article->id;
			$article_array['title'] = addslashes(html_entity_decode($article->title));
			$article_array['content'] = addslashes($article->content);
			$article_array['excerpt'] = addslashes($article->excerpt);
			$article_array['created_date'] = $article->date;
			$article_array['modified_date'] = $article->modified;

			$article_array['featured'] = 1;
			foreach($article->categories as $category) {
				if($category->id == 2266) {
					$article_array['featured'] = 0;
				}
			}

			$article_array['author'] = addslashes($article->author->name);

			if($article->thumbnail_images->thumbnail->url) {
				$article_array['thumbnail_image'] = addslashes($article->thumbnail_images->thumbnail->url);
			}

			if($article->thumbnail_images->thumbnail->url) {
				$article_array['thumbnail_image'] = addslashes($article->thumbnail_images->thumbnail->url);
			}
			if($article->thumbnail_images->medium->url) {
				$article_array['medium_image'] = addslashes($article->thumbnail_images->medium->url);
			}
			if($article->thumbnail_images->large->url) {
				$article_array['large_image'] = addslashes($article->thumbnail_images->large->url);
			}

			$article_array['content'] = addslashes($article->custom_fields->{'mobile_content'}[0]);

			// $article_array['sub_level'] = 0;
			// if(addslashes($article->custom_fields->{'sub_level'}[0])) {
			// 	$article_array['sub_level'] = $article->custom_fields->{'sub_level'}[0];
			// }

			$uod = $this->updateOnDuplicate(self::WRITING,$article_array);
            // echo "uod: ".$uod;
		// }
		return true;
	}

	public function getWritingJSONFromWordpress($page,$category_name,$count) {
		// echo 'https://p1xeLBE4RD!8!:b055apPZ4you!@www.theanfieldwrap.com/api/get_category_posts/?page='.$page.'&count='.$count.'&category_name='.$category_name;
        $curl = curl_init();
		curl_setopt_array($curl, array(
		    CURLOPT_RETURNTRANSFER => 1,
		    CURLOPT_URL => 'https://www.theanfieldwrap.com/api/get_category_posts/?page='.$page.'&count='.$count.'&category_name=app+footie+featured-writing',
		));
		return curl_exec($curl);
    }

    public function getWritingFeedFromWordpress($page) {
        $json = $this->getWritingJSONFromWordpress($page,'footie',10);
        $json = json_decode($json);
		// var_dump($json);
		if($json->posts) {
			foreach($json->posts as $article) {
				// var_dump($post);
				$this->insertWritingFeedContentFromWordpress($article);
			}
			// $page = $page+1;
			// // echo "page: ".$page;
			// $this->getWritingFeedFromWordpress($page);
		}
		// echo "page: ".$page;
		// return true;
    }

	public function getWritingFeed($start,$limit = 25) {
		$limit = $limit;
		$start = $start -1;
		$page = $limit * $start;
		 $this->load->database();
        $this->db->select('*');
        $this->db->from(self::WRITING);
		$this->db->limit($limit,$page);
		$this->db->order_by('created_date','DESC');
        $query = $this->db->get();
        if($query->num_rows()>0) {

			$post_array = array();
			foreach($query->result() as $post) {
				$post_object = array();
				// $post_object['purchased'] = false;
				// $purchased = $this->wallet->checkIfTheUserHasAlreadyPurchasedThisPodcast($post->post_id);
				// if($purchased) {
				// 	$post_object['purchased'] = true;
				// }
				// $post_object['id'] = $post->id;
				$post_object['post_id'] = $post->post_id;
				$post_object['title'] = $post->title;
				$post_object['content'] = $post->content;
				// $post_object['excerpt'] = $post->excerpt;
				$post_object['created_date'] = $post->created_date;
				// $post_object['modified_date'] = $post->modified_date;
				$post_object['featured'] = (bool)$post->featured;
				$post_object['author'] = $post->author;
				$post_object['thumbnail_image'] = $post->thumbnail_image;
				$post_object['medium_image'] = $post->medium_image;
				$post_object['large_image'] = $post->large_image;
				// $post_object['sub_level'] = $post->sub_level;

				array_push($post_array,$post_object);
			}

            return $post_array;
        } else {
            return null;
        }
    }

	public function getArticleByID($post_id) {
		 $this->load->database();
        $this->db->select('*');
        $this->db->from(self::WRITING);
		$this->db->limit(1);
		$this->db->where('post_id',$post_id);
        $query = $this->db->get();
        if($query->num_rows()>0) {
			$post_array = array();
			$post = $query->row_array();
			$post_object = array();
			$post_object['post_id'] = $post['post_id'];
			$post_object['title'] = $post['title'];
			$post_object['content'] = $post['content'];
			$post_object['created_date'] = $post['created_date'];
			$post_object['featured'] = (bool)$post['featured'];
			$post_object['author'] = $post['author'];
			$post_object['thumbnail_image'] = $post['thumbnail_image'];
			$post_object['medium_image'] = $post['medium_image'];
			$post_object['large_image'] = $post['large_image'];
			// $post_object['sub_level'] = (int)$post['sub_level'];

            return $post_object;
        } else {
            return null;
        }
    }


	/* WRITING END ********************************************************************/

    public function updateOnDuplicate($table, $data ) {
         $this->load->database();
        if (empty($table) || empty($data)) return false;
        $duplicate_data = array();
        foreach($data AS $key => $value) {
            $duplicate_data[] = sprintf("%s='%s'", $key, $value);
        }
        $sql = sprintf("%s ON DUPLICATE KEY UPDATE %s", $this->db->insert_string($table, $data), implode(',', $duplicate_data));
        $dbq = $this->db->query($sql);
        // var_dump($data);
		if($this->db->insert_id()) {
			// echo $this->db->insert_id()." - ".$table;
			if($table == 'taw_feed_podcasts') {
				 $this->load->database();
		        $this->db->select('*');
		        $this->db->from(self::NOTIFICATIONS_LOG);
				$this->db->limit(1);
				$this->db->where('post_id =',$data['post_id']);
		        $query = $this->db->get();
		        if($query->num_rows() == 0) {
					$this->notifications->sendNewPodcastNotificationToUsers($data['post_id']);
				}
			} else if($table == 'taw_feed_writing') {
				 $this->load->database();

		        $this->db->select('*');
		        $this->db->from(self::NOTIFICATIONS_LOG);
				$this->db->limit(1);
				$this->db->where('post_id =',$data['post_id']);
		        $query = $this->db->get();
		        if($query->num_rows() == 0) {
					$this->notifications->sendNewArticleNotificationToUsers($data['post_id']);
				}
			} else if($table == 'taw_feed_videos') {
				 $this->load->database();
		        $this->db->select('*');
		        $this->db->from(self::NOTIFICATIONS_LOG);
				$this->db->limit(1);
				$this->db->where('post_id =',$data['post_id']);
		        $query = $this->db->get();
		        if($query->num_rows() == 0) {
					$this->notifications->sendNewVideoNotificationToUsers($data['post_id']);
				}
			}
		}
        // var_dump($this->db->conn_id->error_list);
        return $this->db->insert_id();
    }

	/* PODCASTS START *****************************************************************/

	public function getPodcastByID($post_id) {
		 $this->load->database();
        $this->db->select('*');
        $this->db->from(self::PODCASTS);
		$this->db->limit(1);
		$this->db->where('post_id',$post_id);
        $query = $this->db->get();
        if($query->num_rows()>0) {
			$post = $query->row_array();
			$post_array = array();
			$post_object = array();
			$post_object['purchased'] = false;
			$purchased = $this->wallet->checkIfTheUserHasAlreadyPurchasedThisPodcast($post['post_id']);
			if($purchased) {
				$post_object['purchased'] = true;
			}
			$post_object['post_id'] = $post['post_id'];
			$post_object['title'] = $post['title'];
			$post_object['content'] = $post['content'];
			$post_object['created_date'] = $post['created_date'];
			$post_object['premium'] = (bool)$post['premium'];
			$post_object['podcast_full_url'] = $post['podcast_full_url'];
			$post_object['thumbnail_image'] = $post['thumbnail_image'];
			$post_object['medium_image'] = $post['medium_image'];
			$post_object['large_image'] = $post['large_image'];
			$post_object['podcast_length'] = $post['podcast_length'];
			$post_object['cost'] = (int)$post['credits'];
			$post_object['sub_level'] = (int)$post['sub_level'];

            return $post_object;
        } else {
            return null;
        }
    }

	public function insertFeedContentFromWordpress($podcast) {
		// var_dump($data->data);
		// foreach($post as $podcast) {
			// echo "id - ".$podcast->id;
			$article_array = array();
			$article_array['post_id'] = $podcast->id;
			$article_array['title'] = addslashes(html_entity_decode($podcast->title));
			$article_array['content'] = addslashes($podcast->content);
			$article_array['excerpt'] = addslashes($podcast->excerpt);
			$article_array['created_date'] = $podcast->date;
			$article_array['modified_date'] = $podcast->modified;

			$article_array['premium'] = 1;
			foreach($podcast->tags as $tag) {
				if($tag->id == 1491) {
					$article_array['premium'] = 0;
				}
			}
			if(isset($podcast->custom_fields->{'cost'}[0])) {
				$article_array['credits'] = $podcast->custom_fields->{'cost'}[0];
			}
			$article_array['enclosure'] = "";
			if(isset($podcast->custom_fields->enclosure[0])) {
				$article_array['enclosure'] = addslashes($podcast->custom_fields->enclosure[0]);
			}
			$article_array['podcast_full_url'] = "";
			if(isset($podcast->custom_fields->{'podcast-audio-file'}[0])) {
				$article_array['podcast_full_url'] = addslashes($podcast->custom_fields->{'podcast-audio-file'}[0]);
			}
			$article_array['podcast_length'] = "";
			if(isset($podcast->custom_fields->{'podcast-length-minutes'}[0])) {
				$article_array['podcast_length'] = addslashes($podcast->custom_fields->{'podcast-length-minutes'}[0]);
			}
			// $article_array['enclosure'] = addslashes($podcast->custom_fields->enclosure[0]);
			// $article_array['podcast_full_url'] = addslashes($podcast->custom_fields->{'podcast-audio-file'}[0]);
			// $article_array['podcast_length'] = addslashes($podcast->custom_fields->{'podcast-length-minutes'}[0]);

			if(isset($podcast->thumbnail_images->thumbnail->url)) {
				$article_array['thumbnail_image'] = addslashes($podcast->thumbnail_images->thumbnail->url);
			}
			if(isset($podcast->thumbnail_images->medium->url)) {
				$article_array['medium_image'] = addslashes($podcast->thumbnail_images->medium->url);
			}
			if(isset($podcast->thumbnail_images->large->url)) {
				$article_array['large_image'] = addslashes($podcast->thumbnail_images->large->url);
			}
			$article_array['content'] = "";
			if(isset($podcast->custom_fields->{'mobile_content'}[0])) {
				$article_array['content'] = addslashes($podcast->custom_fields->{'mobile_content'}[0]);
			}
			// $article_array['content'] = addslashes($podcast->custom_fields->{'mobile_content'}[0]);

			$article_array['sub_level'] = 0;
			if(isset($podcast->custom_fields->{'sub_level'}[0])) {
				$article_array['sub_level'] = addslashes($podcast->custom_fields->{'sub_level'}[0]);
				if($article_array['sub_level'] == 0) {
					$article_array['premium'] = 0;
					$article_array['credits'] = 0;
				} else {

				}
			}

			$this->updateOnDuplicate(self::PODCASTS,$article_array);
		// }
		return true;
	}

    public function getJSONFromWordpress($page,$category_id,$category_id_two,$count) {
        $curl = curl_init();
		curl_setopt_array($curl, array(
		    CURLOPT_RETURNTRANSFER => 1,
		    CURLOPT_URL => 'https://www.theanfieldwrap.com/api/get_category_posts/?page='.$page.'&count='.$count.'&category_name=app+player',
		));
		return curl_exec($curl);
    }

    public function getPodcastFeedFromWordpress($page) {
        $json = $this->getJSONFromWordpress($page,1230,2440,25);
        $json = json_decode($json);
		// echo $json->posts;
		if($json->posts) {
			foreach($json->posts as $podcast) {
				// var_dump($post);
				$this->insertFeedContentFromWordpress($podcast);
			}
			// $page = $page+1;
			// // echo "page: ".$page;
			// $this->getPodcastFeedFromWordpress($page);
		}
		// echo "page: ".$page;
		return true;
    }

	public function getPodcastFeed($start,$limit = 25) {
		// $limit = $limit;
		$start = $start -1;
		// $page = @($limit / $start);
		$page = $limit * $start;
		 $this->load->database();
        $this->db->select('*');
        $this->db->from(self::PODCASTS);
		$this->db->limit($limit,$page);
		$this->db->order_by('created_date','DESC');
        $query = $this->db->get();
        if($query->num_rows()>0) {
			$post_array = array();
			foreach($query->result() as $post) {
				$post_object = array();
				$post_object['purchased'] = false;
				$purchased = $this->wallet->checkIfTheUserHasAlreadyPurchasedThisPodcast($post->post_id);
				if($purchased) {
					$post_object['purchased'] = true;
				}
				// $post_object['id'] = $post->id;
				$post_object['post_id'] = $post->post_id;
				$post_object['title'] = $post->title;
				$post_object['content'] = $post->content;
				// $post_object['excerpt'] = $post->excerpt;
				$post_object['created_date'] = $post->created_date;
				// $post_object['modified_date'] = $post->modified_date;
				$post_object['premium'] = (bool)$post->premium;
				// $post_object['enclosure'] = $post->enclosure;
				$post_object['podcast_full_url'] = $post->podcast_full_url;
				$post_object['thumbnail_image'] = $post->thumbnail_image;
				$post_object['medium_image'] = $post->medium_image;
				$post_object['large_image'] = $post->large_image;
				$post_object['podcast_length'] = $post->podcast_length;
				$post_object['cost'] = (int)$post->credits;
				$post_object['sub_level'] = $post->sub_level;

				array_push($post_array,$post_object);
			}


            return $post_array;
        } else {
            return null;
        }
    }

	/* VIDEOS START *****************************************************************/

	public function getVideoByID($post_id) {
		 $this->load->database();
        $this->db->select('*');
        $this->db->from(self::VIDEOS);
		$this->db->limit(1);
		$this->db->where('post_id',$post_id);
        $query = $this->db->get();
        if($query->num_rows()>0) {
			$post = $query->row_array();
			$post_object = array();
			$post_object['purchased'] = false;
			$purchased = $this->wallet->checkIfTheUserHasAlreadyPurchasedThisPodcast($post['post_id']);
			if($purchased) {
				$post_object['purchased'] = true;
			}
			$post_object['post_id'] = $post['post_id'];
			$post_object['title'] = $post['title'];
			$post_object['content'] = $post['content'];
			$post_object['created_date'] = $post['created_date'];
			$post_object['cost'] = (int)$post['cost'];
			$post_object['video_url'] = $post['video_url'];
			$post_object['thumbnail_image'] = $post['thumbnail_image'];
			$post_object['medium_image'] = $post['medium_image'];
			$post_object['large_image'] = $post['large_image'];
			$post_object['type'] = $post['type'];
			$post_object['sub_level'] = $post['sub_level'];

            return $post_object;
        } else {
            return null;
        }
    }

	public function insertVideoFeedContentFromWordpress($video) {
		$article_array = array();
		$article_array['post_id'] = $video->id;
		$article_array['title'] = addslashes(html_entity_decode($video->title));
		$article_array['content'] = addslashes($video->content);
		$article_array['excerpt'] = addslashes($video->excerpt);
		$article_array['created_date'] = $video->date;
		$article_array['modified_date'] = $video->modified;
		if(isset($video->custom_fields->{'video_price'}[0])) {
			$article_array['cost'] = $video->custom_fields->{'video_price'}[0];
		}
		$article_array['video_url'] = addslashes($video->custom_fields->{'video_url'}[0]);
		if(isset($video->thumbnail_images->thumbnail->url)) {
			$article_array['thumbnail_image'] = addslashes($video->thumbnail_images->thumbnail->url);
		}
		if(isset($video->thumbnail_images->medium->url)) {
			$article_array['medium_image'] = addslashes($video->thumbnail_images->medium->url);
		}
		if(isset($video->thumbnail_images->large->url)) {
			$article_array['large_image'] = addslashes($video->thumbnail_images->large->url);
		}
		$article_array['content'] = addslashes($video->custom_fields->{'mobile_content'}[0]);
		$article_array['type'] = 'hosted';

		$article_array['sub_level'] = 0;
		if(isset($video->custom_fields->{'sub_level'}[0])) {
			$article_array['sub_level'] = $video->custom_fields->{'sub_level'}[0];
		}

		$this->updateOnDuplicate(self::VIDEOS,$article_array);
		return true;
	}

    public function getVideosJSONFromWordpress($page,$category_id,$category_id_two,$count) {
        $curl = curl_init();
		curl_setopt_array($curl, array(
		    CURLOPT_RETURNTRANSFER => 1,
		    CURLOPT_URL => 'https://www.theanfieldwrap.com/api/get_category_posts/?page='.$page.'&count='.$count.'&category_name=app+video',
		));
		return curl_exec($curl);
    }
	// youtube: AIzaSyDA45he0ahYKrGyiE-oz6gpK_jDQidd3nk

    public function getVideosFeedFromWordpress($page) {
        $json = $this->getVideosJSONFromWordpress($page,1230,2440,25);
        $json = json_decode($json);
		// echo $json->posts;
		if($json->posts) {
			foreach($json->posts as $podcast) {
				// var_dump($post);
				$this->insertVideoFeedContentFromWordpress($podcast);
			}
			$page = $page+1;
			// echo "page: ".$page;
			$this->getVideosFeedFromWordpress($page);
		}
		// echo "page: ".$page;
		// return true;
    }

	public function getVideosFeed($start,$limit = 25) {
		// $limit = $limit;
		$start = $start -1;
		// $page = @($limit / $start);
		$page = $limit * $start;
		 $this->load->database();
        $this->db->select('*');
        $this->db->from(self::VIDEOS);
		$this->db->limit($limit,$page);
		$this->db->where('type != ', 'youtube');
		$this->db->order_by('created_date','DESC');
        $query = $this->db->get();
        if($query->num_rows()>0) {
			$post_array = array();
			foreach($query->result() as $post) {
				$post_object = array();
				$post_object['purchased'] = false;
				$purchased = $this->wallet->checkIfTheUserHasAlreadyPurchasedThisPodcast($post->post_id);
				if($purchased) {
					$post_object['purchased'] = true;
				}
				// $post_object['id'] = $post->id;
				$post_object['post_id'] = $post->post_id;
				$post_object['title'] = $post->title;
				$post_object['content'] = $post->content;
				// $post_object['excerpt'] = $post->excerpt;
				$post_object['created_date'] = $post->created_date;
				// $post_object['modified_date'] = $post->modified_date;
				$post_object['cost'] = (int)$post->cost;
				$post_object['video_url'] = $post->video_url;
				$post_object['thumbnail_image'] = $post->thumbnail_image;
				$post_object['medium_image'] = $post->medium_image;
				$post_object['large_image'] = $post->large_image;
				$post_object['type'] = $post->type;
				$post_object['sub_level'] = $post->sub_level;
				array_push($post_array,$post_object);
			}

            return $post_array;
        } else {
            return null;
        }
    }
}
