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

class Postad extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{
		$this->load->model('categories_model');
                $this->load->model('user_model');
		$this->load->helper('captcha');
		$parent_categories=$this->categories_model->getParentCategories();
		$data['parent_categories']=$parent_categories;
                $contact=null;
                if($this->session->userdata('is_login') && $this->session->userdata('user_id')){
                    $user=$this->user_model->getUser($this->session->userdata('user_id'));
                    $contact=$user->phone;
                }
		$this->rand = random_string('numeric', 4);
		$this->session->set_userdata('verification_code',$this->rand);
		 $vals = array(
		     'word'   => $this->rand,
		     'img_path'  => './captcha/',
		     'img_url'   => base_url() . 'captcha/',
		     //'font_path'    => './system/fonts/texb.ttf',
		     'img_width'    => '150',
		     'img_height' => 30,
		     'expiration' => 7200
		     );

		
		$cap = create_captcha($vals);
		
		
		$data['veri_image']=$cap;
                $data['contact']=$contact;
		$data['main_content']='postad';
		$data['title']='Post Your ad';
		$data['bodyid']='postad';
		$this->load->view('template',$data);
		
	}
	public function newad()
	{
		
		if(isset($_POST) && !empty($_POST)){
			$this->load->model('user_model');
			$title=$this->input->post('title');
			$description=$this->input->post('description');
			$category_id=$this->input->post('category');
			$price=$this->input->post('price');
			$original_price=$this->input->post('original_price');
			$user_id= $this->input->post('user_id');//$_SESSION['user_id'];
                        $adtype= $this->input->post('adtype');//$_SESSION['user_id'];
			$captcha=$this->input->post('captcha');
			$published=0;
                        $phone=$this->input->post('contact');
			if($user_id==0){
			     $email=$this->input->post('email');
			     $name=$this->input->post('name');
                             
			     $user=$this->user_model->checkUser($email);
			     if(!$user){
				$user_id=$this->user_model->createUser($name,$email,null,1,$phone);
			     }else{
				$user_id=$user;
			     }
			     
			}else{
				$user=$this->user_model->getUser($user_id);
				if($user->verified==1){ $published = 1;}
			}
			$data = array(
			   'title' => $title ,
			   'description' => $description ,
			   'user_id' => $user_id,
                            'adtype'=>$adtype,
                            'phone'=>$phone,
			   'category_id' => $category_id,
			   'price' => $price,
		           'original_price' => $original_price,
			   'published' => $published,
			   'views' => 0,
			   'dt_created' => date('Y:m:d h:i:s'),
			   'dt_modified'=> date('Y:m:d h:i:s')
			);

			$result=$this->db->insert('postings', $data); 

			if($result){
			$image_url='';
				$posting_id= $this->db->insert_id();
				$config['upload_path'] = dirname($_SERVER['SCRIPT_FILENAME']).'/assets/adimages/';
				$config['allowed_types'] = 'gif|jpg|png|jpeg';
				
				$this->load->library('upload', $config);
				$field_name = "filename";

				if ( ! $this->upload->do_upload($field_name))
				{
					$error = array('error' => $this->upload->display_errors());
						//echo '<div id="status">error</div>';
						//echo '<div id="message">'.$error['error'].'</div>';
				}
				else
				{
					$data = array('upload_data' => $this->upload->data());
					$image_url=$data['upload_data']['file_name'];
						//echo '<div id="status">success</div>';
						//then output your message
						//echo '<div id="message">Your file success message</div>';
						//print_r($data);
						$dataarray = array(
						   'posting_id'=>$posting_id,
						   'image_url' => $data['upload_data']['file_name'] ,
						   'is_main'=>1
						);
						$result=$this->db->insert('postingimages', $dataarray); 
						

					//$this->load->view('upload_success', $data);
				}
				if($published==1){
					$params = array(
						
						"message" => $title,
						"link" => base_url().'details/'.formatText($title).'/'.$posting_id,
						"picture" => $image_url,
						"name" => $title,
						//"caption" => "www.pontikis.net",
						"description" =>$description
					);
					$post_id=$this->postToFB($params);
                                        if($post_id){
                                            $this->db->where('id',$posting_id);
                                            $this->db->update('postings',array('fb_post_id'=>$post_id));
                                        }
				}

					redirect(base_url().'details/'.formatText($title).'/'.$posting_id);
			}else{

			}
		}
		
	}
	public function response(){
		$cname=$this->input->post('cname');
		$cemail=$this->input->post('cemail');
		$contact=$this->input->post('contact');
		$comment=$this->input->post('comment');
		$listing_id=$this->input->post('listid');
		$user_id= $this->input->post('cid');
		$data=array(
			'user_id' => $user_id,
			'listing_id' => $listing_id,
			'cname' => $cname ,
			'cemail' => $cemail ,
			'comment' => $comment,
		        'contact' => $contact,
			'view_status' => 0,
			'dt_created' => date('Y:m:d h:i:s'),
			'dt_modified'=> date('Y:m:d h:i:s')
		);
		$result=$this->db->insert('inquiries', $data); 
                if($result){
                    $data['success']=true;
                }else{
                    $data['success']=false;
                    $data['message']='There was a problem processing your request.Please try again later.';
                }
                echo json_encode($data);
	}
        public function edit(){
            if(isset($_POST) && !empty($_POST)){
                        $posting_id=  $this->input->post('posting_id');
			$this->load->model('user_model');
			$title=$this->input->post('title');
			$description=$this->input->post('description');
			$category_id=$this->input->post('category');
			$price=$this->input->post('price');
			$original_price=$this->input->post('original_price');
			$user_id= $this->input->post('user_id');//$_SESSION['user_id'];
			$published=0;
                        $phone=$this->input->post('contact');
			
                        $user=$this->user_model->getUser($user_id);
			if($user->verified==1){ $published = 1;}
			
			$data = array(
			   'title' => $title ,
			   'description' => $description ,
			   'user_id' => $user_id,
                           'phone'=>$phone,
			   'category_id' => $category_id,
			   'price' => $price,
		           'original_price' => $original_price,
			   'published' => $published,
			   'dt_modified'=> date('Y:m:d h:i:s')
			);
                       
			$result=$this->db->update('postings', $data,array('id' => $posting_id)); 
                        $config['upload_path'] = dirname($_SERVER['SCRIPT_FILENAME']).'/assets/adimages/';
			$config['allowed_types'] = 'gif|jpg|png|jpeg';
			$this->load->library('upload', $config);
			$field_name = "adimage";
                         for($i = 1; $i < 6; $i++) {
                             echo $i;
                            /* Handle the file upload */
                            $upload = $this->upload->do_upload('adimage'.$i);
                            print_r($upload);
                            /* File failed to upload - continue */
                            if($upload === FALSE) {
                               echo $this->upload->display_errors();
                            }else{
                                /* Get the data about the file */
                                $data = $this->upload->data();
                                $dataarray = array(
                                    'posting_id'=>$posting_id,
                                    'image_url' => $data['file_name'] ,
                                    'is_main'=>0
                                );
                                $result=$this->db->insert('postingimages', $dataarray); 
                            }
                            //$uploadedFiles[$i] = $data;
                            /* If the file is an image - create a thumbnail */
//                            if($data['is_image'] == 1) {
//                              $configThumb['source_image'] = $data['full_path'];
//                              $this->image_lib->initialize($configThumb);
//                              $this->image_lib->resize();
//                            }
                          }
                          

					//$this->load->view('upload_success', $data);
				
					redirect('details/'.formatText($title).'/'.$posting_id);
			
		}
        }
        public function postToFB($data){
                require(APPPATH.'/third_party/fbsdk/Facebook/autoload.php');
		
		$fb = new Facebook\Facebook([
		  'app_id'     => '1509366035981264',
		  'app_secret' => '93d1a42bac5d0f3912e28ed0b987d28a',
		  'default_graph_version' => 'v2.2',
		  ]);
		  $access_token='EAAVcwqppI9ABAKP6MrWIjviQysTLZAAe56CLRM8N9iAvlhuZCZCZBRCevbg30vR06RDkdFZBC0wzebC1SYCabpYjZA7ndZAgheIOWwTDZBZBju8ZCtI7Xu3r7DC6AUaHgREJer7mCbTL9hJxLCMYiAu5BiopSZAAjzsi1534lKhEeaA6QZDZD';
$data['access_token']=$access_token;
		   $res = $fb->post( '/1756549887910962/feed',$data);
 
                  $post = $res->getGraphObject();
 
               
 
                return $post_id = $post->getProperty('id');

                  }
        
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */