Current File : /home/users/barii/public_html/finansenl.com.pl/wodki/application/classes/Model/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->template->title = $title = 'Moje dane';

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

		$profile = $user->profile_id;
		if( $profile == 4 OR $profile == 5 ) $profile = 2;
		$profile = 1;
		
		$view = View::factory('account/index_'.$profile);
		$images = ORM::Factory('user_image')->where('user_id','=', $user->id)->find_all();
		

		
        $this->template->content = $view
						->bind('title', $title)
						->bind('user', $user)
						->bind('images', $images)
                        ->bind('errors', $errors)
						->bind('message_ok', $message_ok)
                        ->bind('message', $message);
    }
	
	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');	
	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');	
	exit;
		
	}		
	
	/*
   public function action_edit() {

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

		if( !Auth::instance()->logged_in() ) Request::instance()->redirect('logowanie');
		
				
		$user = ORM::Factory('user', Auth::instance()->get_user()->id );
		
		$view = View::factory('account/notice_edit_'.$user->profile_id);
		
		if ($_POST) {
            $data = ac_form::clear_form_data($_POST);
		
				switch( $user->profile_id ) {
					case 1:
					$validata = $this->valid_edit_form($data);
					break;
					case 2:
					$validata = $this->valid_edit_2_form($data);
					break;
					case 3:
					$validata = $this->valid_edit_3_form($data);
					break;
				}
			
            if (sizeof($validata['errors'])) {
                $message = __t('Błędnie wypełniony formularz. Sprawdź poprawność wszystkich pól.');
                $errors = $validata['errors'];
            } else {
			
						
						$user->firstname = $data['register_firstname'];
						$user->email = $data['register_email'];
						$user->www = $data['register_www'];
						$user->phone = $data['register_phone'];
	
						$user->zone_id = !empty($data['register_zone_id']) ? $data['register_zone_id'] : '';
						$user->city_id = !empty($data['register_city_id']) ? $data['register_city_id'] : '';
						$user->discipline = !empty($data['register_discipline']) ? $data['register_discipline'] : '';
						$user->description = !empty($data['register_description']) ? $data['register_description'] : '';
						
						for( $i=1; $i<=7; $i++ ) {
							if( !empty($data['register_working_hours_'.$i]) AND !empty($data['register_working_hours_'.$i.'_']) ){
								$attr = "working_hours_$i";
								$user->$attr = $data['register_working_hours_'.$i.'_']." - ".$data['register_working_hours_'.$i];
							}
						}
						
						$logo = '';
							if( $_FILES) {
									$uploads_dir = 'uploads/user/images/';
									$tmp_name = $_FILES["photo"]["tmp_name"][$i];
									$name = $_FILES["photo"]["name"][$i];
									if( move_uploaded_file($tmp_name, "$uploads_dir/$name") ) {
										$logo = $name;
									}
							}
				
				$user->save();
				Message::success(__t('Zmiany zostały zapisane.'));
				Request::instance()->redirect('account');
			}
			
		}

        $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() {

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

		if( !Auth::instance()->logged_in() ) Request::instance()->redirect('logowanie');
		
				
		$user = ORM::Factory('user', Auth::instance()->get_user()->id );
		
		$view = View::factory('account/edit');
		
		if ($_POST) {
            $data = ac_form::clear_form_data($_POST);
		
			$validata = $this->valid_account_edit_form($data);
		
            if (sizeof($validata['errors'])) {
                $message = __t('Błędnie wypełniony formularz. Sprawdź poprawność wszystkich pól.');
                $errors = $validata['errors'];
            } else {
						$user->gender = $data['register_gender'];
						
						$user->firstname = $data['register_firstname'];
						//$user->lastname = $data['register_firstname'];
						$user->email = $data['register_email'];
						$user->username = $data['register_username'];
						if( !empty( $data['register_password'] ) AND !empty( $data['register_password2'] ) ) 
						$user->password = $data['register_password'];
						
						$user->subdomain = cms::_no_pl($data['register_subdomain']);
						
				
	
				$user->save();
				Message::success(__t('Zmiany zostały zapisane.'));
				Request::instance()->redirect('account');
			}
			
		}

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

	public function action_notice_add( $action = '', $id = null) {

        $this->template->title = $title = 'Ogłoszenia';
		//if( !Auth::instance()->logged_in() ) Request::instance()->redirect('logowanie');
	
		$view = View::Factory('account/notice_add');
        $this->template->content = $view;
    }
	
    public function action_notice( $action = '', $id = null) {

        $this->template->title = $title = 'Twoje Ogłoszenia';

		if( !Auth::instance()->logged_in() ) Request::instance()->redirect('logowanie');
	
		$user_id = Auth::instance()->get_user()->id;
		$user = ORM::Factory('user', $user_id );
		
		if( $action == "delete" AND !is_null( $id ) ) {
			
			ORM::Factory('user')->where('id','=', $id)->where('parent','=',$user_id)->delete_all();
			ORM::Factory('user_discipline')->where('user_id','=',$id)->delete_all();
			
			Message::success('Akcja wykonana pomyślnie.');
			Request::instance()->redirect('account/notice');
		}
		
		$notices = ORM::Factory('user')->where('parent','=', $user_id)->where('status','=', 1)->find_all();
		$view = View::Factory('account/notice');
        $this->template->content = $view
                        ->bind('title', $title)
						->bind('notices', $notices)
                        ->bind('errors', $errors)
						->bind('user', $user)
						->bind('message_ok', $message_ok)
                        ->bind('message', $message);
    }
	
	private function add_user_profile( $data, $id = null, $profile_id ) {
	
	$layout = addslashes($_GET['layout']);
	
		if( is_null($id) ) {
				$user = ORM::Factory('user');
				$user->username = time().rand(1,1000);
				} else {
					if( Auth::instance()->logged_in('admin') )
						$user = ORM::Factory('user', $id );
					else 
						$user = ORM::Factory('user')->where('id','=',$id)->where('parent','=', Auth::instance()->get_user()->id)->find();
						if( !$user->loaded() ) {
						Request::instance()->redirect('account');
						exit;
						}
				}
			
				if( !empty( $data['register_firstname_'.$profile_id] ) ) {
				
				$user->firstname = $data['register_firstname_'.$profile_id];
				$user->description = nl2br($data['register_description_'.$profile_id]);
				$user->age = !empty($data['register_age_'.$profile_id]) ? $data['register_age_'.$profile_id] : '';
				$user->phone = $data['register_phone_'.$profile_id];
				$user->email = $data['register_email_'.$profile_id];
				$user->www = !empty($data['register_www_'.$profile_id]) ? (strpos($data['register_www_'.$profile_id],'http://' )=== false) ? 'http://'.$data['register_www_'.$profile_id] : $data['register_www_'.$profile_id]  : '';
				$user->zone_id = $data['register_zone_id_'.$profile_id];
				$user->city_id = $data['register_city_id_'.$profile_id];
				$user->postcode = !empty($data['register_postcode_'.$profile_id]) ? $data['register_postcode_'.$profile_id] : '';
				$user->street = !empty($data['register_street_'.$profile_id]) ? $data['register_street_'.$profile_id] : '';
			//	$user->profile_id = $data['register_profile_id'];
				$user->profile_id = $profile_id;
				
			
				
				if( !Auth::instance()->logged_in('admin') )
				$user->parent = !empty(Auth::instance()->get_user()->id) ? Auth::instance()->get_user()->id : 0;
				
				/* Kurs i szkolenie */
				$user->date_cours_start = !empty($data['register_date_cours_start_d']) ? $data['register_date_cours_start_y'].'-'.$data['register_date_cours_start_m'].'-'.$data['register_date_cours_start_d'] : '' ;
				$user->date_cours_end = !empty($data['register_date_cours_end_d']) ? $data['register_date_cours_end_y'].'-'.$data['register_date_cours_end_m'].'-'.$data['register_date_cours_end_d'] : '' ;
				$user->price_cours_from = !empty($data['register_price_cours_from']) ? $data['register_price_cours_from'] : '';
				$user->price_cours_to = !empty($data['register_price_cours_to']) ? $data['register_price_cours_to'] : '';
				
				for( $i=1; $i<=7; $i++ ) {
					if( !empty($data['register_working_hours_'.$i.'_']) AND !empty($data['register_working_hours_'.$i]) ){
						$attr = "working_hours_$i";
						$user->$attr = $data['register_working_hours_'.$i.'_']." - ".$data['register_working_hours_'.$i];
					}
				}
						
				if( is_null($id) ) {
				$user->added = time();
				}
				
				if( is_null($id) ) {
					if( $profile_id == 7 ) {
					$user->status = 0;
					} else {
					$user->status = 1;
					}
				}
				$user->save();
				
				$image_type = array('png','gif','jpg','jpeg');
				
				$attach = "";
				
				
			
				$clear_photos = DB::Query(Database::DELETE, "DELETE FROM user_images WHERE user_id = '$user->id'")->execute();
					
                    $uploads_dir = 'uploads/user/images/';
					for($i=1; $i<=3; $i++ ) {
					
					if( !empty( $data['upload_attach_'.$i] )) {
					/*
						if( $profile_id == 2 OR $profile_id == 4 OR $profile_id == 5 OR $profile_id == 7 ) {
						$tmp_name = $_FILES["attach_".$i.'_'.$profile_id]["tmp_name"];
						$name = $_FILES["attach_".$i.'_'.$profile_id]["name"];
						} else {
						$tmp_name = $_FILES["attach_".$i]["tmp_name"];
						$name = $_FILES["attach_".$i]["name"];
						}
					*/	
					
						$name = @$data['upload_attach_'.$i];
						
						if(  !empty( $name ) ) {
						$test_photo = DB::Query(Database::SELECT, "SELECT id FROM user_images WHERE user_id = '$user->id'")->execute();
					
							$f = ORM::Factory('user_image');
							$f->name = $name;
							//if( count($test_photo) == 0 ) $f->highlight = 1;
							if( $i == 1 ) $f->highlight = 1;
							$f->user_id = $user->id;
							$f->text = in_array( pathinfo(strtolower($name), PATHINFO_EXTENSION) , $image_type ) ? 'image' : 'certificate';
							$f->save();
						}
						
					}
					}
					
					for($i=4; $i<=6; $i++ ) {
					
					if( !empty( $data['upload_attach_'.$i] )) {
						$name = @$data['upload_attach_'.$i];
						
						if(  !empty( $name ) ) {
							$f = ORM::Factory('user_image');
							$f->name = $name;
							$f->user_id = $user->id;
							if( $profile_id == 2 )
							$f->text = in_array( pathinfo(strtolower($name), PATHINFO_EXTENSION) , $image_type ) ? 'image' : 'certificate';
							else
							$f->text = 'image';
							
							$f->save();
						}
					}
					
					}
				
				
				/*
				if( $_FILES) {
			
				
                    $uploads_dir = 'uploads/user/images/';
					for($i=1; $i<=3; $i++ ) {
						if( $profile_id == 2 OR $profile_id == 4 OR $profile_id == 5 OR $profile_id == 7 ) {
						$tmp_name = $_FILES["attach_".$i.'_'.$profile_id]["tmp_name"];
						$name = $_FILES["attach_".$i.'_'.$profile_id]["name"];
						} else {
						$tmp_name = $_FILES["attach_".$i]["tmp_name"];
						$name = $_FILES["attach_".$i]["name"];
						}
						
						
						if( move_uploaded_file($tmp_name, "$uploads_dir/$name") OR !empty( $name ) ) {
						$test_photo = DB::Query(Database::SELECT, "SELECT id FROM user_images WHERE user_id = '$user->id'")->execute();
						
							$f = ORM::Factory('user_image');
							$f->name = $name;
							if( count($test_photo) == 0 ) $f->highlight = 1;
							$f->user_id = $user->id;
							$f->text = in_array( pathinfo(strtolower($name), PATHINFO_EXTENSION) , $image_type ) ? 'image' : 'certificate';
							$f->save();
						}
					}
					
					for($i=4; $i<=6; $i++ ) {
					
						if( $profile_id == 2 OR $profile_id == 4 OR $profile_id == 5 OR $profile_id == 7 ) {
						$tmp_name = $_FILES["attach_".$i.'_'.$profile_id]["tmp_name"];
						$name = $_FILES["attach_".$i.'_'.$profile_id]["name"];
						} else {
						$tmp_name = $_FILES["attach_".$i]["tmp_name"];
						$name = $_FILES["attach_".$i]["name"];
						}
						if( move_uploaded_file($tmp_name, "$uploads_dir/$name") OR !empty( $name ) ) {
							$f = ORM::Factory('user_image');
							$f->name = $name;
							$f->user_id = $user->id;
							if( $profile_id == 2 )
							$f->text = in_array( pathinfo(strtolower($name), PATHINFO_EXTENSION) , $image_type ) ? 'image' : 'certificate';
							else
							$f->text = 'image';
							
							$f->save();
						}
					}
				
				}
				*/
				
				
				DB::Query(Database::DELETE, "DELETE FROM `user_disciplines` WHERE `user_id` = '$user->id'")->execute();
				DB::Query(Database::DELETE, "DELETE FROM `user_clubs` WHERE `user_id` = '$user->id'")->execute();
				
				if( $profile_id == 7 OR $profile_id == 6 OR $profile_id == 3 ) {  // Kurs i szkolenia lub wyjazd
					
							for( $i=1; $i<20; $i++ ) {
								if( !empty($data['register_discipline_'.$i]) ){
									$d = ORM::Factory('discipline')->where('title','=',$data['register_discipline_'.$i])->find();
									
									$n = ORM::Factory('user_discipline');
									$n->name = $data['register_discipline_'.$i];
									$n->user_id = $user->id;
									$n->disciplines_id = ($d->loaded()) ? $d->id : 0;
									$n->save();
								}
							}
						}
						
				
					if( !empty( $data['register_profile_id_2'] ) ) {	// Trener
							for( $i=1; $i<20; $i++ ) {
						
								if( !empty($data['register_discipline_'.$i]) AND !empty($data['register_price0_'.$i]) ){
									
									if( !empty(  $data['register_club0_'.$i] ) ) {
										$club_id = $data['register_club0_'.$i];
									} else {
										$club_id = 0;
									}
									
									if( $club_id == "another" ) {
										
										if( !empty( $data['register_club0another_'.$i] ) AND !empty( $data['register_club0another_city_'.$i] ) ) {
										
											$city_q = ORM::Factory('city')->where('title','LIKE', $data['register_club0another_city_'.$i].'%')->find();
											if( !$city_q->loaded() ) {
												$city_q = ORM::Factory('city');
												$city_q->title = $data['register_club0another_city_'.$i];
												$city_q->save();
											}
											sleep(1);
											
											$user_new = ORM::Factory('user')->where('firstname','=', $data['register_club0another_'.$i])->find();
											if( !$user_new->loaded() ) 
												$user_new = ORM::Factory('user');
											
											$user_new->username = time();
											$user_new->firstname = $data['register_club0another_'.$i];
											$user_new->city_id = $city_q->id;
											$user_new->profile_id = 7;
											$user_new->status = 0;
											$user_new->save();
											
											$club_id = $data['register_club0another_'.$i];
											$club_id = $user_new->id;
										}
									} 
								
									$d = ORM::Factory('discipline')->where('title','=',$data['register_discipline_'.$i])->find();
									$n = ORM::Factory('user_discipline');
									$n->name = $data['register_discipline_'.$i];
									$n->price = $data['register_price0_'.$i];
									$n->user_id = $user->id;
									$n->disciplines_id = $d->id;
									$n->club_id = $club_id;
									$n->save();
								}
								
								
								/*
								if( !empty($data['register_club0_'.$i]) AND !empty($data['register_club0_price_'.$i]) ){
								
									$n = ORM::Factory('user_club');
									$n->name = $data['register_club0_'.$i];
									$n->price = $data['register_club0_price_'.$i];
									$n->user_id = $user->id;
									$n->save();
								}
								*/
							}
						}
						
						if( !empty( $data['register_profile_id_4'] ) ) {  // Dietetyk
							for( $i=1; $i<20; $i++ ) {
							
								if( !empty($data['register_club_'.$i]) AND !empty($data['register_club_price_'.$i]) ){
									
									$club_id = $data['register_club_'.$i];
									
									if( $club_id == "another" ) {
										
										if( !empty( $data['register_club1another_'.$i] ) AND !empty( $data['register_club1another_city_'.$i] ) ) {
										
											$city_q = ORM::Factory('city')->where('title','LIKE', $data['register_club1another_city_'.$i].'%')->find();
											if( !$city_q->loaded() ) {
												$city_q = ORM::Factory('city');
												$city_q->title = $data['register_club1another_city_'.$i];
												$city_q->save();
											}
											sleep(1);
											
											$user_new = ORM::Factory('user')->where('firstname','=', $data['register_club1another_'.$i])->find();
											if( !$user_new->loaded() ) 
												$user_new = ORM::Factory('user');
												
											$user_new->username = time();
											$user_new->firstname = $data['register_club1another_'.$i];
											$user_new->city_id = $city_q->id;
											$user_new->profile_id = 7;
											$user_new->save();
											
											$club_id = $data['register_club1another_'.$i];
										}
									} 
								
									$n = ORM::Factory('user_discipline');
									$n->price = $data['register_club_price_'.$i];
									$n->user_id = $user->id;
									$n->club_id = $club_id;
									$n->save();
									
									
									$n = ORM::Factory('user_club');
									$n->name = $data['register_club_'.$i];
									$n->price = $data['register_club_price_'.$i];
									$n->user_id = $user->id;
									$n->save();
								}
							}
						}
						
						if( !empty( $data['register_profile_id_5']  )) {   // fizjoterapeuta
							for( $i=1; $i<20; $i++ ) {
								if( !empty($data['register_club2_'.$i]) AND !empty($data['register_club2_price_'.$i]) ){
									
									
									$club_id = $data['register_club2_'.$i];
									
									if( $club_id == "another" ) {
										
										if( !empty( $data['register_club2another_'.$i] ) AND !empty( $data['register_club2another_city_'.$i] ) ) {
										
											$city_q = ORM::Factory('city')->where('title','LIKE', $data['register_club2another_city_'.$i].'%')->find();
											if( !$city_q->loaded() ) {
												$city_q = ORM::Factory('city');
												$city_q->title = $data['register_club2another_city_'.$i];
												$city_q->save();
											}
											sleep(1);
											
											$user_new = ORM::Factory('user')->where('firstname','=', $data['register_club2another_'.$i])->find();
											if( !$user_new->loaded() ) 
												$user_new = ORM::Factory('user');
												
											$user_new->username = time();
											$user_new->firstname = $data['register_club2another_'.$i];
											$user_new->city_id = $city_q->id;
											$user_new->profile_id = 7;
											$user_new->save();
											
											$club_id = $data['register_club2another_'.$i];
										}
									} 
								
								
									$n = ORM::Factory('user_discipline');
									$n->price = $data['register_club2_price_'.$i];
									$n->user_id = $user->id;
									$n->club_id = $club_id;
									$n->save();
									
									$n = ORM::Factory('user_club');
									$n->name = $data['register_club2_'.$i];
									$n->price = $data['register_club2_price_'.$i];
									$n->user_id = $user->id;
									$n->save();
								}
							}
						}
					
					$e_content = View::factory('email/email_confirmation_profile')
												->bind('user', $user);
											
					aurora::standardEmail(Kohana::config('site.email_confirmation_profile_'.$user->profile_id), __t('Edycja profilu na '.$_SERVER['HTTP_HOST']),  $e_content);
						
						
				return $user;
				} else return 0;
	}
	
    public function action_notice_edit( $a = null, $b = null, $c = null, $id = null) {
	
		$data = array();
		$user_discipline = array();
		$user_club = array();
		
        $this->template->title = $title = 'Ogłoszenia';
	
		$layout = addslashes($_GET['layout']);
		$layout_get = $layout;
		if( $layout == 4 OR $layout == 5 ) $layout = 2;
		
		if( Auth::instance()->logged_in() OR $layout == 7 ) $view = View::factory('account/notice_edit_'.$layout);
		else Request::instance()->redirect('logowanie');

		if( !is_null($id) ) {
			
			if( Auth::instance()->logged_in('admin') )
						$user = ORM::Factory('user', $id );
					else 
						$user = ORM::Factory('user')->where('id','=',$id)->where('parent','=', Auth::instance()->get_user()->id)->find();
						if( !$user->loaded() ) {
						Request::instance()->redirect('account');
						exit;
						}
						
			$user_discipline = ORM::Factory('user_discipline')->where('user_id','=', $user->id )->find_all();
			$user_club = ORM::Factory('user_club')->where('user_id','=', $user->id )->find_all();
		}
		
		if ($_POST) {
			
            $data = ac_form::clear_form_data($_POST);
			$data['id'] = $id;
            $validata = $this->valid_notice_edit_form($data);
            if (sizeof($validata['errors'])) {
                $message = __t('Błędnie wypełniony formularz. Sprawdź poprawność wszystkich pól.');
                $errors = $validata['errors'];
            } else {
				
				if( empty( $data['register_firstname'] ) ) {
					$data['register_firstname'] = "Bez nazwy";
				}
				
				$user = $this->add_user_profile( $data, $id, $layout_get );	
			
				if( !empty( $data['register_profile_id_2'] ) AND $layout_get != 2 ) {	// Trener
				
					$this->add_user_profile( $data, null, 2 );	
				
				}
				
				if( !empty( $data['register_profile_id_4'] ) AND $layout_get != 4 ) {	// Dietyetyk
				
					$this->add_user_profile( $data, null, 4 );	
				}
				
				if( !empty( $data['register_profile_id_5'] ) AND $layout_get != 5 ) {	// Fizjo
				
					$this->add_user_profile( $data, null, 5 );	
				}
				
		
					
					if( Auth::instance()->logged_in('admin') ) {
					
						$profile_id = @addslashes(@$_GET['profile_id']);
						$date_start = @addslashes(@$_GET['date_start']);
						$date_end = @addslashes(@$_GET['date_end']);
						$keyword = @addslashes(@$_GET['keyword']);
						Request::instance()->redirect('admin/user?profile_id='.$profile_id.'&date_start='.$date_start.'&date_end='.$date_end.'&keyword='.$keyword);
					} else {
						if( $user->profile_id == 7 ) {
						Message::success('Dziękujemy za dodanie nowego obiektu sportowego.');
							if( !Auth::instance()->logged_in() ) {
							Request::instance()->redirect('account/notice/add');
							} else {
							Request::instance()->redirect('account/notice');
							}
						} else {
						Message::success('Profil został zmieniony.');
						Request::instance()->redirect('account/notice');
						}
					}
			}
			
		}

        $this->template->content = $view
                        ->bind('title', $title)
						->bind('data', $data)
                        ->bind('errors', $errors)
						->bind('user', $user)
						->bind('id', $id)
						->bind('user_discipline', $user_discipline)
						->bind('user_club', $user_club)
						->bind('message_ok', $message_ok)
                        ->bind('message', $message);
    }		
	
	public function action_notice_promo( $a = null, $b = null, $c = null, $id = null) {
	
		$data = array();
	
        $this->template->title = $title = 'Promuj Ogłoszenia';
		$notice_data = ORM::Factory('user', $id);
		
		if( Auth::instance()->logged_in() ) $view = View::factory('account/notice_promo');
		else Request::instance()->redirect('logowanie');
		
		$user_id = Auth::instance()->get_user()->id;
		$user = ORM::Factory('user', $user_id );
	
		
		if ($_POST) {
			
            $data = ac_form::clear_form_data($_POST);
			
			
			$payment = explode("_", $data['payment']);
			
			if( $payment[0] == "online" ) {
				$amount = $payment[1];
				
				$up = ORM::Factory('user_payment');
				$up->status = 0;
				$up->amount = $amount;
				$up->period = $payment[2];
				$up->user_id = $id;
				$up->save();
				
				header("Location: https://ssl.dotpay.pl?id=".Kohana::config('site.DOTPAY_ID')."&lang=pl&currency=pln&amount=".$amount."&description=Promowanie w ".$_SERVER['HTTP_HOST']."&urlc=http://".$_SERVER['HTTP_HOST']."/account/notice_confirmation?pid=".$up->id);
				exit;
			}
			
			if( $payment[0] == "sms" ) {
				if( !empty( $data['check'] ) ) {

						$id_customer = Kohana::config('site.DOTPAY_ID');              # numer ID zarejestrowanego klienta
						$code = Kohana::config('site.SMS_ID');        # identyfikator usług SMS
						$type = "c1,sms";         # typ konta: C1 - 8 znakowy kod bezobsługowy
											 # typ konta: sms dla sprawdzania SMSow
						
						#
						# gdy sprawdzane będą zarówno konta smsowe jak i konta przy płatnościach kartą
						# to należy wtedy użyć zapisu:
						# $type = "c1,sms";
						#
						#
						# przy sprawdzaniu kilku kont o różnych identyfikatorach należy użyć zapisu:
						# $code = "abcd1,abcd2,kody2,kody6"; 
						# $check = "xxxxxxxx"; # podany kod na stronie gdzie wejście jest płatne i wymagany jest zakupiony kod
						

							$del=0;                # jezeli kod ma byc jednorazowy to ustaw wartosc na 1;

						
							$check = $data['check'];
	
							$array = array();
							$array['check']= $check;
							$array['code'] = $code;
							$array['id']   = $id_customer;
							$array['type'] = $type;
							$array['del']  = $del;

							$handle = fopen("http://dotpay.pl/check_code.php?check=".$check."&id=".$id_customer."&code=".$code."&type=".$type."&del=".$del, 'r');
							$status = fgets($handle, 8);
							$czas_zycia = fgets($handle, 24);
							fclose($handle);
						

							$dane = explode("\n", $czas_zycia);
							$status = $dane[0];
							$ip = $_SERVER['REMOTE_ADDR'];
							$data = time();
						
							if ($status == 0) { 
					
								Message::error(__t('Kod jest niepoprawny!'));
								Request::instance()->redirect('account/notice/promo/'.$id);
								exit;
								
							}  # gdy kod niepoprawny
							else 
							{  
								$user_payment = ORM::Factory('user_payment', $pid );
								$user_payment->highlight = 1;
								$user_payment->save();
								
								Message::success(__t('Wpłata została przekazana! '));
								Request::instance()->redirect('account/notice');
								exit;

							}
				
			
				exit;
				
				}  
				
				Message::success('<form action="" method="post"><span style="float: left;">Wyślij SMS na numer '.Kohana::config('site.SMS_NUMBER').' o treści '.Kohana::config('site.SMS_TEXT').'. Wpisz kod dostępu: </span><input type="hidden" name="payment" value="'.$data['payment'].'"/><input type="text" name="check" style="float: left; margin: -2px 0px 0px 5px; padding: 0px; width: 60px; padding: 3px;" value=""/><input style="float: left;  margin: -2px 0px 0px 5px;padding: 3px;" type="submit" value="OK"/></form>');
				Request::instance()->redirect('account/notice/promo/'.$id);
			}
				
			
			Request::instance()->redirect('account/notice');

			
		}

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

	public function action_notice_confirmation() {
		
		$pid = addslashes( $_GET['pid'] );
		
		// numer konta w systemie Dotpay (Dotpay ID)
		$id = Kohana::config('site.DOTPAY_ID');

		// PIN należy ustawić w panelu administracyjnym "Mój Dotpay" w sekcji "Ustawienia -> parametry URLC". Musi mieć dokładnie 16 znaków alfanumerycznych. 
						
		$PIN = Kohana::config('site.DOTPAY_PIN');
		
		if( $_POST ) {
		
			foreach ($_POST as $key => $value)
			$data .= $key . "=>" . $value . "\r\n";

			// Definiowane po stronie Dotpay

			$dotpay_id = mysql_real_escape_string(trim($_POST['id']));
			$status_transakcji = mysql_real_escape_string(trim($_POST['t_status']));
			$numer_transakcji = mysql_real_escape_string(trim($_POST['t_id']));
			$ststus_platnosci = mysql_real_escape_string(trim($_POST['status']));
			$oryginalna_kwota = mysql_real_escape_string(trim($_POST['orginal_amount']));
			$data_transakcji = mysql_real_escape_string(trim($_POST['t_date']));
			$code = mysql_real_escape_string(trim($_POST['code']));
			$username = mysql_real_escape_string(trim($_POST['username']));
			$password = mysql_real_escape_string(trim($_POST['password']));
			$dotpay_md5 = mysql_real_escape_string(trim($_POST['md5']));

			// Definiowane przez kontrahenta oraz klienta

			$service = mysql_real_escape_string(trim($_POST['service']));
			$kwota = mysql_real_escape_string(trim($_POST['amount']));
			$control = mysql_real_escape_string(trim($_POST['control']));
			$email_kupujacego = mysql_real_escape_string(trim($_POST['email']));
			$opis = mysql_real_escape_string(trim($_POST['description']));

			//Modyfikacje parametrów
			$ip = $_SERVER['REMOTE_ADDR'];
			$dotpay_ip = "195.150.9.37";

			if ($status_transakcji == 2) {


				$user_payment = ORM::Factory('user_payment', $pid );
				$user_payment->highlight = 1;
				$user_payment->save();
				
				Message::success(__t('Wpłata została przekazana! '));
				Request::instance()->redirect('account/notice');
				exit;

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

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

		if( !Auth::instance()->logged_in() )  Request::instance()->redirect('logowanie');
	
		$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.');
			Request::instance()->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() )  Request::instance()->redirect('logowanie');
	
		$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.');
			Request::instance()->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();
		
		
		if( $_GET['layout'] != 2 ) {
		$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
        );
    }	
	

}