<?php
/**
 * Search Controller
 */
class Search extends Controller
{
    /**
     * Process
     */
    public function process()
    {    

		$AuthUser		= $this->getVariable("AuthUser");
		$Route			= $this->getVariable("Route");
        $Settings       = $this->getVariable("Settings");
        $isValid        = $this->getVariable("isValid");

        $new    = array(Input::cleaner(mb_convert_case(str_replace('+', ' ', tagger($Route->params->q,true)), MB_CASE_TITLE, "UTF-8")));
        $old    = array('[name]');

        $Config['title']        = trim(str_replace($old, $new, trim(get($Settings,'data.search_title','seo'))));
        $Config['description']  = trim(str_replace($old, $new, trim(get($Settings,'data.search_description','seo'))));
        if(empty($Route->params->q)) {
            header('location:'.APP.'/404');
        }

        if(isset($_POST['_ACTION']) AND Input::cleaner($_POST['_ACTION']) == 'search' AND $isValid == 1) {
            if(empty(Input::cleaner($_POST['q'])) || Input::cleaner(mb_strlen($_POST['q'])) < 3 || Input::cleaner(mb_strlen($_POST['q'])) > 40) {
                $Notify['type']     = 'danger';
                $Notify['text']     = 'Your search query must be between 3 and 40 characters long'; 
                $this->notify($Notify);
                header('location:'.APP);
            } else {
                header("location: ".search(tagger($_POST['q']))); 
            }
        }
        $Where          = "WHERE posts.status = 1 AND ";
        if(isset($Route->params->q)) {  
            $Where          .= ' posts.title LIKE  "%'.Input::cleaner(tagger($Route->params->q,true)).'%" AND '; 
        }
        
        $Where = rtrim($Where,' AND '); 
        // Query 
        $TotalRecord        = $this->db->from(null,'
            SELECT 
            count(posts.id) as total 
            FROM `posts` '.$Where)
            ->total(); 
        $LimitPage          = $this->db->pagination($TotalRecord, get($Settings,'data.listing','customize') ? get($Settings,'data.listing','customize') : 76, PAGE_PARAM); 
   
        $Listings = $this->db->from(null,'
            SELECT 
            posts.*
            FROM `posts`  
            '.$Where.'
            '.(isset($_GET['sort']) ? 'ORDER BY posts DESC' : 'ORDER BY posts.id DESC').'
            LIMIT '.$LimitPage['start'].','.$LimitPage['limit'])
            ->all();
        $Pagination         = $this->db->showPagination(search(tagger($Route->params->q,true)).'?page=[page]');

     
        $this->setVariable("Config", $Config);   
        $this->setVariable("Listings", $Listings); 
        $this->setVariable("Pagination", $Pagination);   
        $this->setVariable("TotalRecord", $TotalRecord);     

        $this->view("search", "app");
    }
}