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

class Panel extends MY_Controller {
	

	public function index()
	{
		show_404();

	}

	public function dashboard()
	{
		$this->DATA['menu'] 	= 'dashboard';	
	

		$this->DATA['users'] 		= $this->Admin->getCountTable("users");
		$this->DATA['bookmarks'] 	= $this->Admin->getCountTable("bookmarks");
		$this->DATA['sites'] 		= $this->Admin->getCountTable("sites");
		$this->DATA['registered'] 	= $this->Admin->getRegisteredUsersByMonth();
		
		$this->show("dashboard");
	}	

	public function externalservices()
	{
		if(!is_sadmin())
			show_404();
		if($this->input->post())
		{
			$this->save_settings();
			redirect(base_url()."admin/externalservices");
		}

		$this->DATA['menu'] 	= 'externalservices';	
		$this->show("externalservices");
	}	

	
	public function translation()
	{	

		if($this->input->post("code"))
		{

			$this->Admin->setTable("languages",array("name" => $this->input->post("name"),"code" => mb_strtolower(trim($this->input->post("code")))));			
			redirect(base_url()."admin/translation/?languages=".mb_strtolower(trim($this->input->post("code"))));
			exit;
		}
		$lang = "en";
		if($this->input->get("language"))
			$lang = $this->input->get("language");

	
		if($this->input->post("r") && $lang != 'en')
		{
			$this->Admin->deleteTable("translation",array("code_lang" =>$lang));
			$this->Admin->deleteTable("languages",array("code" =>$lang));
			redirect(base_url()."admin/translation/");
			exit;
		}
		if($this->input->post() && !$this->input->post("r"))
		{
			foreach ($this->input->post() as $key => $value) {
				$save['code'] 			= $key;
				$save['translation'] 	= $value;
				$save['code_lang'] 		= $lang;
				$data[] = $save;
			}
			$this->Admin->setTable("translation",$data,true);
			foreach ($data as $key => $value) {
				$this->Admin->updateTable("translation",$value,array("code" => $value['code'],"code_lang" => $value['code_lang']));
			}
		}
		
		/*$temp 							= $this->Admin->getTable("translation",array("code_lang" => $lang));		
		if($temp->num_rows() == 0)
		{
			$temp 							= $this->Admin->getTable("translation",array("code_lang" => "en"));		
			foreach ($temp->result_array() as $key => $value) 
			{
				$t[]	 = array("code" => $value['code'],"translation" => '',"helper" => $value['translation']);
			}
			$this->DATA['translation'] 		= $t;
		}
		else
			$this->DATA['translation'] 		= $temp->result_array();*/

		$trans 							= $this->Admin->getTable("translation",array("code_lang" => $lang));		
		
		$temp 							= $this->Admin->getTable("translation",array("code_lang" => "en"));		

		$obj_t = array();
		foreach ($trans->result_array() as $key => $value) 
		{	
			$t[$value['code']] = array(
					"translation" => $value['translation']					
				);
		}
		
		foreach ($temp->result_array() as $key => $value) 
		{
			$t[$value['code']]['helper'] = $value['translation'];
		}
	
	
		$this->DATA['translation'] 		= $t;
		
	
		$complteted = 0;
		foreach ($this->DATA['translation']  as $key => $value) {
			if($value['translation'] != '')
				$complteted++;
		}

		$this->DATA['current'] = $this->Admin->getTable("languages",array("code" => $lang))->row_array();


		$this->DATA['porc'] 			= ceil(($complteted*100)/$temp->num_rows());
		$temp 							= $this->Admin->getTable("languages");	
		$this->DATA['languages'] 		= $temp->result_array();		
		$this->DATA['menu'] 			= 'translation';	
		$this->DATA['lang'] 			= $lang;	
		$this->show("translation");
	}
	
	public function users()
	{	
		if(is_ajax())
		{
			$this->table_users();
			return false;
		}
		
		$this->DATA['menu'] 	= 'users';	
		$this->show("users");
	}	

	public function pages()
	{	
		if(intval($this->input->get("delete")))
		{
			$this->Admin->deleteTable("pages",array("idpage"=> intval($this->input->get("delete"))));
			redirect(base_url()."admin/pages/");
			exit;
		}
		
		if($this->input->post("page_last_sites"))
		{
			$this->save_settings();
			redirect(base_url()."admin/pages/");
			exit;
		}
		if($this->input->post("text"))
		{
			// Update
			if($this->input->post("idpage"))
			{
				$update = $this->input->post();
				$update['slug'] = url_title($update['title'],"-",TRUE);
				unset($update['_wysihtml5_mode']);
				unset($update['files']);
				$id = intval($update['idpage']);
				unset($update['idpage']);
				$this->Admin->updateTable("pages",$update,array("idpage" => $id));
				
			}
			else
			{
				$save = $this->input->post();
				$save['slug'] = url_title($save['title'],"-",TRUE);
				unset($save['idpage']);
				unset($save['_wysihtml5_mode']);
				unset($save['files']);
				$this->Admin->setTable("pages",$save);
				redirect(base_url()."admin/pages");
			}
		}
		$this->DATA['page'] 	= $this->Admin->getTable("pages",array("idpage" =>  intval($this->input->get("idpage"))))->row_array();	
		$this->DATA['pages'] 	= $this->Admin->getTable("pages",false,"updated DESC")->result_array();
		$this->DATA['menu'] 	= 'pages';	
		$this->show("pages");
	}

	


	public function settings($module = 'website')
	{		
		if(!is_sadmin())
			show_404();
		if($module == 'apperance')
		{
			$this->apperance();
			return false;
		}
		if(!$module)
			$module = 'website';
		if($this->input->post())
		{
			$this->save_settings();
			redirect(base_url()."admin/settings/".$module);
		}
		$this->DATA['menu'] 	= 'settings';		
		$this->DATA['submenu'] 	= $module;		
		$this->DATA['fields']	 = $this->Admin->getTable("settings",array("module" => $module),"order");		
		$this->show("settings");
	}

	protected function apperance()
	{
		if($this->input->post("save"))
		{
			
			createFolder("uploads");
			createFolder("uploads/stations");
			$upload = uploadImage('./uploads/',sha1($this->input->post('name')),'image');				
			if($upload['image'])
			{	
				$this->Admin->updateTable("settings",array("value" => "uploads/".$upload['image']),array("var" => 'logo'));
			}
			
			$this->save_settings();
		
			redirect(base_url()."admin/settings/apperance");
		}


	
		 $langs  = $this->db->query("
		      SELECT {PRE}languages.* FROM 
		      {PRE}languages,
		      {PRE}translation
		      WHERE
		      {PRE}languages.code = {PRE}translation.code_lang
		      GROUP BY {PRE}languages.name
		      ORDER BY {PRE}languages.name
		      "); 

		$this->DATA['langs'] 	= $langs->result();	
		$this->DATA['menu'] 	= 'settings';	
		$this->DATA['submenu'] 	= 'apperance';	
		$this->show("apperance");

		

	}
	protected function save_settings()
	{
		if($this->input->post())
		{
			foreach ($this->input->post() as $key => $value) {
				if(is_array($value))
				{
					//print_p($value);					
					$value = implode(",",$value);
				}
				$this->Admin->setTableIgnore("settings",array("value" => $value,"var" => $key));
				$this->Admin->updateTable("settings",array("value" => $value),array("var" => $key));
				$this->config->set_item($key, $value);  
			}
		}
	}
	
	protected function table_users()
	{
		
	/*
	* Ordering
	*/	$sOrder = false;
		if ($this->input->get('iSortCol_0') || 1==1)
		{
			$columns[0] = 'id';
			$columns[1] = 'avatar';			
			$columns[2] = 'email';						
			$columns[3] = 'names';						
			$columns[4] = 'registered';														
			$sOrder = $columns[$this->input->get('iSortCol_0')]." ".$this->input->get('sSortDir_0');			
		}
		$like= false;
		if ($this->input->get('sSearch') != "" )
		{
			foreach ($columns as $key => $value) {
				$like[$value]	= $this->input->get('sSearch');
			}
			
		}
		$users 				= $this->Admin->getTable("users",false,$sOrder,'id,avatar,username,email,names,registered',$this->input->get('iDisplayLength'),$this->input->get('iDisplayStart'),$like);	
		
		$total 					= $this->Admin->getTable("users",false,$sOrder,'id,avatar,username,email,names,registered',false,false,$like);	
		$total 					= $total->num_rows();
		$output = array(
		"sEcho" => intval($this->input->get('sEcho')),
		"iTotalRecords" => $total,
		"iTotalDisplayRecords" => $total,
		"aaData" => array()
		);
		foreach ($users->result_array() as $key => $value) {
			$row = array();		
			
			$row[] = $value['id'];
			$row[] = "<img src='".avatar($value['avatar'])."' style='height:30px'>";						
			$row[] = $value['email'];			
			$row[] = $value['names'];			
			$row[] = "<span title='".$value['registered']."'>".ago(($value['registered']))."</span>";			
					
			
			
			$output['aaData'][] = $row;
		}
		
		echo json_encode( $output );
	}
	

	public function update()
	{		
		$DATA 				= array();
		if($this->input->post("r") == 'CONFIRM')
		{
			$this->db->query("TRUNCATE TABLE {PRE}albums;");                                           
            $this->db->query("TRUNCATE TABLE {PRE}artist;");                                           
            $this->db->query("TRUNCATE TABLE {PRE}tracks;");                                           
            //$this->db->query("TRUNCATE TABLE {PRE}users_history;");                                                       
            $this->db->query("DELETE FROM {PRE}likes where type IN (1,2,3);");                                
            //$this->db->query("TRUNCATE TABLE {PRE}sessions;");
            redirect(base_url()."admin/dashboard");
		}

		if($this->input->post("uploading"))
		{			
			if(!file_exists('./uploads/'))
			{
				mkdir('./uploads/');
			}
			$config['upload_path'] 		= './uploads/';
			$config['allowed_types'] 	= 'zip';
			$config['overwrite'] 		=  true;
			$cupload onfig['remove_spaces']	=  true;
			$this->load->library('upload', $config);
			if ( ! $this->upload->do_upload('upload'))
			{
				$DATA['upload'] = array('error' => $this->upload->display_errors());				
			}
			else
			{
				$DATA['upload'] = array('upload_data' => $this->upload->data());
				$this->load->library('unzip');
				$file = './uploads/'.$DATA['upload']['upload_data']['file_name'];
				if(file_exists($file))
				{					
					$this->unzip->extract($file, './');	
					$errorZip = strip_tags($this->unzip->error_string());
					if($errorZip != '')
						$DATA['upload'] = $errorZip;
					@unlink($file);
					$this->validate_update();
				}
				else
				{
					$DATA['upload'] = array('error' =>'File '.$file." not exist");	
				}
				
				
			}
		}
			
		
		$this->DATA['menu'] 	= 'update';	
		$this->DATA['upload']  = $DATA['upload'];
		$this->show("update");
	}


}