<?php 
require_once("lib/php/include/dbPDO.php");
require_once('memcache.php');

class Category_model extends lib_Memcache
{

	function __construct()
	{
		$this->db = CommonPDOConnector::connect('MasterLP');
	}

	public function getCategories($limit = true)
	{
		$ttl = 60 * 60 * 24 * 30; // 30 days
		$results = false;
		if ($limit == true) {
			$key = md5('getCategories');
		} else {
			$key = md5('getAllCategories');
		}
		// $results = $this->cache->get($key);
		$results = lib_Memcache::mGet()->get($key);
		if ($results === false) {
			$query = $this->db->query("select distinct cat_title from localpages_cat where cat_title != '';");
			$query_result = $query->fetchAll(PDO::FETCH_ASSOC);
			if (count($query_result) > 0) {
				foreach ($query_result as $row) {
					if (!$limit)
						$subcats = $this->db->query("select distinct cat_name from localpages_cat where cat_title = '" . addslashes($row['cat_title']) . "' order by top_category desc;");
					else
						$subcats = $this->db->query("select distinct cat_name from localpages_cat where cat_title = '" . addslashes($row['cat_title']) . "' order by top_category desc limit 15;");

					foreach ($subcats->fetchAll(PDO::FETCH_ASSOC) as $subcat) {
						$results[$row['cat_title']][] = $subcat;
					}
				}
				// $this->cache->save($key, $results, $ttl);
				lib_Memcache::mGet()->set($key,$results, 0, $ttl);
				return $results;
			} else {
				return false;
			}
		}
		return $results;
	}

	public function getSubCategories($subcat)
	{
		$key = md5('getSubCategories' . $subcat);
		$ttl = 60 * 60 * 24 * 30; // 30 days

		$results = lib_Memcache::mGet()->get($key);

		if ($results === false) {
			$query = $this->db->query("select distinct cat_name from localpages_cat where cat_title = '" . addslashes($subcat) . "' order by top_category desc;");
			$query_result = $query->fetchAll(PDO::FETCH_ASSOC);
			if (count($query_result) > 0) {
				foreach ($query_result as $row) {
					$results[] = $row['cat_name'];
				}
				lib_Memcache::mGet()->set($key, $results,0, $ttl);
				return $results;
			} else {
				return false;
			}
		}

		return $results;
	}

	public function getCategoryDescription($search)
	{
		$key = md5('getCategoryDescription__' . $search);
		$ttl = 60 * 60 * 24 * 10; // 30 days

		$results = lib_Memcache::mGet()->get($key);
		
		if ($results === false) {
			$query = $this->db->query("select * from localpages_cat where cat_title like '" . addslashes($search) . "%' or cat_name like '" . addslashes($search) . "%' order by rand() limit 1");
			$query_result = $query->fetchAll(PDO::FETCH_ASSOC);
			if (count($query_result) > 0) {
				foreach ($query_result as $row) {
					$results[] = $row;
				}
				lib_Memcache::mGet()->set($key, $results[0],0,$ttl);
				return $results[0];
			} else {
				return false;
			}
		}

		return $results;
	}

	public function getSearchCategory($search)
	{
		$query = $this->db->query("select distinct cat_title, cat_name, img1 from localpages_cat where cat_title like '" . addslashes($search) . "%' or cat_name like '" . addslashes($search) . "%' order by rand() limit 5");
		$query_result = $query->fetchAll(PDO::FETCH_ASSOC);
		if (count($query_result) > 0) {
			foreach ($query_result as $row) {
				$results[] = $row;
			}
			return $results;
		} else {
			return false;
		}
	}
	public function GetCategoryCount($search_query) {
		if (!$search_query) {
			return 0;
		}

		// Replacing and from search string as we have added it manually
		$search_query = str_replace('and', '', $search_query);
		$search_query = str_replace('-', ' ', $search_query);
		$terms = explode(' ', trim($search_query));
		$like1 = '';
		foreach($terms as $term) {
			if(strlen($term) >= 3 && !in_array($term, $this->stopwords)) {
				$like1 .= 'bname like \'%'.$term.'%\' or ';
			}
		}
		$like1 = rtrim($like1, ' or ');

		$terms = explode(' ', trim($search_query));
		$like2 = '';
		foreach($terms as $term) {
			if(strlen($term) >= 3 && !in_array($term, $this->stopwords)) {
				$like2 .= 'keywords like \'%'.$term.'%\' or ';
			}
		}
		$like2 = rtrim($like2, ' or ');

		$whereQuery = " WHERE duplicate=0 and ( (bname like '%$search_query%') ";
		if($like1) {
			$whereQuery .= " or ($like1) ";
		}

		if($like2) {
			$whereQuery .= " or ($like2) ";
		}
		$whereQuery .= " ) ";

		// Get the total result count
		$totalQuery = "select SQL_NO_CACHE count(*) as total from local_pages_lat_lon_updated $whereQuery limit 1";

		// Intentionally loading db object to perform heavy duty operation
		$result = $this->db->query($totalQuery);

		if(!$result) {
//			throw new \Exception(__CLASS__ . ': ' . $this->db->_error_number() . ': ' . $this->db->_error_message());
			return 0;
		}

		$totalResult = $result->fetchAll(PDO::FETCH_ASSOC);
		$result_total = $totalResult[0]['total'];

		return (int) $result_total;
	}
}
