<?php
class Baner_glowny_model extends Model {

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

    function Baner_glowny_model()
    {
        // Call the Model constructor
        parent::Model();
        $this->load->helper("log");
    }

    function getMaxBanerGlownyOrder($userId){
    	$sql = "SELECT MAX(baner_glowny_order) from baner_glowny WHERE baner_glowny_user_id='".$userId."' ";
    	$result = $this->db->query($sql);
    	if($result->num_rows() > 0){
    		$row = $result->row_array();
    		return $row['MAX(baner_glowny_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 addbanerglownyphoto($userId, $foto_x, $foto_y, $header, $file, $change_size, $link){
    	$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' => $userId))->row()->user_folder;
    		if(@move_uploaded_file($plik['tmp_name'], 'pages/'.$folder.'/foto/baner/'.$nazwa_pliku)){
    			
    			if($change_size){
	    			$this->setMemoryForImage('pages/'.$folder.'/foto/baner/'.$nazwa_pliku);
	    			
	    			$size = getimagesize('pages/'.$folder.'/foto/baner/'.$nazwa_pliku);
	    			
	    			$this->load->library('image_lib');
	    			
	    			$config['maintain_ratio'] = TRUE;
	    			$config['source_image'] = 'pages/'.$folder.'/foto/baner/'.$nazwa_pliku;
	    			$config['image_library'] = 'gd2';
	    			$config['width'] = $foto_x;
	    			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();
	    				
    			}
    			if($link != '') $link = prep_url($link);
    			$order = $this->getMaxBanerGlownyOrder($userId) + 1;
    			$data = array(
    				'baner_glowny_user_id' => $userId,
    				'baner_glowny_name' => $nazwa_pliku,
    				'baner_glowny_header' => $header,
    				'baner_glowny_link' => $link,
    				'baner_glowny_order' => $order
    			);
    			$this->db->set('baner_glowny_added', 'sysdate()', FALSE);
    			$this->db->insert('baner_glowny', $data);
    			action_log('Dodawanie zdjęcia baneru głównego', 'baner_glowny', 'insert', $this->db->insert_id(), $nazwa_pliku);
    		}
    		$pagename = $this->db->get_where('users', array('ID_users' => $userId))->row()->user_pagename;
    		return reduce_double_slashes(prep_url($pagename).'/foto/baner/'.$nazwa_pliku);
    	} else {return false;}
    }
    
	function setbanerglownyphotosorder($photos){
    	$order = 0;
    	foreach ($photos as $baner){
    		$order++;
    		$this->db->where('ID_baner_glowny', $baner);
    		$this->db->update('baner_glowny', array('baner_glowny_order' => $order));
    		$nazwa = $this->db->get_where('baner_glowny', array('ID_baner_glowny' => $baner))->row()->baner_glowny_name;
    		action_log('Zmiana kolejności zdjęć baneru głównego', 'baner_glowny', 'update', $baner, $nazwa);
    	}
    }
    
	function getbanerglowny($id){
		$query = $this->db->get_where('baner_glowny', array('ID_baner_glowny' => $id));
		if($query->num_rows() > 0){
			$row = $query->row();
			return $row;
		} else return NULL;
	}
	
	function edytujbanerglowny($id, $header, $link){
		if($link != '') $link = prep_url($link);
		$data = array(
			'baner_glowny_header' => $header,
			'baner_glowny_link' => $link
		);
		$this->db->where('ID_baner_glowny', $id);
		$this->db->update('baner_glowny', $data);
		action_log('Edycja zdjęcia baneru głównego', 'baner_glowny', 'update', $id, $header);
	}
	
	function cropbaner($foto, $x, $y, $x2, $y2, $h, $w){
		$n = explode('/', $foto);
		$nazwa_pliku = $n[count($n)-1];
		$folder = $this->db->get_where('users', array('ID_users' => $this->session->userdata('uzytkownik_id')))->row()->user_folder;
		
		$this->setMemoryForImage('pages/'.$folder.'/foto/baner/'.$nazwa_pliku);
		
		$this->load->library('image_lib');
	    			
    	$config['source_image'] = 'pages/'.$folder.'/foto/baner/'.$nazwa_pliku;
    	$config['image_library'] = 'gd2';
    	$config['maintain_ratio'] = FALSE;
    	$config['width'] = $w;
    	$config['height'] = $h;
    	$config['x_axis'] = $x;
		$config['y_axis'] = $y;
    	    	
    	$this->image_lib->initialize($config);
    	$this->image_lib->crop();
    	
    	$stara_nazwa = $nazwa_pliku;
    	$r = explode(".", $stara_nazwa);
    	$nazwa_pliku = time().'.'.$r[count($r)-1];
    	rename('./pages/'.$folder.'/foto/baner/'.$stara_nazwa, './pages/'.$folder.'/foto/baner/'.$nazwa_pliku);
    	
    	$this->db->where('baner_glowny_name', $stara_nazwa);
    	$this->db->update('baner_glowny', array('baner_glowny_name' => $nazwa_pliku));
	}
	
	function removebanerglownyphoto($id, $name){
		$folder = $this->db->get_where('users', array('ID_users' => $this->session->userdata('uzytkownik_id')))->row()->user_folder;
		unlink('pages/'.$folder.'/foto/baner/'.$name);
		$this->db->where('ID_baner_glowny', $id);
		$this->db->delete('baner_glowny');
		$affRows = $this->db->affected_rows();
		
		action_log('Usuwanie zdjęcia baneru głównego', 'baner_glowny', 'delete', $id, $name);
		
		return $affRows;
	}
	
	function getbanerglownyphotos($userId){
		$this->db->order_by('baner_glowny_order', 'asc');
		return $this->db->get_where('baner_glowny', array('baner_glowny_user_id' => $userId));
	}
	
	function checkallpages($userId){
		$query = $this->db->get_where('baner_glowny_config', array('baner_glowny_config_user_id' => $userId));
		if($query && $query->num_rows() > 0){
			$row = $query->row();
			return $row->baner_glowny_config_allpages;
		} else {
			return 1;
		}
	}
	
	function banerglownyustawienia($userId, $checkbaner){ 
		$query = $this->db->get_where('baner_glowny_config', array('baner_glowny_config_user_id' => $userId));
		if($query && $query->num_rows() > 0){
			$this->db->where('baner_glowny_config_user_id', $userId);
			$this->db->update('baner_glowny_config', array('baner_glowny_config_allpages' => $checkbaner));
		} else {
			$this->db->insert('baner_glowny_config', array(
				'baner_glowny_config_user_id' => $userId,
				'baner_glowny_config_allpages' => $checkbaner
			));
		}
	}
		
}
?>