<?php
/**
* Created by PhpStorm.
* User: lambasoft
* Date: 8/29/17
* Time: 8:00 AM
*/
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class CMS_model extends CI_Model{
	public function __construct(){
		parent::__construct();
		$this->load->database();
	}

	public function getCategories($ids = array()){
		$query = $this->db->select("*")
		->where("link_category_id",0)
		->order_by("pos","ASC");

		if(!empty($ids)){
			$query = $query->where_in("id",$ids);
		}

		$query = $query->get('categories');
		return $query->result_array();
	}


	public function getCategory($id){
		$id = (int)$id;
		if (empty($id)){
			return false;
		}
		$query = $this->db->select("*")
		->where("id",$id);

		
		$query = $query->get('categories');
		return $query->result_array();
	}

	public function getSchools(){
		$query = $this->db->select("*")->order_by("name", "ASC"); 
		$query = $query->get('schools');
		return $query->result_array();

	}

	public function getVideosByCategories($categories = array()){
		if(!empty($categories)){
			$query = $this->db->select("videos.*,videos_categories.link_category_id")
			->from("videos")
			->join("videos_categories","videos_categories.link_video_id = videos.id")
			->where_in("videos_categories.link_category_id",$categories)
			->group_by("videos_categories.link_video_id")
			->get();
			$results = $query->result_array();

			foreach ($results AS $k=>$r) {
				$results[$k]['seo-title'] = $this->seoUrl($r['title']);
			}
			return $results;
		}
		return array();
	}

	public function getVideosBySearch($search = ""){
		$query = $this->db->select("videos.*,videos_categories.link_category_id")
		->from("videos")
		->join("videos_categories","videos_categories.link_video_id = videos.id")
		->like("title",$search)
		->or_like("description",$search)
		->group_by("videos_categories.link_video_id")
		->get();

		$results = $query->result_array();

		foreach ($results AS $k=>$r) {
			$results[$k]['seo-title'] = $this->seoUrl($r['title']);
		}
		return $results;
	}


	public function getVideos($ids = array(),$limit = 15){
		$query = $this->db->select("videos.*")
		->from("videos")
		->limit($limit);

		if(!empty($ids)){
			$query =  $this->db->where_in("id",$ids);
		}

		$query = $this->db->get();

		$results = $query->result_array();

		foreach ($results AS $k=>$r) {
			$results[$k]['seo-title'] = $this->seoUrl($r['title']);
		}
		return $results;

	}

	public function getVideo($id){
		$query = $this->db->select("videos.*,
			authors.id as 'author_id',
			authors.name as 'author_name',
			authors.image as 'author_image',
			authors.bio as 'author_bio',
			authors.resume as 'author_resume',
			authors.email as 'author_email'
		")
		->from("videos")
		->join("authors","authors.id = videos.link_author_id")
		->where("videos.id",$id)
		->limit(1)
		->get();
		return $query->row_array();
	}

	public function getVideoCategories($video_id){
		$query = $this->db->select("categories.*")
		->from("videos_categories")
		->join("categories","categories.id = videos_categories.link_category_id")
		->where("videos_categories.link_video_id",$video_id)
		->get();
		return $query->result_array();
	}

	public function getVideoTags($video_id){
		$query = $this->db->select("tags.*")
		->from("videos_tags")
		->join("tags","tags.id = videos_tags.link_tag_id")
		->where("videos_tags.link_video_id",$video_id)
		->get();
		return $query->result_array();
	}


	public function getVideosPick(){
		$query = $this->db->select("*")
		->from("videos_pick")
		->join("videos","videos.id = videos_pick.link_video_id")
		->get();
		return $query->result_array();
	}

	public function getPageSliders($page){
		$result = array();
		$cpageID = $this->isCPage($page);
		if($cpageID){
			$slidersID = $this->getSlidersID($cpageID);

			foreach ($slidersID as $sliderID) {
				$sliderINFO = $this->getSliderInfo($sliderID['id']);
				$result[$sliderINFO['title']] = $this->getSliderVideos($sliderID['id']);
			}
			return  $result;
		}
		return FALSE;
	}

	private function isCPage($page){
		$query = $this->db->select("id")->from("cpages")->where("name",$page)->limit(1)->get();
		return $query->row_array()['id'];
	}

	private function getSlidersID($cpage_id){
		$query = $this->db->select("id")->where("link_cpage_id",$cpage_id)->get("sliders");
		return $query->result_array();
	}

	private function getSliderInfo($sliderID){
		$query = $this->db->select("*")->from("sliders")->where("id",$sliderID)->limit(1)->get();
		return $query->row_array();
	}

	private function getSliderVideos($sliderID){
		$query = $this->db->select("videos.*")
		->from("sliders_videos")
		->join("videos","sliders_videos.link_video_id = videos.ID")
		->where("sliders_videos.link_slider_id", $sliderID)
		->order_by("pos","ASC")
		->get();

		$results = $query->result_array();

		foreach ($results AS $k=>$r) {
			$results[$k]['seo-title'] = $this->seoUrl($r['title']);
		}
		return $results;
	}

	public function isVideo($id){
		$query = $this->db->select("id")->where("id",(int)$id)->limit(1)->get("videos");
		return ($query->num_rows() > 0);
	}

	private function isUserLikedVideo($userID, $videoID){
		$query = $this->db->select("id")
		->where("link_user_id",(int)$userID)
		->where("link_video_id",(int)$videoID)
		->limit(1)
		->get("users_videos_likes");
		return ($query->num_rows() > 0);
	}

	private function isUserWatchLaterVideo($userID, $videoID){
		$query = $this->db->select("id")
		->where("link_user_id",(int)$userID)
		->where("link_video_id",(int)$videoID)
		->limit(1)
		->get("users_videos_later");
		return ($query->num_rows() > 0);
	}

	public function userLikeVideo($userID, $videoID){
		if(!$this->isUserLikedVideo($userID,$videoID)){
			$data = array(
				'link_user_id' => $userID,
				'link_video_id' => $videoID
			);

			$this->db->insert('users_videos_likes', $data);
		}
		return TRUE;
	}


	private function isUserJobShadowed($userID,$videoID,$recently = TRUE){
		$this->db->select("id")->from("job_shadows")
		->where("link_user_id",$userID)
		->where("link_video_id",$videoID);

		if($recently){
			$this->db->where("added <= DATE_SUB(NOW(),INTERVAL 5 MINUTE)");
		}

		$query = $this->db->get();

		return ($query->num_rows() > 0) ? TRUE : FALSE;
	}

	public function addJobShadow($videoID,$userID,$message){
		if(!$this->isUserJobShadowed($userID,$videoID, TRUE)){
			$data = array(
				'link_user_id' => $userID,
				'link_video_id' => $videoID,
				'message' => $message,
				"added" => date('Y-m-d H:i:s')
			);

			$this->db->insert('job_shadows', $data);
			return TRUE;
		}

		return FALSE;
	}

	public function userWatchLaterVideo($userID, $videoID){
		if(!$this->isUserWatchLaterVideo($userID,$videoID)){
			$data = array(
				'link_user_id' => $userID,
				'link_video_id' => $videoID
			);

			$this->db->insert('users_videos_later', $data);
		}
		return TRUE;
	}

	public function getUserLikedVideos($user_id){
		$query = $this->db->select("videos.*,videos_categories.link_category_id")
		->join("videos","videos.id = users_videos_likes.link_video_id")
		->join("videos_categories","videos_categories.link_video_id = videos.id")
		->from("users_videos_likes")
		->where("link_user_id",$user_id)
		->group_by("videos.id")
		->get();
		return $query->result_array();
	}
	public function getUserSavedVideos($user_id){
		$query = $this->db->select("videos.*,videos_categories.link_category_id")
		->join("videos","videos.id = users_videos_later.link_video_id")
		->join("videos_categories","videos_categories.link_video_id = videos.id")
		->from("users_videos_later")
		->where("link_user_id",$user_id)
		->group_by("videos.id")
		->get();
		return $query->result_array();
	}

	public function getPage($slug){
		$query = $this->db->select("*")->from("pages")->where("slug",$slug)->limit(1)->get();
		return $query->row_array();
	}


	public function contactUS($email,$name,$message){
		$query = $this->db->insert(
			"contact_messages",
			array(
				"name" => $name,
				"email" => $email,
				"message" => $message,
				"added" => date('Y-m-d H:i:s')
			)
		);

		return TRUE;
	}

	public function requestCareer($career,$user_id){
		$query = $this->db->insert(
			"career_requests",
			array(
				"name" => $career,
				"link_user_id" => $user_id,
				"added" => date('Y-m-d H:i:s')
			)
		);

		return TRUE;
	}

	public function userRateVideo($userID, $videoID, $rating){
		// if(!$this->isUserRatedVideo($userID, $videoID)){
		$this->deleteUserRating($userID,$videoID);
		$data = array(
			'link_user_id' => $userID,
			'link_video_id' => $videoID,
			'rating' => $rating
		);

		return $this->db->insert('videos_ratings', $data);
		//}

		//return FALSE;
	}

	private function isUserRatedVideo($userID, $videoID){
		$count = $this->db->select("id")
		->where("link_video_id",$videoID)
		->where("link_user_id",$userID)
		->where("deleted",0)
		->from("videos_ratings")
		->count_all_results();

		return ($count > 0 )? TRUE : FALSE;
	}

	private function deleteUserRating($userID, $videoID){
		$this->db->set("deleted", 1)
		->where("link_video_id",$videoID)
		->where("link_user_id",$userID)
		->update("videos_ratings");

		return TRUE;
	}

	public function getVideoRating($videoID){
		$query = $this->db->select("ROUND(ROUND(AVG(rating) * 2) / 2, 1) as rating")->from("videos_ratings")->where("link_video_id",$videoID)->where("deleted",0)->limit(1)->get();
		return $query->row_array()['rating'];
	}

	public function isUserExist($where){
		$count = $this->db->select("id")
		->from("my_users")
		->where($where)
		->limit(1)
		->count_all_results();
		return ($count > 0 )? TRUE : FALSE;
	}


	public function getViewsLimit(){
		$query = $this->db->select("value")
		->from("options")
		->where("key='max_views'")
		->limit(1)
		->get();
		return $query->result_array();
	}


	public function validateSchoolCode($code){
		$code = addslashes($code);
		$count = $this->db->select("id")
		->from("school_codes")
		->where("code='$code'")
		->limit(1)
		->count_all_results();

		$query = $this->db->insert(
			"school_code_requests",
			array(
				"code" => $code,
				"added" => date('Y-m-d H:i:s')
			)
		);       

		return ($count > 0 )? TRUE : FALSE;
	}

	public function seoUrl($str, $options = array()) {
		// Make sure string is in UTF-8 and strip invalid UTF-8 characters
		$str = mb_convert_encoding((string)$str, 'UTF-8', mb_list_encodings());

		$defaults = array(
			'delimiter' => '-',
			'limit' => null,
			'lowercase' => true,
			'replacements' => array(),
			'transliterate' => false,
		);

		// Merge options
		$options = array_merge($defaults, $options);

		$char_map = array(
			// Latin
			'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Æ' => 'AE', 'Ç' => 'C',
			'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I',
			'Ð' => 'D', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ő' => 'O',
			'Ø' => 'O', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ű' => 'U', 'Ý' => 'Y', 'Þ' => 'TH',
			'ß' => 'ss',
			'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'ae', 'ç' => 'c',
			'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i',
			'ð' => 'd', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ő' => 'o',
			'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ü' => 'u', 'ű' => 'u', 'ý' => 'y', 'þ' => 'th',
			'ÿ' => 'y',

			// Latin symbols
			'©' => '(c)',

			// Greek
			'Α' => 'A', 'Β' => 'B', 'Γ' => 'G', 'Δ' => 'D', 'Ε' => 'E', 'Ζ' => 'Z', 'Η' => 'H', 'Θ' => '8',
			'Ι' => 'I', 'Κ' => 'K', 'Λ' => 'L', 'Μ' => 'M', 'Ν' => 'N', 'Ξ' => '3', 'Ο' => 'O', 'Π' => 'P',
			'Ρ' => 'R', 'Σ' => 'S', 'Τ' => 'T', 'Υ' => 'Y', 'Φ' => 'F', 'Χ' => 'X', 'Ψ' => 'PS', 'Ω' => 'W',
			'Ά' => 'A', 'Έ' => 'E', 'Ί' => 'I', 'Ό' => 'O', 'Ύ' => 'Y', 'Ή' => 'H', 'Ώ' => 'W', 'Ϊ' => 'I',
			'Ϋ' => 'Y',
			'α' => 'a', 'β' => 'b', 'γ' => 'g', 'δ' => 'd', 'ε' => 'e', 'ζ' => 'z', 'η' => 'h', 'θ' => '8',
			'ι' => 'i', 'κ' => 'k', 'λ' => 'l', 'μ' => 'm', 'ν' => 'n', 'ξ' => '3', 'ο' => 'o', 'π' => 'p',
			'ρ' => 'r', 'σ' => 's', 'τ' => 't', 'υ' => 'y', 'φ' => 'f', 'χ' => 'x', 'ψ' => 'ps', 'ω' => 'w',
			'ά' => 'a', 'έ' => 'e', 'ί' => 'i', 'ό' => 'o', 'ύ' => 'y', 'ή' => 'h', 'ώ' => 'w', 'ς' => 's',
			'ϊ' => 'i', 'ΰ' => 'y', 'ϋ' => 'y', 'ΐ' => 'i',

			// Turkish
			'Ş' => 'S', 'İ' => 'I', 'Ç' => 'C', 'Ü' => 'U', 'Ö' => 'O', 'Ğ' => 'G',
			'ş' => 's', 'ı' => 'i', 'ç' => 'c', 'ü' => 'u', 'ö' => 'o', 'ğ' => 'g',

			// Russian
			'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D', 'Е' => 'E', 'Ё' => 'Yo', 'Ж' => 'Zh',
			'З' => 'Z', 'И' => 'I', 'Й' => 'J', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'О' => 'O',
			'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C',
			'Ч' => 'Ch', 'Ш' => 'Sh', 'Щ' => 'Sh', 'Ъ' => '', 'Ы' => 'Y', 'Ь' => '', 'Э' => 'E', 'Ю' => 'Yu',
			'Я' => 'Ya',
			'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'yo', 'ж' => 'zh',
			'з' => 'z', 'и' => 'i', 'й' => 'j', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o',
			'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c',
			'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sh', 'ъ' => '', 'ы' => 'y', 'ь' => '', 'э' => 'e', 'ю' => 'yu',
			'я' => 'ya',

			// Ukrainian
			'Є' => 'Ye', 'І' => 'I', 'Ї' => 'Yi', 'Ґ' => 'G',
			'є' => 'ye', 'і' => 'i', 'ї' => 'yi', 'ґ' => 'g',

			// Czech
			'Č' => 'C', 'Ď' => 'D', 'Ě' => 'E', 'Ň' => 'N', 'Ř' => 'R', 'Š' => 'S', 'Ť' => 'T', 'Ů' => 'U',
			'Ž' => 'Z',
			'č' => 'c', 'ď' => 'd', 'ě' => 'e', 'ň' => 'n', 'ř' => 'r', 'š' => 's', 'ť' => 't', 'ů' => 'u',
			'ž' => 'z',

			// Polish
			'Ą' => 'A', 'Ć' => 'C', 'Ę' => 'e', 'Ł' => 'L', 'Ń' => 'N', 'Ó' => 'o', 'Ś' => 'S', 'Ź' => 'Z',
			'Ż' => 'Z',
			'ą' => 'a', 'ć' => 'c', 'ę' => 'e', 'ł' => 'l', 'ń' => 'n', 'ó' => 'o', 'ś' => 's', 'ź' => 'z',
			'ż' => 'z',

			// Latvian
			'Ā' => 'A', 'Č' => 'C', 'Ē' => 'E', 'Ģ' => 'G', 'Ī' => 'i', 'Ķ' => 'k', 'Ļ' => 'L', 'Ņ' => 'N',
			'Š' => 'S', 'Ū' => 'u', 'Ž' => 'Z',
			'ā' => 'a', 'č' => 'c', 'ē' => 'e', 'ģ' => 'g', 'ī' => 'i', 'ķ' => 'k', 'ļ' => 'l', 'ņ' => 'n',
			'š' => 's', 'ū' => 'u', 'ž' => 'z'
		);

		// Make custom replacements
		$str = preg_replace(array_keys($options['replacements']), $options['replacements'], $str);

		// Transliterate characters to ASCII
		if ($options['transliterate']) {
			$str = str_replace(array_keys($char_map), $char_map, $str);
		}

		// Replace non-alphanumeric characters with our delimiter
		$str = preg_replace('/[^\p{L}\p{Nd}]+/u', $options['delimiter'], $str);

		// Remove duplicate delimiters
		$str = preg_replace('/(' . preg_quote($options['delimiter'], '/') . '){2,}/', '$1', $str);

		// Truncate slug to max. characters
		$str = mb_substr($str, 0, ($options['limit'] ? $options['limit'] : mb_strlen($str, 'UTF-8')), 'UTF-8');

		// Remove delimiter from ends
		$str = trim($str, $options['delimiter']);

		return $options['lowercase'] ? mb_strtolower($str, 'UTF-8') : $str;
	}

}