<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends MY_Controller {


	public function index($seg1 = false,$seg2 = false , $seg3=false,$seg4=false)
	{		
		
		$pages= array(
				config_item("slug_login"),
				config_item("slug_logout"),
				config_item("slug_user"),
				config_item("slug_register"),
				config_item("slug_pages"),				
				config_item("slug_contact"),				
				config_item("slug_last"),				
				config_item("slug_filter"),				
				config_item("slug_top")				
			);
		if(!$seg1)
		{
			$recent 				= $this->Admin->getTable("sites",array("completed" => 1),"updated desc",false,false,8);    
			 $this->DATA['recents'] 	= $recent->result();
			 $action = "home";		
		}					
			
		else	
		{
			if(in_array($seg1, $pages))
				$action = $seg1;
			else
				$action = 'review';
		}

		switch ($action) {
			case  config_item("slug_logout"):					
				$this->session->sess_destroy();				 	
				redirect(base_url(),'location');				
				exit;
				break;						
			case  config_item("slug_register"):					
				if($this->input->get("v"))
				{
					$this->validateAccount($this->input->get("v"));		
				}		

				$this->DATA['SEO']["title"] 		= __("Register");
			 	$this->DATA['SEO']["description"]  	= __("Create a FREE account.");

				break;			
			case  config_item("slug_login"):			
				$this->DATA['SEO']["title"] 		= __("Login");
			 	$this->DATA['SEO']["description"]  	= __("Login into your account.");			
				if($this->input->get("r") == '1')
				{
					$this->DATA['SEO']["title"] 		= __("Recovery Password");
			 		$this->DATA['SEO']["description"]  	= __("Recovery Your Password");	
					$action = 'recovery';
				}							
				break;						

			case  config_item("slug_pages"):					
				$page = $this->Admin->getTable("pages",array("slug" => $seg2));
				if($page->num_rows() == 0)
				{
					show_404();
				}
				$this->DATA['page'] = $page->row();
				$recent 				= $this->Admin->getTable("sites",array("completed" => 1),"updated desc",false,false,7);    
				 $this->DATA['recents'] 	= $recent->result();

				$this->DATA['SEO']["title"] 		= $this->DATA['page']->title;
			 	$this->DATA['SEO']["description"]  	= more(strip_tags($this->DATA['page']->text),200);

				$action = 'page';
				break;			
			
			case  config_item("slug_last"):					
				
				$data 				= $this->Admin->getTable("sites",array("completed" => 1),"updated desc",false,false,18);    
				$this->DATA['list'] 	= $data->result();
				$this->DATA['SEO']["title"] 		= __("Latest Updated Sites");

				$top 				= $this->Admin->getTable("sites",array("completed" => 1),"score desc",false,false,7);    
				$this->DATA['top'] 	= $top->result();

			 	

				$action = 'list';
				break;			
			

			case  config_item("slug_top"):					
				
				$data 				= $this->Admin->getTable("sites",array("completed" => 1),"score desc",false,false,18);    
				$this->DATA['list'] 	= $data->result();
				$this->DATA['SEO']["title"] 		= __("Latest Updated Sites");

				$recents 				= $this->Admin->getTable("sites",array("completed" => 1),"updated desc",false,false,7);    
				$this->DATA['recents'] 	= $recents->result();

			 	

				$action = 'list';
				break;	

			case  config_item("slug_filter"):	
						
				
				$seg2 = mb_strtolower($seg2);

				$filter = array("tag","ip","city","country","region","isp",config_item('slug_made_with'));
				if(!in_array($seg2, $filter))
				{

					show_404();
					die();
				}
				if(intval($seg4)==0)
					$seg4 = 1;
				if(intval($seg4)<=1)
					$offset = 0;
				else
					$offset = 12*intval($seg4);
				$limit 	= 13;
				$this->DATA['offset'] = $offset;
				$this->DATA['currentPage'] = $seg4;
				$this->DATA['filter'] = $seg2;
				$this->DATA['search'] = $seg3;
			
				$seg2_text 	= __(urldecode($seg2));
				$seg3 		= urldecode($seg3);

				if($seg2 == config_item('slug_made_with'))
				{

					$seg3 = _clean_special(urldecode($seg3));
					$seg3 = urldecode($seg3);
					$seg2_text = "Made With";
					$data 				= $this->db->query("SELECT {PRE}sites.*,{PRE}technologies.icon FROM {PRE}sites,{PRE}technologies WHERE {PRE}sites.url = {PRE}technologies.url AND {PRE}technologies.name = '$seg3' AND {PRE}sites.completed = 1 ORDER BY {PRE}sites.metaTitle ASC LIMIT $limit OFFSET $offset");    
					$this->DATA['list'] 	= $data->result();
					$this->DATA['title']		= __("Filter sites by ").ucfirst(mb_strtolower($seg2_text)).": <img  style='vertical-align: text-top ;height:40px;' src='".base_url()."assets/images/icons/".$this->DATA['list'][0]->icon."'> ".$seg3." - ".__("Page ").$seg4;

				}
				else
				{

					if($seg2 == 'ip' || $seg == 'tag')
					{
						
						if($seg == 'tag')
						{
							$seg3 = _clean_special(urldecode($seg3));
							$field = 'metaKeywords';
						}
						else
						{
							$field = "ip";
							$seg3 = _clean_ip(urldecode($seg3));
						}
						
						$data 				= $this->db->query("SELECT {PRE}sites.* FROM {PRE}sites WHERE  {PRE}sites.$field  LIKE '%$seg3%'  AND {PRE}sites.completed = 1 ORDER BY {PRE}sites.metaTitle ASC LIMIT $limit OFFSET $offset");    
					}
					else
					{
						
						
						$data 				= $this->Admin->getTable("sites",array("completed" => 1,$seg2 => urldecode($seg3)),"metaTitle asc",false,$offset,$limit);    
					}
					$this->DATA['list'] 	= $data->result();
					$this->DATA['title'] 		= __("Filter sites by ").ucfirst(mb_strtolower($seg2_text)).": ".$seg3." - ".__("Page ").$seg4;	

				}

				$this->DATA['SEO']["title"] 		= __("Filter sites by ").ucfirst(mb_strtolower($seg2_text)).": ".$seg3." - ".__("Page ").$seg4;		
				

				$recents 				= $this->Admin->getTable("sites",array("completed" => 1),"updated desc",false,false,7);    
				$this->DATA['recents'] 	= $recents->result();

				if(count($this->DATA['list'] ) == 0)
				{
					show_404();
					die();
				}

				$action = 'list';
				break;			
		

			case  config_item("slug_contact"):					
					if($this->input->post())
					{
						if(validateCaptcha($this->input->post("g-recaptcha-response")))
            			{     
            				$subject 	 	= $this->input->post("subject");
            				$message 	 	= $this->input->post("message");
            				$names 	 		= $this->input->post("names");
            				$email 	 		= $this->input->post("email");
							$email_admin 	= get_email_admin();
							if($subject && $message && $names && $email)
							{
								$message2 = "<strong>Names:</strong><br>$names <br>";
								$message2 .= "<strong>Email:</strong><br>$email <br>";
								$message2 .= "<strong>Message:</strong><br>$message <br>";
								$message2 .= "<br><br>---- Contact Form";
								if(email($email_admin,$subject,$message2))
								{
									$this->session->set_flashdata('contact_message', __("Message Sent"));
				                	redirect(base_url().config_item("slug_contact"),'location');
				                	exit; 
				                }
							}

						}
						else
						{
							$this->session->set_flashdata('contact_error', __("Captcha Error"));
			                redirect(base_url().config_item("slug_contact"),'location');
			                exit;  
						}
					}
				
				break;			
			
			
			case  config_item("slug_user"):	
				if(!is_logged())  
		        {            
		            	redirect(base_url().config_item("slug_login"),'location');
		            exit;
		        }

		        $bookmarks = $this->db->query("SELECT {PRE}sites.* from {PRE}sites,{PRE}bookmarks WHERE {PRE}bookmarks.iduser= "._user("id")." AND {PRE}sites.id = {PRE}bookmarks.idsite ORDER BY score DESC");
				$this->DATA['page'] = $seg2;
				$this->DATA['bookmarks'] = $bookmarks->result();
				 if($this->input->post("names"))
				 {
				 	$this->Admin->updateTable("users",array("names" => _clean_special($this->input->post("names"))),array("id" => _user("id")));
				 } 

				 if($this->input->post("password"))
				 {
				 	$password   = $this->input->post("password",TRUE);
            		$password2  = $this->input->post("password-r",TRUE);
            		if($password == $password2)
	                {
	                    if(strlen($password) >=5)
	                    {
	                    	$this->Admin->updateTable("users",array("password" => sha1($this->input->post("password"))),array("id" => _user("id")));	
	                    }
	                    else
	                    {
	                    	$this->session->set_flashdata('update_error', __("The password length is very short, please add more than 5 characters"));                        	
	                    	$error = true;
	                    }
	                }
	                else
	                {
	                   	$this->session->set_flashdata('update_error', __("Password doesn't match"));                        	
	                	$error = true;
	                }

				 	
				 }

				if($this->input->post())
				{
					if(!$error)
					{
						$user       = $this->Admin->getTable("users",array("id" => _user("id")));                    
                    	$data_user = $user->row_array();
						$this->session->set_userdata("user",$data_user);
                    	$this->session->set_flashdata('update_message', __("Your account has been updated successfully"));
                    }
                	redirect(base_url().config_item("slug_user")."/".$seg2,'location');
                	exit;    
                }

				break;			
			

			case  "review":		
				$this->load->helper('seo');				
				 $site 					= $this->Admin->getTable("sites",array("url" => $seg1));
				 if($site->num_rows() == 0)
				 	show_404();

				 $site_data = $site->row();
				 $score1				= $site_data->score-20;
				 $score2				= $site_data->score;
				 $recent 				= $this->Admin->getTable("sites",array("completed" => 1),"updated desc",false,false,7);    
				 $technologies 			= $this->Admin->getTable("technologies",array("url" => $seg1));    
				 $similar 				= $this->db->query("SELECT * FROM {PRE}sites WHERE score BETWEEN $score1 AND $score2 AND completed = 1 ORDER BY score DESC LIMIT 7");    
				 

				 $this->DATA['SEO']["title"] 		= ucfirst(mb_strtolower($site_data->url))." ".__("- SEO Checker - Website Review");
				 $this->DATA['SEO']["description"]  = ucfirst(mb_strtolower($site_data->url))." ".__(" - Website Review, SEO, Estimation Traffic and Earnings And Speed And Optimization Tips ");
				 $this->DATA['site'] 		= $site_data;
				 $this->DATA['recents'] 	= $recent->result();
				 $this->DATA['similar'] 	= $similar->result();
				 $this->DATA['technologies'] 	= $technologies->result();

			default:
				# code...
				break;
		}
		if(!$this->DATA['SEO']["title"])
			$this->DATA['SEO']["title"] 		= config_item("site_title");

		if(!$this->DATA['SEO']["description"])
			$this->DATA['SEO']["description"] 		= config_item("site_description");

		$pages = $this->Admin->getTable("pages",false,"title");
		$this->DATA['pages'] = $pages->result();
		$this->DATA['totalSites'] 		= $this->Admin->getCountTable("sites");
		$this->show($action);

	}

	
}
