<?php
class Galeria_model extends Model {

    var $title   = '';
    var $content = '';
    var $date    = '';
	var $encryption_key = "i:Dvv%^uJKK9)_K<";

    function Galeria_model()
    {
        // Call the Model constructor
        parent::Model();
        $this->load->helper("log");
    }
	/*
	function log($info, $table, $operation, $id, $name=''){
		$data = array(
			'action_log_user_id' => $this->session->userdata('uzytkownik_id'),
			'action_log_login' => $this->session->userdata('uzytkownik'),
			'action_log_info' => $info.'. Tabela '.$table.', operacja '.$operation.', ID pozycji '.$id.', nazwa '.$name
		);
		$this->db->set('action_log_time', 'sysdate()', FALSE);
		$this->db->insert('action_log', $data);
	}
    */
	
	function getphotosize($userId) {
		return $this->db->get_where('gallery_config', array('gallery_config_user_id' => $userId));
	}
		
	function editphotosize($userId, $x, $y){
		$size = $this->getphotosize($userId);
		if($size && $size->num_rows()>0){
			$data = array('gallery_config_size_x' => $x, 'gallery_config_size_y' => $y);
			$this->db->where('gallery_config_user_id', $userId);
			$this->db->update('gallery_config', $data);
		
			$affRows = $this->db->affected_rows();
			$s = $size->row();
			action_log('Zmiana domyślnego rozmiaru miniaturki', 'gallery_config', 'update', $s->ID_gallery_config);
		} else {
			$data = array('gallery_config_user_id' => $userId, 'gallery_config_size_x' => $x, 'gallery_config_size_y' => $y);
			$this->db->insert('gallery_config', $data);
			
			$affRows = $this->db->affected_rows();
			action_log('Zmiana domyślnego rozmiaru miniaturki', 'gallery_config', 'insert', $this->db->insert_id());
		}
		return $affRows;
	}
		
	function getMaxPhotoOrder($moduleId){
		$sql="SELECT MAX(photos_order) FROM photos WHERE photos_module_id='".$moduleId."' ";
		$result= $this->db->query($sql);
		if($result->num_rows()>0){
			$row = $result->row_array();
			return $row['MAX(photos_order)'];
		} else return 1;
	}
	
	function setMemoryForImage( $filename ){
	    $imageInfo = getimagesize($filename);
	    $MB = 1048576;  // number of bytes in 1M
	    $K64 = 65536;    // number of bytes in 64K
	    $TWEAKFACTOR = 1.5;  // Or whatever works for you
	    $memoryNeeded = round( ( $imageInfo[0] * $imageInfo[1]
	                                           * $imageInfo['bits']
	                                           * $imageInfo['channels'] / 8
	                             + $K64
	                           ) * $TWEAKFACTOR
	                         );
	    //ini_get('memory_limit') only works if compiled with "--enable-memory-limit" also
	    //Default memory limit is 8MB so well stick with that.
	    //To find out what yours is, view your php.ini file.
	    $memoryLimit = 8 * $MB;
	    if (function_exists('memory_get_usage') &&
	        memory_get_usage() + $memoryNeeded > $memoryLimit)
	    {
	    	$memoryLimitMB = (integer) ini_get('memory_limit');
	        $newLimit = $memoryLimitMB + ceil( ( memory_get_usage()
	                                            + $memoryNeeded
	                                            - $memoryLimit
	                                            ) / $MB
	                                        );
	        ini_set( 'memory_limit', $newLimit . 'M' );
	        return true;
		}else
	    return false;
	}
	
	
	function addphoto($moduleId, $x, $y, $foto_x, $foto_y, $header, $description, $file){
		
		$plik=$_FILES['plik'];
		
		
	
		if(in_array($plik['type'], array('image/jpeg', 'image/pjpeg', 'image/png', 'image/gif'))){
			
			$n=$plik['name'];
			$r=explode(".",$n);
			$nazwa_pliku=time().'.'.$r[count($r)-1];
			$folder = $this->db->get_where('users', array('ID_users' => $this->session->userdata('uzytkownik_id')))->row()->user_folder;
			if(@move_uploaded_file($plik['tmp_name'], 'pages/'.$folder.'/foto/'.$nazwa_pliku)){
				
				$this->setMemoryForImage('pages/'.$folder.'/foto/'.$nazwa_pliku);
				
				$size = getimagesize('pages/'.$folder.'/foto/'.$nazwa_pliku);
				
				$this->load->library('image_lib');
				
				$config['maintain_ratio'] = TRUE;
				$config['source_image'] = 'pages/'.$folder.'/foto/'.$nazwa_pliku;
				$config['image_library'] = 'gd2';
				$config['width'] = $foto_x;
				//$config['height'] = $foto_y;
				if($size[0] > $size[1])
    				$config['height'] = $foto_x;//$foto_y;
    			else $config['height'] = $foto_x * 5;
    			
				$this->image_lib->initialize($config);
				$this->image_lib->resize();
				$this->image_lib->clear();
				
				
				$config['maintain_ratio'] = TRUE;
				$config['create_thumb'] = TRUE;
				$config['thumb_marker'] = FALSE;
				$config['source_image'] = 'pages/'.$folder.'/foto/'.$nazwa_pliku;
				$config['new_image'] = 'pages/'.$folder.'/foto/thumb_'.$nazwa_pliku;//'/path/to/new_image.jpg';
				$config['image_library'] = 'gd2';
				$config['width'] = $x;
				//$config['height'] = $y;
				if($size[0] > $size[1])
    				$config['height'] = $x;//$foto_y;
    			else $config['height'] = $x * 5;
    			
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
				/*
				
				*/
				$order = $this->getMaxPhotoOrder($moduleId) + 1;
				
				$data = array(
					'photos_module_id' => $moduleId,
					'photos_name' => $nazwa_pliku,
					'photos_header' => $header,
					'photos_description' => $description,
					'photos_order' => $order
					);
				$this->db->set('photos_added', 'sysdate()', FALSE);
				$this->db->insert('photos', $data); 
				action_log('Dodawanie zdjęcia', 'photos', 'insert', $this->db->insert_id(), $nazwa_pliku);
				//echo ' '.$nazwa_pliku.' ';
			} 
			return true;
		} else {return false;}
	}
		
	function setphotosorder($photos){
		$order = 0;
		foreach ($photos as $photo){
			$order++;
			$this->db->where('ID_photos', $photo);			
			$this->db->update('photos', array('photos_order' => $order));
			$nazwa = $this->db->get_where('photos', array('ID_photos' => $photo))->row()->photos_name;
			action_log('Zmiana kolejności zdjęć', 'photos', 'update', $photo, $nazwa);
		}
	}
	
	function getphoto($id){
		$query = $this->db->get_where('photos', array('ID_photos' => $id));
		if($query->num_rows()>0){
			$row = $query->row();
			return $row;
		} else return NULL;
	}
	
	function edytujfoto($id, $header, $desc){
		
		$data = array(
			'photos_header' => $header,
			'photos_description' => $desc
		);
		$this->db->where("ID_photos", $id);
		$this->db->update('photos', $data);
		action_log('Edycja zdjęcia', 'photos', 'update', $id, $header);
	}
	
}
?>