Current File : /home/users/barii/public_html/finansenl.com.pl/wodki/application/views/account/Account.php
<?php

defined('SYSPATH') or die('No direct script access.');

class Controller_Account extends Controller_Frontend {

     public function action_index($action = '', $id_t = null) {
	
		$this->redirect('account/edit'); 
	
        $this->template->title = $title = 'Moje dane';

		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
		
		$id =  Auth::instance()->get_user()->id;
		
		$user = ORM::Factory('User', $id );

		$profile = $user->profile_id;
		
		$notices = ORM::Factory('User')->where('parent','=', $id)->find_all();
		
		if( $profile > 1 ) $profile = 1;
		
		$view = View::factory('account/index_'.$profile);
		//$images = ORM::Factory('user_image')->where('user_id','=', $user->id)->find_all();
		
		$discount_message = ORM::Factory('User_Discount')->where('user_id','=',$user->id)->find();
		
		if( $discount_message->loaded() ) {
			if( $discount_message->file_id != 0 ) {
				$discount_message = __t('Został przyznany Tobie rabat w wysokości '.$discount_message->discount.'% na skrypt '.$discount_message->file->title);
			} else {
				$discount_message = __t('Został przyznany Tobie rabat w wysokości '.$discount_message->discount.'% na wszystkie skrypty');
			}
		} else {
			$discount_message = '';
		}

        $this->template->content = $view
						->bind('title', $title)
						->bind('notices', $notices)
						->bind('discount_message', $discount_message)
						->bind('user', $user)
						->bind('user_id', $id)
						//->bind('images', $images)
                        ->bind('errors', $errors)
						->bind('message_ok', $message_ok)
                        ->bind('message', $message);
    }
	
	public function action_report() {

        $this->template->title = $title = 'Raport';

		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
		$view = View::factory('account/report');
        $this->template->content = $view
                        ->bind('title', $title)
                        ->bind('errors', $errors)
                        ->bind('message', $message);
    }	
	public function action_earning() {

        $this->template->title = $title = 'Finanse';
		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
		$view = View::factory('account/earning');
		
		$user = ORM::Factory('User', Auth::instance()->get_user()->id);
		
		$y = !empty($_GET['y']) ? addslashes($_GET['y']) : date('Y');
		$m = !empty($_GET['m']) ? addslashes($_GET['m']) : date('n');
		
		$n = $m;
		if( $n<10 ) $n = '0'.$n;
		
		$date = $y."-".$n;
		$sold = ORM::Factory('Order')->where(DB::expr('DATE_FORMAT(`date`,"%Y-%m")'),'=', $date)->where('seller_id','=', $user->id)->find_all();
		
		$points = ORM::Factory('Stat')->where(DB::expr('DATE_FORMAT(`date`,"%Y-%m")'),'=', $date)->where('user_id','=', $user->id)->find_all();
		$invoices = ORM::Factory('invoice')->where(DB::expr('DATE_FORMAT(`date`,"%Y-%m")'),'=', $date)->where('customers_id','=', $user->id)->find_all();
		$commission = ORM::Factory('User_commission')->select(array(DB::expr('SUM(`amount`)'), 'total'))->where(DB::expr('DATE_FORMAT(`date`,"%Y-%m")'),'=', $date)->where('user_id','=', $user->id)->where('status','=', 2)->find();
        $this->template->content = $view
                        ->bind('title', $title)
						->bind('invoices', $invoices)
						->bind('commission', $commission)
						->bind('y', $y)
						->bind('m', $m)
						->bind('user', $user)
						->bind('points', $points)
						->bind('sold', $sold)
                        ->bind('errors', $errors)
                        ->bind('message', $message);
    }
	
	public function action_stat() {

        $this->template->title = $title = 'Statystyki konta';
		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
		$view = View::factory('account/stat');
		
		$user = ORM::Factory('User', Auth::instance()->get_user()->id);
		
		$y = !empty($_GET['y']) ? addslashes($_GET['y']) : date('Y');
		$m = !empty($_GET['m']) ? addslashes($_GET['m']) : date('n');
		
		$n = $m;
		if( $n<10 ) $n = '0'.$n;
		
		$date = $y."-".$n;
		$sold = ORM::Factory('Order')->where(DB::expr('DATE_FORMAT(`date`,"%Y-%m")'),'=', $date)->where('seller_id','=', $user->id)->find_all();
		
		$points = ORM::Factory('Stat')->where(DB::expr('DATE_FORMAT(`date`,"%Y-%m")'),'=', $date)->where('user_id','=', $user->id)->find_all();
		
		$REGISTER = ORM::Factory('Stat')
				->select(array(DB::expr('sum(`value`)'), 'sum_val'))
				->where('keyname','=', 'REGISTER')
				->where(DB::expr('DATE_FORMAT(`date`,"%Y-%m")'),'=', $date)
				->where('user_id','=', $user->id)
				->find();
		$ADD_ITEM = ORM::Factory('Stat')
				->select(array(DB::expr('sum(`value`)'), 'sum_val'))
				->where('keyname','=', 'ADD_ITEM')
				->where(DB::expr('DATE_FORMAT(`date`,"%Y-%m")'),'=', $date)
				->where('user_id','=', $user->id)
				->find();
		$INVITE_TO_REGISTER = ORM::Factory('Stat')
				->select(array(DB::expr('sum(`value`)'), 'sum_val'))
				->where('keyname','=', 'INVITE_TO_REGISTER')
				->where(DB::expr('DATE_FORMAT(`date`,"%Y-%m")'),'=', $date)
				->where('user_id','=', $user->id)
				->find();
				
		$BUY = ORM::Factory('Stat')
				->select(array(DB::expr('sum(`value`)'), 'sum_val'))
				->where('keyname','=', 'BUY')
				->where(DB::expr('DATE_FORMAT(`date`,"%Y-%m")'),'=', $date)
				->where('user_id','=', $user->id)
				->find();
				
		$SELL = ORM::Factory('Stat')
				->select(array(DB::expr('sum(`value`)'), 'sum_val'))
				->where('keyname','=', 'SELL')
				->where(DB::expr('DATE_FORMAT(`date`,"%Y-%m")'),'=', $date)
				->where('user_id','=', $user->id)
				->find();
				
		$FB = ORM::Factory('Stat')
				->select(array(DB::expr('sum(`value`)'), 'sum_val'))
				->where('keyname','=', 'SHARE_FB')
				->where(DB::expr('DATE_FORMAT(`date`,"%Y-%m")'),'=', $date)
				->where('user_id','=', $user->id)
				->find();				
		
		$invoices = ORM::Factory('invoice')->where(DB::expr('DATE_FORMAT(`date`,"%Y-%m")'),'=', $date)->where('customers_id','=', $user->id)->find_all();
        $this->template->content = $view
                        ->bind('title', $title)
						->bind('invoices', $invoices)
						->bind('y', $y)
						->bind('m', $m)
						->bind('user', $user)
						->bind('points', $points)
						->bind('FB', $FB)
						->bind('REGISTER', $REGISTER)
						->bind('ADD_ITEM', $ADD_ITEM)
						->bind('INVITE_TO_REGISTER', $INVITE_TO_REGISTER)
						->bind('BUY', $BUY)
						->bind('SELL', $SELL)
						->bind('sold', $sold)
                        ->bind('errors', $errors)
                        ->bind('message', $message);
    }

	public function action_file() {

        $this->template->title = $title = 'File';
		$user_id = Auth::instance()->get_user()->id;
		
		$files = ORM::Factory('File')->where('user_id','=', $user_id)->find_all();

		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
		$view = View::factory('account/file');
        $this->template->content = $view
                        ->bind('title', $title)
						->bind('files', $files)
                        ->bind('errors', $errors)
                        ->bind('message', $message);
    }

	public function action_site() {

        $this->template->title = $title = 'Site';

		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
		$view = View::factory('account/site');
        $this->template->content = $view
                        ->bind('title', $title)
                        ->bind('errors', $errors)
                        ->bind('message', $message);
    }

	public function action_resseler() {

        $this->template->title = $title = 'Resseler';

		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
		$view = View::factory('account/resseler');
        $this->template->content = $view
                        ->bind('title', $title)
                        ->bind('errors', $errors)
                        ->bind('message', $message);
    }	
	public function action_affiliate() {

        $this->template->title = $title = 'Affiliate';
		$id =  Auth::instance()->get_user()->id;
		
		$user = ORM::Factory('User', $id );
		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
		
		$canPP = Kohana::$config->load('site.canPP');
		
		if( !$canPP ) {
			Message::success(__t('PP jest obecnie wyłączony!'));
			$this->redirect('account/edit');
		}
		
		if( $_POST ) {
			$data = ac_form::clear_form_data($_POST);
			if( !empty( $data['billing_name']) and !empty( $data['billing_bank_account']) ) {
				foreach( $data as $key => $val ) {
					$user->{$key} = $val;
				}
				$user->save();
				
				$sum = DB::Query(Database::SELECT, "select sum(amount) as amount from payments where status = 0 and user_id = '$id'")->as_object()->execute();
				if( $sum[0]->amount >= Kohana::$config->load('site.canPaymentMoney') ) {
					$p = ORM::factory('Payment');
					$p->amount = $amount;
					$p->status = 2;		// wypłacono, historia wypłat
					$p->direct = 'O';
					$p->user_id = $id;
					$p->save();
					
					DB::Query(Database::UPDATE, "update payments set status = 1 where status = 0 and user_id = '$id'")->execute();
					
					
					
					if( Kohana::$config->load('site.canConfirmAdminPaymentPP') ) {
						
						$title = __t('Zmiana w licencji dla '.$order->customer->username);
					
						$e_content = View::factory('email/confirmation_payment_pp')
													->bind('user', $user)->bind('amount', $amount);
						$from = array();
						$from[0] = Kohana::$config->load('site.email_business');
						$from[1] = Kohana::$config->load('site.appName');
			
						aurora::standardEmail(Kohana::$config->load('site.email_business'), $title,  $e_content);
			
			
					}
					//ustawiamy jako wypłacono już...
					
				} else {
					Message::success( __t('Nie możesz dokonać jeszcze wypłaty') );
					$this->redirect('account/affiliate');
				}
			}
		}
		
		$uniq_link_pp = 'http://'.$_SERVER['HTTP_HOST'].'/register/customer?i='.$user->id.'_'.md5($user->id);
		
		$pay_in = DB::Query(Database::SELECT, "SELECT SUM(amount) as amount FROM payments WHERE user_id = '$id'")->as_object()->execute();
		
		$earn = (float)$pay_in[0]->amount;
		
		$almost = Kohana::$config->load('site.canPaymentMoney')-$earn;
		if( $almost < 0 ) $almost = 0;

		$view = View::factory('account/affiliate');
        $this->template->content = $view
                        ->bind('title', $title)
						->bind('uniq_link_pp', $uniq_link_pp)
						->bind('earn', $earn)
						->bind('almost', $almost)
                        ->bind('errors', $errors)
						->bind('user', $user)
                        ->bind('message', $message);
    }
	
     public function action_delete() {

        $this->template->title = $title = 'Moje dane';

		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
		
		$id =  Auth::instance()->get_user()->id;
		
		$user = ORM::Factory('User', $id );
		$user->status = 100;
		$user->save();
		
		Message::success('Administrator otrzyma informacje o prośbie usunięcia konta!');
		$this->redirect('account/edit');
		
    }
	
	public function action_delete_photo( $id = null ) {
		
		$user_id = Auth::instance()->get_user()->id;
		$photo_id = addslashes($_GET['photo_id']);
		
		$item_id = addslashes($_GET['id']);
		$layout = addslashes($_GET['layout']);
		$user = ORM::Factory('User', $item_id);
		
		$select = ORM::Factory('user_image')->where('id','=',$photo_id)->find();
		if( $select->loaded() ) {
			
			if( Auth::instance()->logged_in('admin') ) {
				$select->delete();
			
			} else {
				if( $user->parent == $user_id ) {
				$select->delete();
				
				
				}
			
			}
			
			$this->request->redirect('account/notice/edit/'.$item_id.'?layout='.$layout);	
		}
		
		$this->request->redirect('account/edit');	
	exit;
		
	}	
	
	public function action_set_thumb_photo( $id = null ) {
		
		$user_id = Auth::instance()->get_user()->id;
		$photo_id = addslashes($_GET['photo_id']);
		
		$item_id = addslashes($_GET['id']);
		$layout = addslashes($_GET['layout']);
		$user = ORM::Factory('User', $item_id);
		
		$select = ORM::Factory('user_image')->where('id','=',$photo_id)->find();
		if( $select->loaded() ) {
		
			if( Auth::instance()->logged_in('admin') ) {
				DB::Query(Database::UPDATE, "UPDATE user_images SET highlight = 0 WHERE user_id = '$item_id'")->execute();
				$select->highlight = 1;
				$select->save();
				$this->request->redirect('account/notice/edit/'.$item_id.'?layout='.$layout);	
			} else {
			
				if( $user->parent == $user_id ) {
				DB::Query(Database::UPDATE, "UPDATE user_images SET highlight = 0 WHERE user_id = '$item_id'")->execute();
				$select->highlight = 1;
				$select->save();
				$this->request->redirect('account/notice/edit/'.$item_id.'?layout='.$layout);	
				}
			}
		}
		
		$this->request->redirect('account/edit');	
	exit;
		
	}		
	
	
	public function action_activate_email() {
		$email_old = Request::current()->param('email_old');
		$id = Request::current()->param('id');
		$email_new = Request::current()->param('email_new');
		
		$u = ORM::Factory('User')->where('email','=', $email_old)->find();
		if( $u->loaded() ) {
			if( md5($u->id) == $id ) {
				$u->email = $email_new;
				$u->save();
				
			}
		}
		
		$this->redirect('account/edit');
	}

	public function action_shopping() {

		$this->template->title = $title = 'Twoje zakupy';
		$id = Request::current()->param('id');
		
		$filtr = !empty($_GET['filtr']) ? addslashes($_GET['filtr']) : '';
		$sort = !empty($_GET['sort']) ? addslashes($_GET['sort']) : 'date';
		
		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
		
		$user_id = Auth::instance()->get_user()->id;
		$user = ORM::Factory('User', $user_id);
		
		if( !empty($_GET['get_courier']) AND !empty($_POST['send']) ) {
		
			$oid = (int)$_POST['order_id'];
			$order = ORM::Factory('Order', $oid);	
			$order->courier = 1; 
			$order->courier_text = addslashes($_POST['note_text']); 
			$order->ringleader_courier = $user_id; 
			$order->save();
			$title = __t('Zamówienie kuriera dla '.$user->username);
					
			$note_text = $order->courier_text;
					$e_content = View::factory('email/get_courier')
													->bind('note_text', $note_text)
													->bind('user', $user);
					$from = array();
					$from[0] = Kohana::$config->load('site.email_business');
					$from[1] = Kohana::$config->load('site.appName');
			
					aurora::standardEmail(Kohana::$config->load('site.email_business'), $title,  $e_content);
			
					Message::success(__t('Wiadomość przesłana do administracji!'));
					$this->redirect('account/shopping');
		}
		
		if( !empty($_GET['rakeback']) AND !empty($_POST['order_id']) ) {
		
			$title = __t('Wystąpienie o zwrot prowizji');
			$oid = (int)$_POST['order_id'];
			$order = ORM::Factory('Order', $oid);	
			$order->rakeback = 1;
			$order->ringleader_rakeback = $user_id; 			
			$order->rakeback_text = addslashes($_POST['note_text']); 
			$order->save();
			
			$note_text = $order->rakeback_text;
			
					$e_content = View::factory('email/rakeback')
													->bind('user', $user)
													->bind('note_text', $note_text)
													->bind('order', $order);
					$from = array();
					$from[0] = Kohana::$config->load('site.email_business');
					$from[1] = Kohana::$config->load('site.appName');
			
					aurora::standardEmail(Kohana::$config->load('site.email_business'), $title,  $e_content);
			
					Message::success(__t('Wiadomość przesłana do administracji!'));
					$this->redirect('account/shopping');
		}
		
		if( !empty($_GET['controversy']) AND !empty($_POST['order_id']) ) {
		
			$title = __t('Nowy spór w transkacji');
			$oid = (int)$_POST['order_id'];
			$order = ORM::Factory('Order', $oid);	
			$order->controversy = 1; 
			$order->ringleader_controversy = $user_id; 
			$order->controversy_text = addslashes($_POST['note_text']); 
			$order->save();
			
			$note_text = $order->controversy_text;
					$e_content = View::factory('email/controversy')
													->bind('user', $user)
													->bind('note_text', $note_text)
													->bind('order', $order);
					$from = array();
					$from[0] = Kohana::$config->load('site.email_business');
					$from[1] = Kohana::$config->load('site.appName');
			
					aurora::standardEmail(Kohana::$config->load('site.email_business'), $title,  $e_content);
			
					Message::success(__t('Wiadomość przesłana do administracji!'));
					$this->redirect('account/shopping');
		}
		
		
		$view = View::factory('account/order');
		
		
		
		$orders = ORM::Factory('Order');
		
		if( !empty( $filtr ) ) {
				$orders = $orders
							->where($filtr,'=', $filtr_value);
			}
			
		$orders = $orders->where('user_id','=', $user_id)->order_by($sort, 'desc')->find_all();
	
        $this->template->content = $view
                        ->bind('title', $title)
						->bind('user', $user)
						->bind('sort', $sort)
						->bind('orders', $orders)
                        ->bind('errors', $errors)
						->bind('message_ok', $message_ok)
                        ->bind('message', $message);
	}
	
	public function action_order() {

		$this->template->title = $title = 'Zamówienia';
		$id = Request::current()->param('id');
		
		$filtr = !empty($_GET['filtr']) ? addslashes($_GET['filtr']) : '';
		$sort = !empty($_GET['sort']) ? addslashes($_GET['sort']) : 'date';
		
		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
		
		$user_id = Auth::instance()->get_user()->id;
		$user = ORM::Factory('User', $user_id);
		
		if( !empty($_GET['get_courier']) AND !empty($_POST['send']) ) {
		
			$oid = (int)$_POST['order_id'];
			$order = ORM::Factory('Order', $oid);	
			$order->courier = 1; 
			$order->courier_text = addslashes($_POST['note_text']); 
			$order->ringleader_courier = $user_id; 
			$order->save();
			$title = __t('Zamówienie kuriera dla '.$user->username);
					
			$note_text = $order->courier_text;
					$e_content = View::factory('email/get_courier')
													->bind('note_text', $note_text)
													->bind('user', $user);
					$from = array();
					$from[0] = Kohana::$config->load('site.email_business');
					$from[1] = Kohana::$config->load('site.appName');
			
					aurora::standardEmail(Kohana::$config->load('site.email_business'), $title,  $e_content);
			
					Message::success(__t('Wiadomość przesłana do administracji!'));
					$this->redirect('account/order');
		}
		
		if( !empty($_GET['rakeback']) AND !empty($_POST['order_id']) ) {
		
			$title = __t('Wystąpienie o zwrot prowizji');
			$oid = (int)$_POST['order_id'];
			$order = ORM::Factory('Order', $oid);	
			$order->rakeback = 1;
			$order->ringleader_rakeback = $user_id; 			
			$order->rakeback_text = addslashes($_POST['note_text']); 
			$order->save();
			
			$note_text = $order->rakeback_text;
			
					$e_content = View::factory('email/rakeback')
													->bind('user', $user)
													->bind('note_text', $note_text)
													->bind('order', $order);
					$from = array();
					$from[0] = Kohana::$config->load('site.email_business');
					$from[1] = Kohana::$config->load('site.appName');
			
					aurora::standardEmail(Kohana::$config->load('site.email_business'), $title,  $e_content);
			
					Message::success(__t('Wiadomość przesłana do administracji!'));
					$this->redirect('account/order');
		}
		
		if( !empty($_GET['controversy']) AND !empty($_POST['order_id']) ) {
		
			$title = __t('Nowy spór w transkacji');
			$oid = (int)$_POST['order_id'];
			$order = ORM::Factory('Order', $oid);	
			$order->controversy = 1; 
			$order->ringleader_controversy = $user_id; 
			$order->controversy_text = addslashes($_POST['note_text']); 
			$order->save();
			
			$note_text = $order->controversy_text;
					$e_content = View::factory('email/controversy')
													->bind('user', $user)
													->bind('note_text', $note_text)
													->bind('order', $order);
					$from = array();
					$from[0] = Kohana::$config->load('site.email_business');
					$from[1] = Kohana::$config->load('site.appName');
			
					aurora::standardEmail(Kohana::$config->load('site.email_business'), $title,  $e_content);
			
					Message::success(__t('Wiadomość przesłana do administracji!'));
					$this->redirect('account/order');
		}
		
		
		$view = View::factory('account/order');
		
		
		
		$orders = ORM::Factory('Order');
		
		if( !empty( $filtr ) ) {
				$orders = $orders
							->where($filtr,'=', $filtr_value);
			}
			
		$orders = $orders->where('seller_id','=', $user_id)->order_by($sort, 'desc')->find_all();
	
        $this->template->content = $view
                        ->bind('title', $title)
						->bind('user', $user)
						->bind('sort', $sort)
						->bind('orders', $orders)
                        ->bind('errors', $errors)
						->bind('message_ok', $message_ok)
                        ->bind('message', $message);
	}
	
	public function action_order_detail() {

		$this->template->title = $title = 'Szczegóły zamówienia';
		$id = addslashes($_GET['order_id']);
		
		if( !empty( $id ) ) {
		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
		
		$user_id = Auth::instance()->get_user()->id;
		$user = ORM::Factory('User', $user_id);
		
		
		$view = View::factory('account/order_detail');
		
		$order = ORM::Factory('Order', $id);
	
        echo $view
                        ->bind('title', $title)
						->bind('user', $user)
						->bind('data', $order)
                        ->bind('errors', $errors)
						->bind('message_ok', $message_ok)
                        ->bind('message', $message);
		}			
						exit;
	}
		
	
	public function action_order_invoice() {
		
		$preview = false;
		
		$id = Request::current()->param('id');
	
		if( !Auth::instance()->logged_in() ) $this->redirect('/');
		
		$user_id = Auth::instance()->get_user()->id;
		
		

		$invoice = ORM::Factory('Order')->where('id','=', $id)->where('user_id','=', $user_id)->find();
		
		$user = ORM::Factory('User', $invoice->seller_id); // Seller
		
		if( $invoice->loaded() ) {
		
		
		$customer = $invoice->customer;
		defined('FPDF_FONTPATH') OR define('FPDF_FONTPATH','modules/fpdf/font/');
	
	$height = 10;
	
	require_once('modules/fpdf/fpdf.php');
	$faktura = new FPDF();
	$faktura->SetUTF8(true);
	$faktura->SetDisplayMode('real', 'single');
	$faktura->Open();
	$faktura->AddPage();
	$faktura->AddFont('arial_ce', "", "arial_ce.php");

	$faktura->SetCompression(false);  //włącza kompresję dokumentu

	/* a poniższe tylko dla ambitnych */
	$faktura->SetAuthor('Faktura VAT');  //ustawia autora dokumentu
	$faktura->SetCreator('Faktura VAT');  //ustawia generator dokumentu
	$faktura->SetSubject('Faktura VAT');  //ustawia temat dokumentu
	$faktura->SetTitle('Faktura VAT');  //ustawia tytuł dokumentu

	$faktura->SetDisplayMode(200);  //domyślne powiększenie dokumentu w przeglądarce
	//$faktura->SetMargins(10, 10 , 10);  //ustawia marginesy dla dokumentu
	//$faktura->Image('images/logo.jpg', 28, 15,127,77);					
	
	$z_x = 237;
	$y = 20;
	$faktura->SetFont('arial_ce','',11);	
	$faktura->MultiCell(0, $height-10,  'Data wystawienia: '.$invoice->date, 0, 'R', 0);
	
	$faktura->MultiCell(0, $height+20,  'Data sprzedaży: '.$invoice->date, 0, 'R', 0);
		
	$y += 30;
	if( !empty( $user->logo ) ) {
	$faktura->Image($user->logo, 10, 20, 193, 59); 
	}
	
	$faktura->SetFont('arial_ce','',22);	
	$faktura->MultiCell(0, $height+15, 'FAKTURA VAT', 0, 'C', 0);						
							
	$y += 5;				
	$faktura->SetFont('arial_ce','',12);		
	$faktura->MultiCell(0, $height,  'F/'.$invoice->id, 0, 'C', 0);
	
	$y += 5;				
	$faktura->SetFont('arial_ce','',6);		
	$faktura->MultiCell(0, $height,  __t('oryginał/kopia'), 0, 'C', 0);

	$faktura->SetFont('arial_ce','',11);	
	$faktura->SetXY(28, 112);
	$faktura->SetFillColor(170,170,170);
	$faktura->MultiCell(260, 20,  __t('Sprzedawca'), 1, 'C', 1);
	$faktura->MultiCell(260, 20,  'Firma', 'LRT', 'L', 0);
	$faktura->MultiCell(260, 20,  'Adres', 'LR', 'L', 0);
	$faktura->MultiCell(260, 20,  'Miasto', 'LR', 'L', 0);
	$faktura->MultiCell(260, 20,  'NIP', 'LRB', 'L', 0);
	
	$faktura->SetXY(305, 112);
	$faktura->MultiCell(260, 20,  __t('Nabywca'), 1, 'C', 1);
	$faktura->SetXY(305, 132);		
	$faktura->MultiCell(260, 20,  $customer->company.' '.$customer->firstname.' '.$customer->lastname, 'LRT', 'L', 0);
	$faktura->SetFont('arial_ce','',12);		
	$faktura->SetXY(305, 152);
	$faktura->MultiCell(260, 20,  $customer->street, 'LR', 'L', 0);
	$faktura->SetXY(305, 172);
	$city = $customer->city;
	$faktura->MultiCell(260, 20,  $customer->postcode.' '.$city, 'LR', 'L', 0);
	$faktura->SetXY(305, 192);
	$faktura->MultiCell(260, 20,  @$customer->nip, 'LRB', 'L', 0);
	
	$faktura->SetFillColor(255,255,255);
	
	$faktura->SetXY(28, 230);
	
	$faktura->SetFont('arial_ce','',6);	
	
	$faktura->MultiCell(15, 25, __t("Lp"), 1, 'C', 0);
	$faktura->SetXY(43, 230);
	$faktura->MultiCell(280, 25, __t("Nazwa"), 1, 'L', 0);
	$faktura->SetXY(323, 230);
	$faktura->MultiCell(30, 25, __t("PKWiU"), 1, 'C', 0);
	$faktura->SetXY(353, 230);
	$faktura->MultiCell(20, 25, __t("Ilość"), 1, 'C', 0);
	$faktura->SetXY(373, 230);
	$faktura->MultiCell(50, 25, __t("Cena jedn. netto"), 1, 'C', 0);
	$faktura->SetXY(423, 230);
	$faktura->MultiCell(40, 25, __t("Wart. netto"), 1, 'C', 0);
	$faktura->SetXY(463, 230);
	$faktura->MultiCell(60, 25, __t("Podatek"), 1, 'C', 0);
	$faktura->SetXY(523, 230);
	$faktura->MultiCell(42, 25, __t("Wart. brutto"), 1, 'C', 0);
	
//	$faktura->SetFont('arial_ce','',6);		
	
	$Y_POS = 255;
	
	$wartosc_netto = 0;
	$podatek = 0;
	$wartosc_brutto = 0;
	
	$suma_wartosc_netto = 0;
	$suma_podatek = 0;
	$suma_wartosc_brutto = 0;	
	
	$suma_wartosc_netto23 = 0;
	$suma_podatek23 = 0;
	$suma_wartosc_brutto23 = 0;	
	
	$suma_wartosc_netto8 = 0;
	$suma_podatek8 = 0;
	$suma_wartosc_brutto8 = 0;	
	
	$suma_wartosc_netto3 = 0;
	$suma_podatek3 = 0;
	$suma_wartosc_brutto3 = 0;	
	
	$suma_wartosc_netto0 = 0;
	$suma_podatek0 = 0;
	$suma_wartosc_brutto0 = 0;	
	
	$suma_wartosc_nettozw = 0;
	$suma_podatekzw = 0;
	$suma_wartosc_bruttozw = 0;	
	
	$data['titleposition_1'] = __t($invoice->title);
	$data['jmposition_1'] = __t('szt.');
	$data['pkwiu_1'] = '';
	$data['amountposition_1'] = 1;
	$data['priceposition_1'] = $invoice->price;
	$data['rateposition_1'] = $invoice->tax;

	for( $i = 1; $i < 2; $i++ ) {
	
	$titleposition = $data['titleposition_'.$i];
	$jmposition = $data['jmposition_'.$i];
	$pkwiu = $data['pkwiu_'.$i];
	$amountposition = $data['amountposition_'.$i];
	$priceposition = $data['priceposition_'.$i];
	$rateposition = $data['rateposition_'.$i];

	if( !empty( $titleposition ) ) {

		$wartosc_brutto = $invoice->price;
			
		$wartosc_netto = $invoice->netto;
		
		$podatek = $invoice->tax;
		

		$suma_wartosc_brutto += $wartosc_brutto;

		$suma_wartosc_netto += $wartosc_netto;

		$suma_podatek += $podatek;

		$faktura->SetXY(28, $Y_POS);
		
		$faktura->MultiCell(15, 25, $i.".", 1, 'C', 0);
		$faktura->SetXY(43, $Y_POS);
		$faktura->MultiCell(280, 25, $titleposition, 1, 'L', 0);
		$faktura->SetXY(323, $Y_POS);
		$faktura->MultiCell(30, 25, $pkwiu, 1, 'C', 0);
		$faktura->SetXY(353, $Y_POS);
		$faktura->MultiCell(20, 25, $amountposition, 1, 'C', 0);
		$faktura->SetXY(373, $Y_POS);
		$faktura->MultiCell(50, 25, number_format($wartosc_netto, 2, ',', ' '), 1, 'C', 0);
		$faktura->SetXY(423, $Y_POS);
		$faktura->MultiCell(40, 25, number_format($wartosc_netto, 2, ',', ' '), 1, 'C', 0);
		$faktura->SetXY(463, $Y_POS);
		$faktura->MultiCell(20, 25, "23%", 1, 'C', 0);
		$faktura->SetXY(483, $Y_POS);
		$faktura->MultiCell(40, 25, number_format($podatek, 2, ',', ' '), 1, 'C', 0);
		$faktura->SetXY(523, $Y_POS);
		$faktura->MultiCell(42, 25, number_format($wartosc_brutto, 2, ',', ' '), 1, 'C', 0);
		
		$Y_POS = $Y_POS+25;
		
	}
	
	}
	
	//$suma_wartosc_brutto = number_format($invoice->price, 2, ',', ' ');

	$faktura->SetXY(323, $Y_POS);
	$faktura->MultiCell(30, 25, __t("Razem"), 1, 'C', 0);
	$faktura->SetXY(353, $Y_POS);
	$faktura->MultiCell(20, 25, "", 1, 'C', 0);
	$faktura->SetXY(373, $Y_POS);
	$faktura->MultiCell(50, 25, "", 1, 'C', 0);
	$faktura->SetXY(423, $Y_POS);
	$faktura->MultiCell(40, 25, number_format($suma_wartosc_netto, 2, ',', ' '), 1, 'C', 0);
	$faktura->SetXY(463, $Y_POS);
	$faktura->MultiCell(20, 25, "X", 1, 'C', 0);
	$faktura->SetXY(483, $Y_POS);
	$faktura->MultiCell(40, 25, number_format($suma_podatek, 2, ',', ' '), 1, 'C', 0);
	$faktura->SetXY(523, $Y_POS);
	$faktura->MultiCell(42, 25,  number_format($invoice->price, 2, ',', ' '), 1, 'C', 0);

	$Y_POS = $Y_POS+25;

	$Y = $faktura->getY()+20;

	$slownie = cms::words2pay($suma_wartosc_brutto);

	$faktura->SetXY(28, $Y);
	$payment_method = __t('przelew');
	$faktura->MultiCell(0, 15, __t("Termin płatności").": ".date('d-m-Y', strtotime($invoice->date)+300*24*Kohana::$config->load('site.maturity'))."\n".__t("Sposób płatności").": ".$payment_method."\n".__t("Zapłacono").": 0,00 zł\n".__t("Wartosc brutto").": ".$suma_wartosc_brutto." zł\n".__t("Słownie").": ".$slownie."\n".__t("Nazwa banku").": ".$user->billing_bank."\n".__t("Numer konta").": ".$user->billing_bank_account , 1, 'L', 0);
	
	//$faktura->SetXY(415, $Y);
	
	//$faktura->MultiCell(150, 25, "Całkowita kwota:  10 000,00 PLN\nZapłacono: 10 000,00 PLN\nDo zapłaty: 10 000,00 PLN" , 1, 'R', 0);
	
	$Y += 145;
	
	$faktura->SetXY(28, $Y);
	
	$faktura->SetFont('arial_ce','',6);	
	
	$faktura->MultiCell(300, 10, "--------------------------\nPodpis osoby upoważnionej do\nwystawienia faktury" , 0, 'L', 0);
	
	$faktura->SetXY(365, $Y);
	
	$faktura->MultiCell(200, 10, "--------------------------\nPodpis osoby upoważnionej do\nodbioru faktury" , 0, 'R', 0);
	
	$Y += 75;
	
	$faktura->SetXY(28, $Y);
	
	$faktura->MultiCell(0, 10, " " , 0, 'C', 0);
	
	$Y += 25;
	$faktura->SetXY(28, $Y);

	$rand = rand(1,100);
	
	$file_name = 'uploads/pdf/fv_'.md5($id).'.pdf';
	
		if( $preview ) {
			$faktura->Output();
			
		} else {
			$faktura->Output($file_name,'F');	
					
			$invoice->file_name = $file_name;
			$invoice->save();
			
			$this->redirect($file_name);
		}
		
		} else {
			$this->redirect('account/order');
		}
		exit;
	
	}	
	
	public function action_invoice() {
		
		$preview = false;
		
		$id = Request::current()->param('id');

		if( !Auth::instance()->logged_in() ) $this->redirect('/');
		
		$user_id = Auth::instance()->get_user()->id;
		
		

		$invoice = ORM::Factory('invoice')->where('id','=', $id)->where('customers_id','=', $user_id)->find();
		
		$user = ORM::Factory('User', $invoice->user_id); // Seller
		$customer = ORM::Factory('User', $invoice->customers_id); 
		
		if( $invoice->loaded() ) {
	
		defined('FPDF_FONTPATH') OR define('FPDF_FONTPATH','modules/fpdf/font/');
	
	$height = 10;
	
	require_once('modules/fpdf/fpdf.php');
	$faktura = new FPDF();
	$faktura->SetUTF8(true);
	$faktura->SetDisplayMode('real', 'single');
	$faktura->Open();
	$faktura->AddPage();
	$faktura->AddFont('arial_ce', "", "arial_ce.php");

	$faktura->SetCompression(false);  //włącza kompresję dokumentu

	/* a poniższe tylko dla ambitnych */
	$faktura->SetAuthor('Faktura VAT');  //ustawia autora dokumentu
	$faktura->SetCreator('Faktura VAT');  //ustawia generator dokumentu
	$faktura->SetSubject('Faktura VAT');  //ustawia temat dokumentu
	$faktura->SetTitle('Faktura VAT');  //ustawia tytuł dokumentu

	$faktura->SetDisplayMode(200);  //domyślne powiększenie dokumentu w przeglądarce
	//$faktura->SetMargins(10, 10 , 10);  //ustawia marginesy dla dokumentu
	//$faktura->Image('images/logo.jpg', 28, 15,127,77);					
	
	$z_x = 237;
	$y = 20;
	$faktura->SetFont('arial_ce','',11);	
	$faktura->MultiCell(0, $height-10,  'Data wystawienia: '.$invoice->date, 0, 'R', 0);
	
	$faktura->MultiCell(0, $height+20,  'Data sprzedaży: '.$invoice->date, 0, 'R', 0);
		
	$y += 30;
	//if( !empty( $user->logo ) ) {
	//$faktura->Image($user->logo, 10, 20, 193, 59); 
	//}
	
	$faktura->SetFont('arial_ce','',22);	
	$faktura->MultiCell(0, $height+15, 'FAKTURA VAT', 0, 'C', 0);						
							
	$y += 5;				
	$faktura->SetFont('arial_ce','',12);		
	$faktura->MultiCell(0, $height,  'F/'.$invoice->id, 0, 'C', 0);
	
	$y += 5;				
	$faktura->SetFont('arial_ce','',6);		
	$faktura->MultiCell(0, $height,  __t('oryginał/kopia'), 0, 'C', 0);

	$faktura->SetFont('arial_ce','',11);	
	$faktura->SetXY(28, 112);
	$faktura->SetFillColor(170,170,170);
	$faktura->MultiCell(260, 20,  __t('Sprzedawca'), 1, 'C', 1);
	$faktura->MultiCell(260, 20,  $user->company, 'LRT', 'L', 0);
	$faktura->MultiCell(260, 20,  $user->street, 'LR', 'L', 0);
	$faktura->MultiCell(260, 20,  $user->city, 'LR', 'L', 0);
	$faktura->MultiCell(260, 20,  $user->nip, 'LRB', 'L', 0);
	
	$faktura->SetXY(305, 112);
	$faktura->MultiCell(260, 20,  __t('Nabywca'), 1, 'C', 1);
	$faktura->SetXY(305, 132);		
	$faktura->MultiCell(260, 20,  $customer->company.' '.$customer->firstname.' '.$customer->lastname, 'LRT', 'L', 0);
	$faktura->SetFont('arial_ce','',12);		
	$faktura->SetXY(305, 152);
	$faktura->MultiCell(260, 20,  $customer->street, 'LR', 'L', 0);
	$faktura->SetXY(305, 172);
	$city = $customer->city;
	$faktura->MultiCell(260, 20,  $customer->postcode.' '.$city, 'LR', 'L', 0);
	$faktura->SetXY(305, 192);
	$faktura->MultiCell(260, 20,  @$customer->nip, 'LRB', 'L', 0);
	
	$faktura->SetFillColor(255,255,255);
	
	$faktura->SetXY(28, 230);
	
	$faktura->SetFont('arial_ce','',6);	
	
	$faktura->MultiCell(15, 25, __t("Lp"), 1, 'C', 0);
	$faktura->SetXY(43, 230);
	$faktura->MultiCell(280, 25, __t("Nazwa"), 1, 'L', 0);
	$faktura->SetXY(323, 230);
	$faktura->MultiCell(30, 25, __t("PKWiU"), 1, 'C', 0);
	$faktura->SetXY(353, 230);
	$faktura->MultiCell(20, 25, __t("Ilość"), 1, 'C', 0);
	$faktura->SetXY(373, 230);
	$faktura->MultiCell(50, 25, __t("Cena jedn. netto"), 1, 'C', 0);
	$faktura->SetXY(423, 230);
	$faktura->MultiCell(40, 25, __t("Wart. netto"), 1, 'C', 0);
	$faktura->SetXY(463, 230);
	$faktura->MultiCell(60, 25, __t("Podatek"), 1, 'C', 0);
	$faktura->SetXY(523, 230);
	$faktura->MultiCell(42, 25, __t("Wart. brutto"), 1, 'C', 0);
	
//	$faktura->SetFont('arial_ce','',6);		
	
	$Y_POS = 255;
	
	$wartosc_netto = 0;
	$podatek = 0;
	$wartosc_brutto = 0;
	
	$suma_wartosc_netto = 0;
	$suma_podatek = 0;
	$suma_wartosc_brutto = 0;	
	
	$suma_wartosc_netto23 = 0;
	$suma_podatek23 = 0;
	$suma_wartosc_brutto23 = 0;	
	
	$suma_wartosc_netto8 = 0;
	$suma_podatek8 = 0;
	$suma_wartosc_brutto8 = 0;	
	
	$suma_wartosc_netto3 = 0;
	$suma_podatek3 = 0;
	$suma_wartosc_brutto3 = 0;	
	
	$suma_wartosc_netto0 = 0;
	$suma_podatek0 = 0;
	$suma_wartosc_brutto0 = 0;	
	
	$suma_wartosc_nettozw = 0;
	$suma_podatekzw = 0;
	$suma_wartosc_bruttozw = 0;	
	
	$data['titleposition_1'] = __t($invoice->title);
	$data['jmposition_1'] = __t('szt.');
	$data['pkwiu_1'] = '';
	$data['amountposition_1'] = 1;
	$data['priceposition_1'] = $invoice->price;
	$data['rateposition_1'] = $invoice->tax;

	for( $i = 1; $i < 2; $i++ ) {
	
	$titleposition = $data['titleposition_'.$i];
	$jmposition = $data['jmposition_'.$i];
	$pkwiu = $data['pkwiu_'.$i];
	$amountposition = $data['amountposition_'.$i];
	$priceposition = $data['priceposition_'.$i];
	$rateposition = $data['rateposition_'.$i];

	if( !empty( $titleposition ) ) {

		$wartosc_brutto = $invoice->price;
			
		$wartosc_netto = $invoice->netto;
		
		$podatek = $invoice->tax;
		

		$suma_wartosc_brutto += $wartosc_brutto;

		$suma_wartosc_netto += $wartosc_netto;

		$suma_podatek += $podatek;

		$faktura->SetXY(28, $Y_POS);
		
		$faktura->MultiCell(15, 25, $i.".", 1, 'C', 0);
		$faktura->SetXY(43, $Y_POS);
		$faktura->MultiCell(280, 25, $titleposition, 1, 'L', 0);
		$faktura->SetXY(323, $Y_POS);
		$faktura->MultiCell(30, 25, $pkwiu, 1, 'C', 0);
		$faktura->SetXY(353, $Y_POS);
		$faktura->MultiCell(20, 25, $amountposition, 1, 'C', 0);
		$faktura->SetXY(373, $Y_POS);
		$faktura->MultiCell(50, 25, number_format($wartosc_netto, 2, ',', ' '), 1, 'C', 0);
		$faktura->SetXY(423, $Y_POS);
		$faktura->MultiCell(40, 25, number_format($wartosc_netto, 2, ',', ' '), 1, 'C', 0);
		$faktura->SetXY(463, $Y_POS);
		$faktura->MultiCell(20, 25, "23%", 1, 'C', 0);
		$faktura->SetXY(483, $Y_POS);
		$faktura->MultiCell(40, 25, number_format($podatek, 2, ',', ' '), 1, 'C', 0);
		$faktura->SetXY(523, $Y_POS);
		$faktura->MultiCell(42, 25, number_format($wartosc_brutto, 2, ',', ' '), 1, 'C', 0);
		
		$Y_POS = $Y_POS+25;
		
	}
	
	}
	
	//$suma_wartosc_brutto = number_format($invoice->price, 2, ',', ' ');

	$faktura->SetXY(323, $Y_POS);
	$faktura->MultiCell(30, 25, __t("Razem"), 1, 'C', 0);
	$faktura->SetXY(353, $Y_POS);
	$faktura->MultiCell(20, 25, "", 1, 'C', 0);
	$faktura->SetXY(373, $Y_POS);
	$faktura->MultiCell(50, 25, "", 1, 'C', 0);
	$faktura->SetXY(423, $Y_POS);
	$faktura->MultiCell(40, 25, number_format($suma_wartosc_netto, 2, ',', ' '), 1, 'C', 0);
	$faktura->SetXY(463, $Y_POS);
	$faktura->MultiCell(20, 25, "X", 1, 'C', 0);
	$faktura->SetXY(483, $Y_POS);
	$faktura->MultiCell(40, 25, number_format($suma_podatek, 2, ',', ' '), 1, 'C', 0);
	$faktura->SetXY(523, $Y_POS);
	$faktura->MultiCell(42, 25,  number_format($invoice->price, 2, ',', ' '), 1, 'C', 0);

	$Y_POS = $Y_POS+25;

	$Y = $faktura->getY()+20;

	$slownie = cms::words2pay($suma_wartosc_brutto);

	$faktura->SetXY(28, $Y);
	$payment_method = __t('przelew');
	$faktura->MultiCell(0, 15, __t("Termin płatności").": ".date('d-m-Y', strtotime($invoice->date)+300*24*Kohana::$config->load('site.maturity'))."\n".__t("Sposób płatności").": ".$payment_method."\n".__t("Zapłacono").": 0,00 zł\n".__t("Wartosc brutto").": ".$suma_wartosc_brutto." zł\n".__t("Słownie").": ".$slownie."\n".__t("Nazwa banku").": ".$user->billing_bank."\n".__t("Numer konta").": ".$user->billing_bank_account , 1, 'L', 0);
	
	//$faktura->SetXY(415, $Y);
	
	//$faktura->MultiCell(150, 25, "Całkowita kwota:  10 000,00 PLN\nZapłacono: 10 000,00 PLN\nDo zapłaty: 10 000,00 PLN" , 1, 'R', 0);
	
	$Y += 145;
	
	$faktura->SetXY(28, $Y);
	
	$faktura->SetFont('arial_ce','',6);	
	
	$faktura->MultiCell(300, 10, "--------------------------\nPodpis osoby upoważnionej do\nwystawienia faktury" , 0, 'L', 0);
	
	$faktura->SetXY(365, $Y);
	
	$faktura->MultiCell(200, 10, "--------------------------\nPodpis osoby upoważnionej do\nodbioru faktury" , 0, 'R', 0);
	
	$Y += 75;
	
	$faktura->SetXY(28, $Y);
	
	$faktura->MultiCell(0, 10, " " , 0, 'C', 0);
	
	$Y += 25;
	$faktura->SetXY(28, $Y);

	$rand = rand(1,100);
	
	$file_name = 'uploads/pdf/fv_'.md5($id).'.pdf';
	
		if( $preview ) {
			$faktura->Output();
			
		} else {
			$faktura->Output($file_name,'F');	
					
			$invoice->file_name = $file_name;
			$invoice->save();
			
			$this->redirect($file_name);
		}
		
		} else {
			$this->redirect('account/earning');
		}
		exit;
	
	}
	
   public function action_edit() {

        $this->template->title = $title = 'Moje dane';

		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
		
		$user_id = Auth::instance()->get_user()->id;
	
		$user = ORM::Factory('moderator_user', $user_id );
		$_user = ORM::Factory('user', $user_id );
		
		$view = View::factory('account/edit');
		
		$gallery = array();
		
		if( $user->profile_id == 2 ) {
		
			$gallery = ORM::Factory('moderator_gallery')->where('user_id','=', $user->id)->find();
			
				if( $gallery->loaded() ) {  } else {
			
					$gallery = ORM::Factory('moderator_gallery');
					$gallery->user_id = $user_id;
					$gallery->save();
					//$gallery_ = ORM::Factory('gallery');
					//$gallery_->user_id = $user_id;
				}
		}
		
		if ($_POST) {
				$data = ac_form::clear_form_data($_POST);
				
				
			
				if( !empty( $data['description_tab'] ) AND $data['description_tab'] == "change_description_file" ) {
				
				if( $user->profile_id == 2 ) {
					$gallery->gallery_content = $data['description'];
					$user->description = $data['description'];
					$gallery->save();
				} else {
					$user->description = $data['description'];
				}
				
					if( $_FILES ) {
					$uploads_dir = 'uploads/user/images/';
					
					
						$name = $_FILES['logo']['name'];
						$tmp_name = $_FILES['logo']['tmp_name'];
						if( move_uploaded_file($tmp_name, "$uploads_dir/$name") AND !empty( $name )) {
							$user->logo = $name;
						}
					
					}
				}
				
				
				if( !empty( $data['action'])) {
					
					$test_user = ORM::Factory('moderator_user')
								->where('username','=', $data['username'])
								->where('id','!=', $user_id)
								->find();
								
					if( $test_user->loaded() ) {
						Message::success(__t('Użytkownik już istnieje w bazie danych.'));
						$this->redirect('account/edit');
					} 
					
					$user->newsletter = 0;
					$user->newsletter2 = 0;
					
					foreach( $data as $key => $val) {
						if($key != 'action' AND $key != 'gallery_type' ) {
							$user->{$key} = @$val;
						}
					}
					
					if( $user->profile_id == 2 ) {
						$gallery->gallery_name = $data['company'];
						$gallery->gallery_type = $data['gallery_type'];
						$gallery->save();
					}
				
				} else {
				
				
				
				if( !empty( $data['email'] ) ) {
					
					if( $user->email ==  $data['email'] ) {
						Message::success(__t('Podany e-mail jest taki sam jak bieżący.'));
						$this->redirect('account/edit');
					} 
					
					//$user->email  = $data['email'];
					$title = __t('Potwierdzenie emaila');
				   
						$link = "<a href='http://".Kohana::$config->load('site.domain')."/Account/activate_email/".$user->email."/".md5($user->id)."/".$data['email']."' target='blank'>Aktywacja</a>";
					
						$e_content = View::factory('email/change_email')
												->bind('link', $link)
												->bind('user', $user);
						$from = array();
						$from[0] = Kohana::$config->load('site.email_business');
						$from[1] = Kohana::$config->load('site.appName');
					
						if(aurora::standardEmail( $data['email'], $title,  $e_content) ) {
							
							Message::success('Odbierz e-mail aktywacyjny, aby zmienić email w serwisie.');
							$this->redirect('account/edit');
						} else {
						
						}
						
						
				}
				
				if( !empty( $data['password'] ) ) {
					
					$user_password = ORM::Factory('User', $user_id );
					
					if( $user_password->password == Auth::instance()->hash($data['oldpassword']) ) {
				
					if( $user_password->password ==  Auth::instance()->hash($data['password']) ) {
					Message::success(__t('Podane hasło jest takie same jak bieżące.'));
					$this->redirect('account/edit');
					} 
					$user_password->password  = $data['password'];
					$user_password->save();
					}
					else {
					Message::success(__t('Hasła są różne.'));
					$this->redirect('account/edit');
					}
					
					Message::success(__t('Zmiany zostały zapisane!'));
					$this->redirect('account/edit');
				
				} 
				
				}
				
				$user->is_change = 1;
				$user->save();
				
				
				//cms::confirmAdmin(Request::current()->controller(), Request::current()->action());
				Message::success(__t('Zmiany zostały zapisane i oczekują na akceptację moderatora!'));
				$this->redirect('account/edit');
			//}
			
		}

        $this->template->content = $view
                        ->bind('title', $title)
						->bind('user', $user)
						->bind('_user', $_user)
						->bind('gallery', $gallery)
                        ->bind('errors', $errors)
						->bind('message_ok', $message_ok)
                        ->bind('message', $message);
    }	
	
	 public function action_photos() {

        $this->template->title = $title = 'Moje zdjęcia';

		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
		
		$user_id = Auth::instance()->get_user()->id;
		$user = ORM::Factory('User', $user_id );
		
		$gallery = ORM::Factory('gallery')->where('user_id','=', $user_id)->find();
		
		$view = View::factory('account/photos');
		
		if( !empty ($_GET['delete'] ) ) {
			$d = addslashes($_GET['delete']);
			$f = ORM::Factory('galleryimage2gallery')->where('galleryImage_id','=', $d)->find();
			if( $f->gallery_id == $gallery->gallery_id ) {
				$f->delete();
				ORM::Factory('galleryimage', $d)->delete();

				$this->redirect('account/photos');
			}
		}
		
		if( $_FILES ) {
	
			$uploads_dir = 'uploads/user/photos/';
					
					for( $i=0; $i<count($_FILES['photos']['name']);$i++) {
						$name = $_FILES['photos']['name'][$i];
						$tmp_name = $_FILES['photos']['tmp_name'][$i];
						if( move_uploaded_file($tmp_name, "$uploads_dir/$name") AND !empty( $name )) {
							$path = "$uploads_dir/$name";
							$gi = ORM::Factory('galleryimage');
							$gi->galleryImage_image = $path;
							$gi->save();
							
							$g2i = ORM::Factory('galleryimage2gallery');
							$g2i->galleryImage_id = $gi->galleryImage_id;
							$g2i->gallery_id = $gallery->gallery_id;
							$g2i->save();
						}
					}
			
				Message::success(__t('Zmiany zostały zapisane.'));
				$this->redirect('account/photos');
		
			
		}
		
		
		$galleryImages = DB::query( Database::SELECT , "SELECT * FROM galleryImage gI left join galleryImage_2_gallery gI_2_g on (gI_2_g.galleryImage_id = gI.galleryImage_id )  left join gallery g on (g.gallery_id = gI_2_g.gallery_id) WHERE g.gallery_id = '$gallery->gallery_id'")->as_object()->execute();
		
        $this->template->content = $view
                        ->bind('title', $title)
						->bind('user', $user)
						->bind('galleryImages', $galleryImages)
                        ->bind('errors', $errors)
						->bind('message_ok', $message_ok)
                        ->bind('message', $message);
    }	
	
	
	public function action_edit_password() {

        $this->template->title = $title = 'Moje hasło';

		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
		
				
		$user = ORM::Factory('User', Auth::instance()->get_user()->id );
		
		$view = View::factory('account/edit_password');
		
		if ($_POST) {
				$data = ac_form::clear_form_data($_POST);
				
				if( !empty( $data['action'])) {
				$user->newsletter = 0;
				$user->newsletter2 = 0;
					foreach( $data as $key => $val) {
						if($key != 'action' ) {
							$user->{$key} = @$val;
						}
					}
					
				} else {
				
				if( !empty( $data['email'] ) ) {
				
					if( $user->email ==  $data['email'] ) {
						Message::success(__t('Podany e-mail jest taki sam jak bieżący.'));
						$this->redirect('account/edit');
					} 
					
					//$user->email  = $data['email'];
					$title = __t('Potwierdzenie emaila');
				   
						$link = "<a href='http://".Kohana::$config->load('site.domain')."/Account/activate_email/".$user->email."/".md5($user->id)."/".$data['email']."' target='blank'>Aktywacja</a>";
					
						$e_content = View::factory('email/change_email')
												->bind('link', $link)
												->bind('user', $user);
						$from = array();
						$from[0] = Kohana::$config->load('site.email_business');
						$from[1] = Kohana::$config->load('site.appName');
					
						if(aurora::standardEmail( $data['email'], $title,  $e_content) ) {
							
							Message::success('Odbierz e-mail aktywacyjny, aby zmienić email w serwisie.');
							$this->redirect('account/edit');
						} else {
						
						}
						
						
				}
				
				if( !empty( $data['password'] ) AND $user->password == Auth::instance()->hash($data['oldpassword']) ) {
					if( $user->password ==  Auth::instance()->hash($data['password']) ) {
					Message::success(__t('Podane hasło jest takie same jak bieżące.'));
					$this->redirect('account/edit');
					} 
					$user->password  = $data['password'];
				
				} else {
				Message::success(__t('Hasła są różne.'));
				$this->redirect('account/edit');
				}
				
				}
				
				$user->save();
				
				Message::success(__t('Zmiany zostały zapisane.'));
				$this->redirect('account/edit');
			//}
			
		}

        $this->template->content = $view
                        ->bind('title', $title)
						->bind('user', $user)
                        ->bind('errors', $errors)
						->bind('message_ok', $message_ok)
                        ->bind('message', $message);
    }	

	public function action_edit_email() {

        $this->template->title = $title = 'Mój e-mail';

		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
		
				
		$user = ORM::Factory('User', Auth::instance()->get_user()->id );
		
		$view = View::factory('account/edit_email');
		
		if ($_POST) {
				$data = ac_form::clear_form_data($_POST);
				
				if( !empty( $data['action'])) {
				$user->newsletter = 0;
				$user->newsletter2 = 0;
					foreach( $data as $key => $val) {
						if($key != 'action' ) {
							$user->{$key} = @$val;
						}
					}
					
				} else {
				
				if( !empty( $data['email'] ) ) {
				
					if( $user->email ==  $data['email'] ) {
						Message::success(__t('Podany e-mail jest taki sam jak bieżący.'));
						$this->redirect('account/edit');
					} 
					
					//$user->email  = $data['email'];
					$title = __t('Potwierdzenie emaila');
				   
						$link = "<a href='http://".Kohana::$config->load('site.domain')."/Account/activate_email/".$user->email."/".md5($user->id)."/".$data['email']."' target='blank'>Aktywacja</a>";
					
						$e_content = View::factory('email/change_email')
												->bind('link', $link)
												->bind('user', $user);
						$from = array();
						$from[0] = Kohana::$config->load('site.email_business');
						$from[1] = Kohana::$config->load('site.appName');
					
						if(aurora::standardEmail( $data['email'], $title,  $e_content) ) {
							
							Message::success('Odbierz e-mail aktywacyjny, aby zmienić email w serwisie.');
							$this->redirect('account/edit');
						} else {
						
						}
						
						
				}
				
				if( !empty( $data['password'] ) AND $user->password == Auth::instance()->hash($data['oldpassword']) ) {
					if( $user->password ==  Auth::instance()->hash($data['password']) ) {
					Message::success(__t('Podane hasło jest takie same jak bieżące.'));
					$this->redirect('account/edit');
					} 
					$user->password  = $data['password'];
				
				} else {
				Message::success(__t('Hasła są różne.'));
				$this->redirect('account/edit');
				}
				
				}
				
				$user->save();
				
				Message::success(__t('Zmiany zostały zapisane.'));
				$this->redirect('account/edit');
			//}
			
		}

        $this->template->content = $view
                        ->bind('title', $title)
						->bind('user', $user)
                        ->bind('errors', $errors)
						->bind('message_ok', $message_ok)
                        ->bind('message', $message);
    }	

    public function action_news() {
		
		$action = Request::current()->param('act');
		$id = Request::current()->param('id');
		$children = array();
		
        $this->template->title = $title = 'Twoje aktualności';
		
		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
	
		$user_id = Auth::instance()->get_user()->id;
		$user = ORM::Factory('User', $user_id);
		if( empty( $action ) ) {
			$view = View::Factory('account/news');	
			$news = ORM::Factory('moderator_news')->where('user_id','=', $user_id)->or_where('owner_id','=', $user_id)->find_all();
			
		} else {
			$children = ORM::Factory('user')->where('parent','=', $user_id)->find_all();
			
			$view = View::Factory('account/news_edit');
			if( !empty( $id) ) {
				$news = ORM::Factory('moderator_news', $id);
			} else {
					$news = ORM::Factory('moderator_news');
			}
			
			if ($_POST) {
				
				$data = ac_form::clear_form_data($_POST);
				
				$get_gallery = ORM::Factory('moderator_gallery')->where('user_id','=', (int)$data['parent'])->find();
				$news->title = $data['title'];
				$news->description = $data['description'];
				$news->user_id = $get_gallery->gallery_id;
				$news->owner_id = $user_id;
				
				if( $_FILES ) {
					$uploads_dir = 'uploads/article/';
						$name = $_FILES['thumb']['name'];
						$tmp_name = $_FILES['thumb']['tmp_name'];
						if( move_uploaded_file($tmp_name, "$uploads_dir/$name")) {
							$news->thumb = "$uploads_dir/$name";
						}	
				}
				
				$news->date = strtotime($data['date']);
				$news->status = 0;
				if( !empty($data['fb_event']) ) {
					$news->fb_event =  1;
				}
				$news->is_change = 1;
				$news->save();
				
				cms::confirmAdmin(Request::current()->controller(), Request::current()->action());
				Message::success(__t('Zmiany zostały zapisane i oczekują na akceptację moderatora!'));
				$this->redirect('account/news');
			
			}
		}
		
		
		if( $action == "delete" AND !is_null( $id ) ) {
			
			ORM::Factory('News')->where('id','=', $id)->where('user_id','=',$user_id)->find()->delete();
			ORM::Factory('moderator_news')->where('id','=', $id)->where('user_id','=',$user_id)->find()->delete();
			
			Message::success('Akcja wykonana pomyślnie.');
			$this->redirect('account/news');
		}
		
        $this->template->content = $view
                        ->bind('title', $title)
						->bind('children', $children)
						->bind('news', $news)
						->bind('user', $user)
						->bind('user_id', $user_id)
                        ->bind('errors', $errors)
						->bind('message_ok', $message_ok)
                        ->bind('message', $message);
    }
	
	   public function action_article() {
		
		$action = Request::current()->param('act');
		$id = Request::current()->param('id');
		$children = array();
		
        $this->template->title = $title = 'Twoje artykuły';
		
		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
	
		$user_id = Auth::instance()->get_user()->id;
		$user = ORM::Factory('User', $user_id);
		if( empty( $action ) ) {
			$view = View::Factory('account/article');	
			$news = ORM::Factory('moderator_article')->where('user_id','=', $user_id)->or_where('owner_id','=', $user_id)->find_all();
			
		} else {
			$children = ORM::Factory('user')->where('parent','=', $user_id)->find_all();
			
			$view = View::Factory('account/article_edit');
			if( !empty( $id) ) {
				$news = ORM::Factory('moderator_article', $id);
			} else {
					$news = ORM::Factory('moderator_article');
			}
			
			if ($_POST) {
			
				$data = ac_form::clear_form_data($_POST);
				
				$get_gallery = ORM::Factory('moderator_gallery')->where('user_id','=', (int)$data['parent'])->find();
				
				$news->title = $data['title'];
				$news->description = $data['description'];
				$news->date = time();
				$news->user_id = $get_gallery->gallery_id;
				$news->owner_id = $user_id;
				$news->status = 0;
				$news->is_change = 1;
				$news->save();
				
				cms::confirmAdmin(Request::current()->controller(), Request::current()->action());
				Message::success(__t('Zmiany zostały zapisane i oczekują na akceptację moderatora!'));
				$this->redirect('account/article');
			
			}
		}
		
		
		if( $action == "delete" AND !is_null( $id ) ) {
			
			ORM::Factory('article')->where('id','=', $id)->where('user_id','=',$user_id)->find()->delete();
			ORM::Factory('moderator_article')->where('id','=', $id)->where('user_id','=',$user_id)->find()->delete();
			
			Message::success('Akcja wykonana pomyślnie.');
			$this->redirect('account/article');
		}
		
        $this->template->content = $view
                        ->bind('title', $title)
						->bind('children', $children)
						->bind('news', $news)
						->bind('user', $user)
						->bind('user_id', $user_id)
                        ->bind('errors', $errors)
						->bind('message_ok', $message_ok)
                        ->bind('message', $message);
    }

    public function action_gallery() {
		
		$action = Request::current()->param('act');
		$id = Request::current()->param('id');
		
        $this->template->title = $title = 'Twoja galeria';
		
		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
		
		if( Auth::instance()->get_user()->profile_id != 2 ) $this->redirect('Account/artist');
		$user_id = Auth::instance()->get_user()->id;
		
		$is_gallery = ORM::Factory('gallery')->where('user_id','=', $user_id)->find()->loaded();
		
		if( empty( $action ) ) {
			$view = View::Factory('account/gallery');	
			$gallery = ORM::Factory('gallery')->where('user_id','=', $user_id)->find_all();
		} elseif( $action == "photos" ) {
			$view = View::Factory('account/gallery_photos');
			$gallery = ORM::factory('gallery', $id);
			$galleryImages = DB::query( Database::SELECT , "SELECT * FROM galleryImage gI left join galleryImage_2_gallery gI_2_g on (gI_2_g.galleryImage_id = gI.galleryImage_id )  left join gallery g on (g.gallery_id = gI_2_g.gallery_id) WHERE g.gallery_id = '$id'")->execute();
		
		
		} elseif( $action == "edit" ) {
			$view = View::Factory('account/gallery_edit');
			if( !empty( $id) ) {
				$gallery = ORM::Factory('gallery', $id);
			} else {
					$gallery = ORM::Factory('gallery');
			}
			
			if ($_POST) {
			
				//$data = ac_form::clear_form_data($_POST);
				$data = $_POST;
				$gallery->gallery_name = $data['title'];
				$gallery->gallery_content = $data['description'];
				$gallery->user_id = $user_id;
				$gallery->status = 0;
				$gallery->save();
				/*
				if( $_FILES ) {
					$uploads_dir = 'uploads/gallery/';
					
					for( $i=0; $i < count( $_FILES['images']['name']) ; $i++ ) {
						$name = $_FILES['images']['name'][$i];
						$tmp_name = $_FILES['images']['tmp_name'][$i];
						if( move_uploaded_file($tmp_name, "$uploads_dir/$name") AND !empty( $name )) {
							$gallery_image = ORM::Factory('gallery_image');
							$gallery_image->name = "$uploads_dir/$name";
							$gallery_image->item_id = $gallery->gallery_id;
							$gallery_image->save();
						}
					}
				}
				
				$gallery->save();
				*/
				
				$this->redirect('account/gallery');
			
			}
		}
		
		
		if( $action == "delete" AND !is_null( $id ) ) {
			
			ORM::Factory('gallery')->where('id','=', $id)->where('user_id','=',$user_id)->find()->delete();
			
			Message::success('Akcja wykonana pomyślnie.');
			$this->redirect('account/gallery');
		}
		
        $this->template->content = $view
                        ->bind('title', $title)
						->bind('gallery', $gallery)
						->bind('galleryImages', $galleryImages)
						->bind('is_gallery', $is_gallery)
                        ->bind('errors', $errors)
						->bind('message_ok', $message_ok)
                        ->bind('message', $message);
    }
	
    public function action_item() {

		$action = Request::current()->param('act');
		$id = Request::current()->param('id');
		
        $this->template->title = $title = 'Twoje prace';
		$sort = !empty($_GET['sort']) ? addslashes($_GET['sort']) : 'id';
		
		$categories_id = !empty($_GET['categories_id']) ? addslashes($_GET['categories_id']) : '';
		$techniques_id = !empty($_GET['techniques_id']) ? addslashes($_GET['techniques_id']) : '';
		$topics_id = !empty($_GET['topics_id']) ? addslashes($_GET['topics_id']) : '';
		$types_id = !empty($_GET['types_id']) ? addslashes($_GET['types_id']) : '';
		$tags = !empty($_GET['tags']) ? addslashes($_GET['tags']) : '';
		$price = !empty($_GET['price']) ? addslashes($_GET['price']) : '';
		
		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
	
		$user_id = Auth::instance()->get_user()->id;
		$user = ORM::Factory('User', $user_id);
		$images = array();
		$children = array();
		
		if( !empty ($_GET['delete'] ) ) {
			$d = addslashes($_GET['delete']);
			$f = ORM::Factory('item_image')->where('id','=', $d)->find();
			if( $id == $f->item_id ) {
				$f->delete();
			
				$this->redirect('account/item/edit/'.$id);
			}
		}
		
		if( empty( $action ) ) {
			$view = View::Factory('account/item');	
			$item = ORM::Factory('moderator_item')
					->and_where_open()
					->where('owner_id','=', $user_id)
					->or_where('user_id','=', $user_id)
					->and_where_close();
					
					
					
			if( !empty( $price ) ) {
				$price = explode("_", $price);
				$item = $item
							->where('moderator_item.price','>=', $price[0])
							->where('moderator_item.price','=<', $price[1]);
			}
			
			if( !empty( $categories_id ) ) {
				$item = $item
							->where('moderator_item.categories_id','=', $categories_id);
			}
			
			if( !empty( $techniques_id ) ) {
				$item = $item
							->where('moderator_item.techniques_id','=', $techniques_id);
			}
			
			if( !empty( $topics_id ) ) {
				$item = $item
							->where('moderator_item.topics_id','=', $topics_id);
			}
			
			if( !empty( $tags ) ) {
				$item = $item
						->where('moderator_item.tags','LIKE', '%'.$tags.'%');
			}
			
			$item = $item->find_all();
			
			$item2 = DB::Query(Database::SELECT, "SELECT items.* FROM items LEFT JOIN users ON users.id = items.owner_id WHERE users.parent = '$user_id'")->as_object()->execute();

		} else {
			$view = View::Factory('account/item_edit');
			$children = ORM::Factory('user')->where('parent','=', $user_id)->find_all();
			$item_type_link = array();
			$item_topic_link = array();
			
			if( !empty( $id) ) {
				$item = ORM::Factory('moderator_item', $id);
				
				$images = ORM::Factory('item_image')->where('item_id','=', $id)->order_by('order','asc')->find_all();
				
				foreach( ORM::Factory('item_topic_link')->where('id','=', $id)->find_all() as $itl ) {
					$item_topic_link[] = $itl->topics_id;
				}
				
				foreach( ORM::Factory('item_type_link')->where('id','=', $id)->find_all() as $itl ) {
					$item_type_link[] = $itl->types_id;
				}
			} 
			
			if ($_POST) {
				
				
				
				//$data = ac_form::clear_form_data($_POST);
				$data = $_POST;
				
				for( $y=1; $y<=10; $y++ ) {
				if( !empty( $data['upload_thumb'.$y] ) ) {
					if( empty( $id) ) {
						$item = ORM::Factory('moderator_item');
					} else {
						if( $y == 1 ) 
							$item = ORM::Factory('moderator_item', $id);
						else
							$item = ORM::Factory('moderator_item');
					}
					$item->title = empty($data['title']) ? 'Bez nazwy' : $data['title'];
					$item->description = $data['description'];
					if(!empty($data['personal_delivery']) OR ($data['main_type'] == "print")) echo "aa";
					
					$item->personal_delivery = (!empty($data['personal_delivery']) OR ($data['main_type'] == "print")) ? 1: 0;
					$item->can_print = !empty($data['can_print']) ? 1: 0;
					//$item->price = $data['price'];
					$item->price_original = $data['price'];
					$item->price_frame = @$data['price_frame'];
					$item->price_nice_frame = @$data['price_nice_frame'];
					$item->price_produce = @$data['price_produce'];
					$item->size = @$data['size'];
					$item->tags = $data['tags'];
					
					// zerowanie
					$item->manual = 0;
					$item->print = 0;
					$m_type = $data['main_type'];
					$item->{"$m_type"} = 1;
					$item->date = time();
					$item->shipping_cost = (int)@$data['shipping_cost'];
					if( empty( $data['parent'] ) )
						$item->user_id = $user_id;
					else 
						$item->user_id = (int)@$data['parent'];
					
					$item->owner_id = $user_id;
					$item->status = 1;
					$item->save();
					
					if( !empty( $data['categories_id_own'] ) ) {
						$c = ORM::Factory('item_category');
						$c->title = $data['categories_id_own'];
						$c->languages_id = 1;
						$c->status = 0;
						$c->user_id = $user_id;
						$c->save();
						$item->categories_id = $c->id;
					} else {
						$item->categories_id = $data['categories_id'];
					}
					if( !empty( $data['topics_id_own'] ) ) {
						$c = ORM::Factory('item_topic');
						$c->title = $data['topics_id_own'];
						$c->languages_id = 1;
						$c->user_id = $user_id;
						$c->status = 0;
						$c->save();
						
						$itl = ORM::Factory('item_topic_link');
						$itl->id = $item->id;
						$itl->topics_id = $c->id;
						$itl->save();
						
						$item->topics_id = $item->id;
					} else {
						$itl = ORM::Factory('item_topic_link')->where('id','=', $item->id)->find_all();
						foreach( $itl as $d ) $d->delete();
						// Dodaję...
						if( !empty( $data['topics_id']) AND is_array( $data['topics_id'] ) )  {
							foreach( $data['topics_id'] as $val ) {
								if( !empty( $val ) ) {
									$itl = ORM::Factory('item_topic_link');
									$itl->id = $item->id;
									$itl->topics_id = $val;
									$itl->save();
								}
							}
							$item->topics_id = $item->id;
						}
					}
					if( !empty( $data['types_id_own'] ) ) {
						$c = ORM::Factory('item_type');
						$c->title = $data['types_id_own'];
						$c->languages_id = 1;
						$c->user_id = $user_id;
						$c->status = 0;
						$c->save();
						
						$itl = ORM::Factory('item_type_link');
						$itl->id = $item->id;
						$itl->types_id = $c->id;
						$itl->save();
								
						$item->types_id = $item->id;
					} else {
						$itl = ORM::Factory('item_type_link')->where('id','=', $item->id)->find_all();
						foreach( $itl as $d ) $d->delete();
						// Dodaję...
						if( !empty( $data['types_id']) AND is_array( $data['types_id'] ) )  {
							foreach( $data['types_id'] as $val ) {
								if( !empty( $val ) ) {
									$itl = ORM::Factory('item_type_link');
									$itl->id = $item->id;
									$itl->types_id = $val;
									$itl->save();
								}
							}
							$item->types_id = $item->id;
						}
				
					}
					
					if( !empty( $data['techniques_id_own'] ) ) {
						$c = ORM::Factory('item_technique');
						$c->title = $data['techniques_id_own'];
						$c->languages_id = 1;
						$c->user_id = $user_id;
						$c->status = 0;
						$c->save();
						$item->techniques_id = $c->id;
					} else {
						$item->techniques_id = $data['techniques_id'];
					}
					
							
							
					//
					
					$item->save();
					
					for( $i=1; $i <= 5 ; $i++ ) {
								$name = $data['v_upload_thumb_'.$i];
							
								if( !empty( $name )) {
									$item_image = ORM::Factory('item_image');
									$item_image->name = "$name";
									$item_image->item_id = $item->id;
									$item_image->save();
								}
							}
							
						/*if( $_FILES) {
							$uploads_dir = 'uploads/items/';
							
							
							//$name = $_FILES['thumb']['name'];
							//$tmp_name = $_FILES['thumb']['tmp_name'];
							//if( move_uploaded_file($tmp_name, "$uploads_dir/$name") AND !empty( $name )) {
							
							//	$item->thumb = "$uploads_dir/$name";
							//}
							
							
							
		
							for( $i=0; $i < count( $_FILES['images']['name']) ; $i++ ) {
								$name = $_FILES['images']['name'][$i];
								$tmp_name = $_FILES['images']['tmp_name'][$i];
								if( move_uploaded_file($tmp_name, "$uploads_dir/$name") AND !empty( $name )) {
									$item_image = ORM::Factory('item_image');
									$item_image->name = "$uploads_dir/$name";
									$item_image->item_id = $item->id;
									$item_image->save();
								}
							}
						}
						*/
						
					$item->thumb = $data['upload_thumb'.$y];
					
					if( !empty($data['upload_thumb'.$y])) {
						
						$image = $data['upload_thumb'.$y];
						$sizes = GetImageSize($image); 
							
							$width = $sizes[0];
							$height = $sizes[1];

							$bleed = (28*5);
							$dst_x = 0;   // X-coordinate of destination point. 
							$dst_y = 0;   // Y --coordinate of destination point. 
							$src_x = $bleed; // Crop Start X position in original image
							$src_y = $bleed; // Crop Srart Y position in original image
							$dst_w = $width-($bleed*2); // Thumb width
							$dst_h = $height-($bleed*2); // Thumb height
							//$src_w = $src_x+$dst_w; // $src_x + $dst_w Crop end X position in original image
							//$src_h = $src_y+$dst_h; // $src_y + $dst_h Crop end Y position in original image
							$src_w = $width-($bleed*2);
							$src_h = $height-($bleed*2);
							

							// Creating an image with true colors having thumb dimensions.( to merge with the original image )
							$dst_image = imagecreatetruecolor($dst_w,$dst_h);
							// Get original image
							$src_image = imagecreatefromjpeg($image);
							// Cropping 
							imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
							// Saving 
							$img = explode(".", basename($image));
							$fname = "uploads/items/".$img[0]."_crop.jpg";
							@imagejpeg($dst_image, $fname);
							$item->cropped = $fname;
					}
					$item->is_change = 1;
					$item->save();
				
				}
				
				}
				
				cms::confirmAdmin(Request::current()->controller(), Request::current()->action());
				Message::success('Zmiany zapisane i czekają na akceptację moderatora!');
				$this->redirect('account/item');
			
			}
		}
		
		
		if( $action == "delete" AND !is_null( $id ) ) {
			
			ORM::Factory('moderator_item')->where('id','=', $id)->where('owner_id','=',$user_id)->find()->delete();
			$t = ORM::Factory('item')->where('id','=', $id)->where('owner_id','=',$user_id)->find();
			
			foreach( ORM::Factory('item_topic_link')->where('id','=', $id )->find_all() as $itl ) {
				$itl->delete();
			}
			
			foreach( ORM::Factory('item_type_link')->where('id','=', $id )->find_all() as $itl ) {
				$itl->delete();
			}
			
			if( $t->loaded() ) $t->delete();
			
			Message::success('Akcja wykonana pomyślnie.');
			$this->redirect('account/item');
		}
		
		$techniques = ORM::Factory('item_technique')->where('status','=', 1)->order_by('order','asc')->find_all();
		$types = ORM::Factory('item_type')->where('status','=', 1)->order_by('order','asc')->find_all();
		$topics = ORM::Factory('item_topic')->where('status','=', 1)->order_by('order','asc')->find_all();
		$categories = ORM::Factory('item_category')->where('status','=', 1)->order_by('order','asc')->find_all();
		
        $this->template->content = $view
                        ->bind('title', $title)
						->bind('item', $item)
						->bind('item2', $item2)
						->bind('sort', $sort)
						->bind('user', $user)
						->bind('user_id', $user_id)
						->bind('children', $children)
						->bind('techniques', $techniques)
						->bind('types', $types)
						->bind('item_type_link', $item_type_link)
						->bind('item_topic_link', $item_topic_link)
						->bind('topics', $topics)
						->bind('categories', $categories)
						->bind('images', $images)
                        ->bind('errors', $errors)
						->bind('message_ok', $message_ok)
                        ->bind('message', $message);
    }
	
   public function action_artist() {
		
		$action = Request::current()->param('act');
		$id = Request::current()->param('id');
		
        $this->template->title = $title = 'Twoi artyści';
		
		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
	
		$user_id = Auth::instance()->get_user()->id;
		$user = ORM::Factory('User', $user_id);
		$images = array();
		
		if( empty( $action ) ) {
			$view = View::Factory('account/artist');	
			$artist = ORM::Factory('moderator_user')->where('parent','=', $user_id)->find_all();
		} else {
			$view = View::Factory('account/artist_edit');
			if( !empty( $id) ) {
				$artist = ORM::Factory('moderator_user', $id);
				
			} else {
					$artist = ORM::Factory('moderator_user');
			}
			
			if ($_POST) {
			
				$data = ac_form::clear_form_data($_POST);
				
				$time = time();
				//$artist->username = $time;
				$artist->password = $time;
				$artist->email = "$time@".$_SERVER['HTTP_HOST'];
				$artist->newsletter = 0;
				$artist->newsletter2 = 0;
				
					foreach( $data as $key => $val) {
						if($key != 'action' ) {
							$artist->{$key} = @$val;
						}
					}
					
					if( $_FILES ) {
						$uploads_dir = 'uploads/user/images/';
					
						$name = $_FILES['logo']['name'];
						$tmp_name = $_FILES['logo']['tmp_name'];
						if( move_uploaded_file($tmp_name, "$uploads_dir/$name") AND !empty( $name )) {
							$artist->logo = $name;
						}
					
					}
				$artist->zone_id = $data['zone_id'];
				$artist->parent = $user_id;
				$artist->profile_id = 1;
				$artist->added = $time;
				$artist->is_change = 1;
				$artist->save();
				
				cms::confirmAdmin(Request::current()->controller(), Request::current()->action());
				Message::success(__t('Zmiany zostały zapisane i oczekują na akceptację moderatora!'));
				$this->redirect('account/artist');
			
			}
		}
		
		
		if( $action == "delete" AND !is_null( $id ) ) {
			
			ORM::Factory('user')->where('id','=', $id)->where('parent','=',$user_id)->find()->delete();
			ORM::Factory('moderator_user')->where('id','=', $id)->where('parent','=',$user_id)->find()->delete();
			
			Message::success('Akcja wykonana pomyślnie.');
			$this->redirect('account/artist');
		}
		
        $this->template->content = $view
                        ->bind('title', $title)
						->bind('artist', $artist)
						->bind('user', $user)
                        ->bind('errors', $errors)
						->bind('message_ok', $message_ok)
                        ->bind('message', $message);
    }	
	
  public function action_comment() {
		
		$action = Request::current()->param('act');
		$id = Request::current()->param('id');
		
        $this->template->title = $title = 'Twoje komentarze';
		
		if( !Auth::instance()->logged_in() ) $this->redirect('Login');
	
		$user_id = Auth::instance()->get_user()->id;
		$user = ORM::Factory('User', $user_id);
		
		$images = array();
		
		if( empty( $action ) ) {
			$view = View::Factory('account/comment');	
			$comment = ORM::Factory('moderator_page_comment')->where('user_id','=', $user_id)->find_all();
		} else {
			$view = View::Factory('account/comment_edit');
			if( !empty( $id) ) {
				$comment = ORM::Factory('moderator_page_comment', $id);
				
			} else {
					$comment = ORM::Factory('moderator_page_comment');
			}
			
			if ($_POST) {
			
				$data = ac_form::clear_form_data($_POST);
		
					foreach( $data as $key => $val) {
						if($key != 'action' ) {
							$comment->{$key} = @$val;
						}
					}
				
				$comment->save();
				
				cms::confirmAdmin(Request::current()->controller(), Request::current()->action());
				Message::success(__t('Zmiany zostały zapisane i oczekują na akceptację moderatora!'));
				$this->redirect('account/comment');
			
			}
		}
		
		
		if( $action == "delete" AND !is_null( $id ) ) {
			
			$test = ORM::Factory('page_comment')->where('id','=', $id)->where('user_id','=',$user_id)->find();
			if( $test->loaded() ) $test->delete();
			ORM::Factory('moderator_page_comment')->where('id','=', $id)->where('user_id','=',$user_id)->find()->delete();
			
			Message::success('Akcja wykonana pomyślnie.');
			$this->redirect('account/comment');
		}
		
        $this->template->content = $view
                        ->bind('title', $title)
						->bind('comment', $comment)
						->bind('user', $user)
                        ->bind('errors', $errors)
						->bind('message_ok', $message_ok)
                        ->bind('message', $message);
    }		
	

	public function action_message( $id = null, $action = null) {

        $this->template->title = $title = 'Moje wiadomości';

		if( !Auth::instance()->logged_in() )  $this->redirect('Login');
	
		$user_id = Auth::instance()->get_user()->id;
		$user = ORM::Factory('User', $user_id );
		
		if( $action == "delete" AND $id != null ) {
	
			ORM::Factory('user_message')->where('talk_id', '=', $id)->where('has','=',$user_id)->delete_all();
			Message::SUCCESS('Akcja wykonana prawidłowo.');
			$this->redirect('account/message');
		}

		if ($_POST) {
            $data = ac_form::clear_form_data($_POST);
            $validata = $this->valid_send_form($data);
            if (sizeof($validata['errors'])) {
                $message = __t('Błędnie wypełniony formularz. Sprawdź poprawność wszystkich pól.');
                $errors = $validata['errors'];
            } else {	
			
			$id_u = ORM::Factory('User')->where('email','=', $data['user_list'])->find();
			if( !empty( $data['register_title'] ) ) {
				
				$talk_id_fix = ORM::Factory('user_message')->find_all()->count()+1;
				
				$create = ORM::Factory('user_message');
				$create->subject= $data['register_title'];
				$create->description = $data['register_description'];
				$create->date = time();
				$create->marked = 0;
				$create->direct = 'I';
				$create->has = $id_u; // recipient
				$create->parent = 1;
				$create->user_id = $user_id;
				$create->talk_id = $talk_id_fix;
				$create->save();
				
				$create = ORM::Factory('user_message');
				$create->subject= $data['register_title'];
				$create->description = $data['register_description'];
				$create->date = time();
				$create->marked = 1;
				$create->direct = 'O';
				$create->has = $user_id;
				$create->parent = 1;
				$create->user_id = $id_u;
				$create->talk_id = $talk_id_fix;
				$create->save();
				
				$message_ok = __t('Wiadomość została wysłana!');
			}
			
		}
	}

		if( $id != ".*" ) { 
			$view = View::factory('account/message_item');
			$messages = ORM::Factory('user_message')->where('has','=', $user_id)->where('talk_id','=', $id)->order_by('date','desc')->find_all();
	
			$m = ORM::Factory('user_message', $id);
			$m->marked = 1;
			$m->save();

		}
		else {
		
			$messages = array();
			$view = View::factory('account/message');
			$i = 0;
			if( empty( $_GET['filtr'] ) OR $_GET['filtr'] == 1 )  {
			//	$query = DB::select('talk_id')->distinct(TRUE)->from('user_messages')->where('direct','=', 'I')->where('has','=', $user_id)->order_by('date','desc');
			//	$talks = $query->execute();
			//	foreach( $talks as $t ) {
				//	foreach( ORM::Factory('user_message')->where('direct','=', 'I')->where('talk_id','=', $t['talk_id'])->order_by('date','desc')->limit(2)->find_all() as $message_item  ) {
					foreach( ORM::Factory('user_message')->where('direct','=', 'I')->where('has','=', $user_id)->order_by('date','desc')->limit(2)->find_all() as $message_item  ) {
					$messages[$i]['id'] = $message_item->id;
					$messages[$i]['subject'] = $message_item->subject;
					$messages[$i]['description'] = $message_item->description;
					$messages[$i]['date'] = $message_item->date;
					$messages[$i]['marked'] = $message_item->marked;
					$messages[$i]['has'] = $message_item->has;
					$messages[$i]['parent'] = $message_item->parent;
					$messages[$i]['direct'] = $message_item->direct;
					$messages[$i]['talk_id'] = $message_item->talk_id;
					$messages[$i++]['user_id'] = $message_item->user_id;
					}
			//	}
			//	}
			} elseif( !empty( $_GET['filtr'] ) AND $_GET['filtr'] == 2 )  {
			
				foreach( ORM::Factory('user_message')->where('direct','=', 'O')->where('has','=', $user_id)->order_by('date','desc')->find_all() as $message_item  ) {
					$messages[$i]['id'] = $message_item->id;
					$messages[$i]['subject'] = $message_item->subject;
					$messages[$i]['description'] = $message_item->description;
					$messages[$i]['date'] = $message_item->date;
					$messages[$i]['marked'] = $message_item->marked;
					$messages[$i]['has'] = $message_item->has;
					$messages[$i]['parent'] = $message_item->parent;
					$messages[$i]['direct'] = $message_item->direct;
					$messages[$i]['talk_id'] = $message_item->talk_id;
					$messages[$i++]['user_id'] = $message_item->user_id;
				}
				
			} elseif( !empty( $_GET['filtr'] ) AND $_GET['filtr'] == 3 )  {
			
				foreach( ORM::Factory('user_message')->where('user_id','=', $user_id)->or_where('has','=', $user_id)->order_by('date','desc')->find_all() as $message_item  ) {
					$messages[$i]['id'] = $message_item->id;
					$messages[$i]['subject'] = $message_item->subject;
					$messages[$i]['description'] = $message_item->description;
					$messages[$i]['date'] = $message_item->date;
					$messages[$i]['marked'] = $message_item->marked;
					$messages[$i]['has'] = $message_item->has;
					$messages[$i]['parent'] = $message_item->parent;
					$messages[$i]['direct'] = $message_item->direct;
					$messages[$i]['talk_id'] = $message_item->talk_id;
					$messages[$i++]['user_id'] = $message_item->user_id;
				}
					
			}
			
		}


        $this->template->content = $view
                        ->bind('title', $title)
						->bind('user', $user)
						->bind('messages', $messages)
                        ->bind('errors', $errors)
						->bind('id', $id)
						->bind('message_ok', $message_ok)
                        ->bind('message', $message);
    }	

	
	
	public function action_message_item( $talk_id = null, $id = null) {

        $this->template->title = $title = 'Moje wiadomości';

		if( !Auth::instance()->logged_in() )  $this->redirect('Login');
	
		$user_id = Auth::instance()->get_user()->id;
		$user = ORM::Factory('User', $user_id );
		
		if( $talk_id != null AND $id != null ) {
		
			ORM::Factory('user_message', $id)->where('user_id', '=', $user_id)->delete();
			Message::SUCCESS('Akcja wykonana prawidłowo.');
			$this->redirect('account/message/'.$talk_id);
		}

		if ($_POST) {
            $data = ac_form::clear_form_data($_POST);
            $validata = $this->valid_send_form($data);
            if (sizeof($validata['errors'])) {
                $message = __t('Błędnie wypełniony formularz. Sprawdź poprawność wszystkich pól.');
                $errors = $validata['errors'];
            } else {	
				$create = ORM::Factory('user_message');
				$create->description = $data['message_text'];
				$create->date = time();
				$create->marked = 0;
				$create->direct = 'I';
				$create->has = $data['message_recipient'];
				$create->parent = 1;
				$create->user_id = $user_id;
				$create->talk_id = $talk_id;
				$create->save();
				
				$create = ORM::Factory('user_message');
				$create->description = $data['message_text'];
				$create->date = time();
				$create->marked = 1;
				$create->direct = 'O';
				$create->has = $user_id;
				$create->parent = 1;
				$create->user_id = $data['message_recipient'];
				$create->talk_id = $talk_id;
				$create->save();
				aurora::addPoints($user_id, 'message');
				$message_ok = __t('Wiadomość została wysłana!');
			}
			
		}

		
		$view = View::factory('account/message_item');
		$messages = ORM::Factory('user_message')->where('has','=', $user_id)->where('talk_id','=', $talk_id)->order_by('date','desc')->find_all();
	
		//$messages = ORM::Factory('user_message')->where('talk_id','=', $talk_id)->order_by('date','desc')->find_all();
		foreach( $messages as $mm ) {
			$m = ORM::Factory('user_message', $mm->id);
			$m->marked = 1;
			$m->save();
		}


        $this->template->content = $view
                        ->bind('title', $title)
						->bind('user', $user)
						->bind('messages', $messages)
                        ->bind('errors', $errors)
						->bind('id', $talk_id)
						->bind('message_ok', $message_ok)
                        ->bind('message', $message);
    }
	
 	
   public function action_blog_comment_add( $id_user = null, $id_blog = null) {

		$this->template = View::factory('mini');
		
        //$this->template->title = $title = 'Dodaj komentarz';

		if ($_POST) {
            $data = ac_form::clear_form_data($_POST);
            $validata = $this->valid_add_comment_form($data);
            if (sizeof($validata['errors'])) {
                $message = __t('Błędnie wypełniony formularz. Sprawdź poprawność wszystkich pól.');
                $errors = $validata['errors'];
				
            } else {
				$create = ORM::Factory('blog_comment');
				$create->description = $data['register_description'];
				$create->date = time();
				$create->user_id = $id_user;
				$create->blog_id = $id_blog;
				$create->save();
				aurora::addPoints($id_user, 'blog_comment');
				$message_ok = __t('Komentarz dodany ! Niebawem pojawi się na liście komentarzy.');
			}
		}

		$view = View::factory('profile/blog_comment_add');

        $this->template->content = $view
						->bind('id_user', $id_user)
						->bind('id_blog', $id_blog)
                        ->bind('errors', $errors)
						->bind('message_ok', $message_ok)
                        ->bind('message', $message);
    }
	
	private function valid_account_edit_form($data) {
        //var_dump($data);
        $prefix = 'register';
        $errors = array();

		$name = ac_form::get_name('gender', $prefix);
        if (!isset($data[$name]) ) {
            $errors[$name] = __t('Pole nie może być puste');
        }
		
		$name = ac_form::get_name('firstname', $prefix);
        if (empty($data[$name])) {
            $errors[$name] = __t('Pole nie może być puste');
        }
		
		$name = ac_form::get_name('email', $prefix);
        if (empty($data[$name])) {
            $errors[$name] = __t('Pole nie może być puste');
        }
		
		$name = ac_form::get_name('password', $prefix);
		$name2 = ac_form::get_name('password2', $prefix);
        if (!empty($data[$name])) {
			if (!empty($data[$name2]) ) {
			 
				if( $data[$name] != $data[$name2] ) {
					$errors[$name] = __t('Pola się różnią');
				}
			} else {
				$errors[$name2] = __t('Pole nie może być puste');
			}
        }
		
		
		$name = ac_form::get_name('subdomain', $prefix);
		if (!empty($data[$name])) {
			
					$test_subdomain = ORM::Factory('User')->where('id','!=', Auth::instance()->get_user()->id)->where('subdomain','=', $data[$name])->find();
					if( $test_subdomain->loaded()) {
						$errors[$name] = __t('Subdomana już istnieje!');
					}
		}
        return array(
            'data' => $data,
            'errors' => $errors
        );
    }
  
    private function valid_edit_form($data) {
        //var_dump($data);
        $prefix = 'register';
        $errors = array();

		
		$name = ac_form::get_name('firstname', $prefix);
        if (empty($data[$name])) {
            $errors[$name] = __t('Pole nie może być puste');
        }

        return array(
            'data' => $data,
            'errors' => $errors
        );
    }	
	
	private function valid_notice_edit_form($data) {
        //var_dump($data);
        $prefix = 'register';
        $errors = array();
		
		
		$name = ac_form::get_name('firstname', $prefix);
        if (empty($data[$name.'_'.$_GET['layout']])) {
            $errors[$name] = __t('Pole nie może być puste');
        }
		
		$name = ac_form::get_name('email', $prefix);
        if (!empty($data[$name.'_'.$_GET['layout']])) {
			if( !Validate::email( $data[$name.'_'.$_GET['layout']] ) ) {
				$errors[$name] = __t('Proszę wpisać poprawny adres e-mail');
			} else {
			/*
				$test = ORM::Factory('User')->where('email','=', $data[$name.'_'.$_GET['layout']] )->find();
				if( $test->loaded() AND is_null($data['id']) ) {
					$errors[$name] = __t('Wybrany e-mail jest już zajęty');
				}
			*/
			}
        }
		
		$name = ac_form::get_name('phone', $prefix);
        if (!empty($data[$name.'_'.$_GET['layout']])) {
			if( !Validate::phone( $data[$name.'_'.$_GET['layout']] ) ) {
				$errors[$name] = __t('Proszę wpisać poprawnie numer telefonu');
			}
        }
		
		$name = ac_form::get_name('www', $prefix);
        if (!empty($data[$name.'_'.$_GET['layout']])) {
			if( !strpos($data[$name.'_'.$_GET['layout']], ".") ) {
				$errors[$name] = __t('Proszę wpisać poprawnie adres www');
			}
        }
		
		$allowed = array('png','gif','jpg','jpeg','pdf','doc','docx','odt');
		
		for( $i=1;$i<=6;$i++ ) {
			
			if( !empty( $_FILES['attach_'.$i.'_'.$_GET['layout']]['name'] ) ) {
				$ext = pathinfo($_FILES['attach_'.$i.'_'.$_GET['layout']]['name'], PATHINFO_EXTENSION);

				//$ext = $path_info['extension']; // "bill"
			
				if( !in_array( strtolower($ext), $allowed ) ) {
					$errors['file'] = __t('Złe rozszerzenie pliku załącznika!');
					break;
				}
			}
		}
//var_dump($errors);
        return array(
            'data' => $data,
            'errors' => $errors
        );
    }	
	
	private function valid_send_form($data) {
        //var_dump($data);
        $prefix = 'register';
        $errors = array();

		
	

        return array(
            'data' => $data,
            'errors' => $errors
        );
    }	
	

}