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

/**
 * 
 * User related functions
 * @author Teamtweaks
 *
 */

class Order extends MY_Controller { 
	function __construct(){
        parent::__construct();
		$this->load->helper(array('cookie','date','form','email'));
		$this->load->library(array('encrypt','form_validation'));		
		$this->load->model('order_model');
		$this->load->model('product_model');
		
		$this->data['loginCheck'] = $this->checkLogin('U');
    }
    
  
	/**
	 * 
	 * Loading Order Page
	 */
	
	public function index(){
		
		
		if ($this->data['loginCheck'] != ''){
			$this->data['meta_title'] = $this->data['heading'] = 'Order Confirmation'; 
			if($this->uri->segment(2) == 'giftsuccess'){
				if($this->uri->segment(4)==''){
					$transId = $_REQUEST['txn_id'];
					$Pray_Email = $_REQUEST['payer_email'];
				}else{
					$transId = $this->uri->segment(4);
					$Pray_Email = '';
				}	
				
				$GiftSuccessCheck = $this->order_model->get_all_details(GIFTCARDS_TEMP,array( 'user_id' => $this->uri->segment(3)));
				if($GiftSuccessCheck->num_rows() > 0){
					$this->data['Confirmation'] = $this->order_model->PaymentGiftSuccess($this->uri->segment(3),$transId,$Pray_Email);	
				}
					
				redirect("order/confirmation/gift");
			}elseif($this->uri->segment(2) == 'subscribesuccess'){
					$transId = $this->uri->segment(4);
					$Pray_Email = '';
				
				$this->data['Confirmation'] = $this->order_model->PaymentSubscribeSuccess($this->uri->segment(3),$transId);	
				redirect("order/confirmation/subscribe");
				
			}elseif($this->uri->segment(2) == 'success'){
				if($this->uri->segment(5)==''){
					$transId = $_REQUEST['txn_id'];
					$Pray_Email = $_REQUEST['payer_email'];
				}else{
					$transId = $this->uri->segment(5);
					$Pray_Email = '';
				}	
				$PaymentSuccessCheck = $this->order_model->get_all_details(PAYMENT,array( 'user_id' => $this->uri->segment(3), 'dealCodeNumber' => $this->uri->segment(4),'status'=>'Paid'));		
				if($PaymentSuccessCheck->num_rows() == 0){
					$this->data['Confirmation'] = $this->order_model->PaymentSuccess($this->uri->segment(3),$this->uri->segment(4),$transId,$Pray_Email);	
				}
				redirect("order/confirmation/cart");
				//$this->load->view('site/order/order.php',$this->data);
			
			}elseif($this->uri->segment(2) == 'sellersuccess'){
				if($this->uri->segment(5)==''){
					$transId = $_REQUEST['txn_id'];
					$Pray_Email = $_REQUEST['payer_email'];
				}else{
					$transId = $this->uri->segment(5);
					$Pray_Email = '';
				}	
				$UserPaymentSuccessCheck = $this->order_model->get_all_details(USER_PAYMENT,array( 'user_id' => $this->uri->segment(3), 'dealCodeNumber' => $this->uri->segment(4),'status'=>'Paid'));		
				if($UserPaymentSuccessCheck->num_rows() == 0){
					$this->data['Confirmation'] = $this->order_model->UserPaymentSuccess($this->uri->segment(3),$this->uri->segment(4),$transId,$Pray_Email);	
				}
				
				redirect("order/confirmation/cart");
				//$this->load->view('site/order/order.php',$this->data);
			}elseif($this->uri->segment(2) == 'productsuccess'){
					$totAmt = $this->uri->segment(3);
				if($this->uri->segment(5)==''){
					$transId = $_REQUEST['txn_id'];
					$Pray_Email = $_REQUEST['payer_email'];
				}else{
					$transId = $this->uri->segment(5);
					$Pray_Email = '';
				}	
				
				$this->data['Confirmation'] = $this->order_model->UserPaymentProductSuccess($this->uri->segment(4),$totAmt,$transId,$Pray_Email);	
				
				redirect("order/confirmation/product");
				//$this->load->view('site/order/order.php',$this->data);	
				
			
			}elseif($this->uri->segment(2) == 'successgift'){
				
				$transId = 'GIFT'.$this->uri->segment(4);
				$Pray_Email = '';
				$this->data['Confirmation'] = $this->order_model->PaymentSuccess($this->uri->segment(3),$this->uri->segment(4),$transId,$Pray_Email);	
				redirect("order/confirmation");
			
			}elseif($this->uri->segment(2) == 'productfailure'){
				
				$this->data['meta_title'] = $this->data['Confirmation'] = 'Failure';
				$this->data['errors'] = $this->uri->segment(3);
				$this->data['productPage'] = 'ProductRedirect';
				$this->load->view('site/order/order.php',$this->data);
			
			}elseif($this->uri->segment(2) == 'failure'){
				
				$this->data['meta_title'] = $this->data['Confirmation'] = 'Failure';
				$this->data['errors'] = $this->uri->segment(3);
				$this->load->view('site/order/order.php',$this->data);
			}elseif($this->uri->segment(2) == 'notify'){
				$this->data['meta_title'] = $this->data['Confirmation'] = 'Failure';			
				$this->load->view('site/order/order.php',$this->data);
			}elseif($this->uri->segment(2) == 'confirmation'){
				$this->data['meta_title'] = $this->data['Confirmation'] = 'Success';
			 	$this->load->view('site/order/order.php',$this->data);
			}
			
			
		}else{
			redirect('login');
		}	
	}
	
	
	
	public function ipnpayment(){

		mysql_query('CREATE TABLE IF NOT EXISTS '.TRANSACTIONS.' ( `id` int(11) NOT NULL AUTO_INCREMENT,`payment_cycle` varchar(255) NOT NULL,`txn_type` varchar(255) NOT NULL, `last_name` varchar(255) NOT NULL,`next_payment_date` varchar(255) NOT NULL, `residence_country` varchar(255) NOT NULL, `initial_payment_amount` varchar(255) NOT NULL, `currency_code` varchar(255) NOT NULL, `time_created` varchar(255) NOT NULL, `verify_sign` varchar(750) NOT NULL, `period_type` varchar(255) NOT NULL, `payer_status` varchar(255) NOT NULL, `test_ipn` varchar(255) NOT NULL, `tax` varchar(255) NOT NULL, `payer_email` varchar(255) NOT NULL, `first_name` varchar(255) NOT NULL, `receiver_email` varchar(255) NOT NULL, `payer_id` varchar(255) NOT NULL, `product_type` varchar(255) NOT NULL, `shipping` varchar(255) NOT NULL, `amount_per_cycle` varchar(255) NOT NULL, `profile_status` varchar(255) NOT NULL, `charset` varchar(255) NOT NULL, `notify_version` varchar(255) NOT NULL, `amount` varchar(255) NOT NULL, `outstanding_balance` varchar(255) NOT NULL, `recurring_payment_id` varchar(255) NOT NULL, `product_name` varchar(255) NOT NULL,`custom_values` varchar(255) NOT NULL, `ipn_track_id` varchar(255) NOT NULL, `tran_date` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3;');

		mysql_query("insert into ".TRANSACTIONS." set  payment_cycle='".$_REQUEST['payment_cycle']."', txn_type='".$_REQUEST['txn_type']."', last_name='".$_REQUEST['last_name']."',
next_payment_date='".$_REQUEST['next_payment_date']."', residence_country='".$_REQUEST['residence_country']."', initial_payment_amount='".$_REQUEST['initial_payment_amount']."',
currency_code='".$_REQUEST['currency_code']."', time_created='".$_REQUEST['time_created']."', verify_sign='".$_REQUEST['verify_sign']."', period_type= '".$_REQUEST['period_type']."', payer_status='".$_REQUEST['payer_status']."', test_ipn='".$_REQUEST['test_ipn']."', tax='".$_REQUEST['tax']."', payer_email='".$_REQUEST['payer_email']."', first_name='".$_REQUEST['first_name']."', receiver_email='".$_REQUEST['receiver_email']."', payer_id='".$_REQUEST['payer_id']."', product_type='".$_REQUEST['product_type']."', shipping='".$_REQUEST['shipping']."', amount_per_cycle='".$_REQUEST['amount_per_cycle']."', profile_status='".$_REQUEST['profile_status']."', charset='".$_REQUEST['charset']."',
notify_version='".$_REQUEST['notify_version']."', amount='".$_REQUEST['amount']."', outstanding_balance='".$_REQUEST['payment_status']."', recurring_payment_id='".$_REQUEST['txn_id']."', product_name='".$_REQUEST['product_name']."', custom_values ='".$_REQUEST['custom']."', ipn_track_id='".$_REQUEST['ipn_track_id']."', tran_date=NOW()");


		$this->data['heading'] = 'Order Confirmation'; 

		if($_REQUEST['payment_status'] == 'Completed'){
			$newcustom = explode('|',$_REQUEST['custom']);
	
			if($newcustom[0]=='Product'){
				$userdata = array('shopsy_session_user_id' => $newcustom[1],'randomNo' => $newcustom[2]);
				$this->session->set_userdata($userdata);	
				$transId = $_REQUEST['txn_id'];
				$Pray_Email = $_REQUEST['payer_email'];
				$this->data['Confirmation'] = $this->order_model->PaymentSuccess($newcustom[1],$newcustom[2],$transId,$Pray_Email);	
				//$userdata = array('shopsy_session_user_id' => $newcustom[1],'randomNo' => $newcustom[2]);
				$this->session->unset_userdata($userdata);
			}elseif($newcustom[0]=='Gift'){
				$userdata = array('shopsy_session_user_id' => $newcustom[1]);
				$this->session->set_userdata($userdata);
				$transId = $_REQUEST['txn_id'];
				$Pray_Email = $_REQUEST['payer_email'];
				$this->data['Confirmation'] = $this->order_model->PaymentGiftSuccess($newcustom[1],$transId,$Pray_Email);	
				//$userdata = array('shopsy_session_user_id' => $newcustom[1]);
				$this->session->unset_userdata($userdata);
			}elseif($newcustom[0]=='SellerProduct'){
				$userdata = array('shopsy_session_user_id' => $newcustom[1],'UserrandomNo' => $newcustom[2]);
				$this->session->set_userdata($userdata);	
				$transId = $_REQUEST['txn_id'];
				$Pray_Email = $_REQUEST['payer_email'];
				$this->data['Confirmation'] = $this->order_model->UserPaymentSuccess($newcustom[1],$newcustom[2],$transId,$Pray_Email);	
				//$userdata = array('shopsy_session_user_id' => $newcustom[1],'randomNo' => $newcustom[2]);
				$this->session->unset_userdata($userdata);
		
			}elseif($newcustom[0]=='SellerProductPayment'){
				$userdata = array('shopsy_session_user_id' => $newcustom[1]);
				$this->session->set_userdata($userdata);	
				$transId = $_REQUEST['txn_id'];
				$Pray_Email = $_REQUEST['payer_email'];
				$this->data['Confirmation'] = $this->order_model->UserPaymentProductSuccess($newcustom[1],$transId,$Pray_Email);	
				//$userdata = array('shopsy_session_user_id' => $newcustom[1],'randomNo' => $newcustom[2]);
				$this->session->unset_userdata($userdata);
			}
			

		}	
			
	}
	
	
	public function insert_product_comment(){
	 			$uid= $this->checkLogin('U');
				$returnStr['status_code'] = 0;
				$comments = $this->input->post('comments');
				$product_id = $this->input->post('cproduct_id');
				$datestring = "%Y-%m-%d %h:%i:%s";
				$time = time();
				$conditionArr = array('comments'=>$comments,'user_id'=>$uid,'product_id'=>$product_id,'status'=>'InActive','dateAdded'=>mdate($datestring,$time));
				$this->order_model->simple_insert(PRODUCT_COMMENTS,$conditionArr);
				$cmtID = $this->order_model->get_last_insert_id();
				$datestring = "%Y-%m-%d %h:%i:%s";
				$time = time();
				$createdTime = mdate($datestring,$time);
				$actArr = array(
					'activity'		=>	'own-product-comment',
					'activity_id'	=>	$product_id,
					'user_id'		=>	$this->checkLogin('U'),
					'activity_ip'	=>	$this->input->ip_address(),
					'created'		=>	$createdTime,
					'comment_id'	=> $cmtID
				);
				$this->order_model->simple_insert(NOTIFICATIONS,$actArr);
				$this->send_comment_noty_mail($cmtID,$product_id);
				$returnStr['status_code'] = 1;
				echo json_encode($returnStr);
	}
	
	public function send_comment_noty_mail($cmtID='0',$pid='0'){
		if ($this->checkLogin('U')!=''){
			if ($cmtID != '0' && $pid != '0'){
				$productUserDetails = $this->product_model->get_product_full_details($pid);
				if ($productUserDetails->num_rows()==1){
					$emailNoty = explode(',', $productUserDetails->row()->email_notifications);
					if (in_array('comments', $emailNoty)){
						$commentDetails = $this->product_model->view_product_comments_details('where c.id='.$cmtID);
						if ($commentDetails->num_rows() == 1){
							if ($productUserDetails->prodmode == 'seller'){
								$prodLink = base_url().'things/'.$productUserDetails->row()->id.'/'.url_title($productUserDetails->row()->product_name,'-');
							}else {
								$prodLink = base_url().'user/'.$productUserDetails->row()->user_name.'/things/'.$productUserDetails->row()->seller_product_id.'/'.url_title($productUserDetails->row()->product_name,'-');
							}
							
							$newsid='1';
							$template_values=$this->order_model->get_newsletter_template_details($newsid);
							$adminnewstemplateArr=array('email_title'=> $this->config->item('email_title'),'logo'=> $this->data['logo'],'full_name'=>$commentDetails->row()->full_name,'product_name'=>$productUserDetails->row()->product_name,'user_name'=>$commentDetails->row()->user_name);
							extract($adminnewstemplateArr);
							$subject = $this->config->item('email_title').' - '.$template_values['news_subject'];
							
							$message .= '<!DOCTYPE HTML>
								<html>
								<head>
								<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
								<meta name="viewport" content="width=device-width"/>
								<title>'.$template_values['news_subject'].'</title>
								<body>';
							include('./newsletter/registeration'.$newsid.'.php');	
							
							$message .= '</body>
								</html>';
							
							if($template_values['sender_name']=='' && $template_values['sender_email']==''){
								$sender_email=$this->data['siteContactMail'];
								$sender_name=$this->data['siteTitle'];
							}else{
								$sender_name=$template_values['sender_name'];
								$sender_email=$template_values['sender_email'];
							}
		
							$email_values = array('mail_type'=>'html',
												'from_mail_id'=>$sender_email,
												'mail_name'=>$sender_name,
												'to_mail_id'=>$productUserDetails->row()->email,
												'subject_message'=>$subject,
												'body_messages'=>$message
												);
							$email_send_to_common = $this->product_model->common_email_send($email_values);
						}
					}
				}
			}
		}
	}
	
	public function discussion($orderID=''){
		if ($this->checkLogin('U') != '' || $this->checkLogin('A')!=''){
			if ($this->checkLogin('A')!='' && $this->checkLogin('U') == ''){
				$checkUser = $this->order_model->get_all_details(USERS,array('id' => $this->checkLogin('A')));
					if ($checkUser->num_rows() == 1){ 					
					$userdata1 = array('shopsy_session_user_id'=>'','shopsy_session_user_name'=>'','shopsy_session_full_name'=>'','shopsy_session_user_email'=>'','shopsy_session_temp_id'=>'');
					$this->session->unset_userdata($userdata1);
					$this->session->unset_userdata('currency_data');
					$this->session->unset_userdata('region');
								delete_cookie("Shopsy_NewUser");
								
					$userdata = array(
								'shopsy_session_user_id' => $checkUser->row()->id,
								'shopsy_session_user_name' => $checkUser->row()->user_name,
								'shopsy_session_full_name' => $checkUser->row()->full_name,
								'shopsy_session_user_email' => $checkUser->row()->email,
								'userType'=>$checkUser->row()->group
							);
					}
					$this->session->set_userdata($userdata);
					$this->data['loginCheck'] =$checkUser->row()->id;
					$this->setErrorMessage('success','Welcome, Admin');
		
		 }
			$this->data['heading'] = 'Order Discussion';
			$this->data['ViewList'] = $this->order_model->order_discussion_init($orderID);
			$this->data['ordercomments'] = $ordercomments=$this->order_model->get_all_details(ORDER_COMMENTS,array('orderid'=>$orderID),array(array('field'=>'post_time','type'=>'desc')));
			#echo $ordercomments->num_rows();
			$this->load->view('site/order/discussion',$this->data);
		
		
		}else {
			redirect('login');			
		}			
	}
	public function postcomment(){
		$orderid=$this->input->post('orderid');
		$post_message=$this->input->post('post_message');
		$buyerid=$this->input->post('buyerid');
		$sellerid=$this->input->post('sellerid');
		$post_time=date('Y-m-d H:i:s');
		
		$orderinformation=$this->order_model->get_order_details($orderid);
		
		if($this->checkLogin('U')==$buyerid){
			$posted_by='buyer';
			$sender_name=$orderinformation->row()->buyer_name;
			$sender_email=$orderinformation->row()->buyer_mail;
			$receive_email=$orderinformation->row()->seller_mail;
			$ccmail=$this->data['siteContactMail'];
		}elseif($this->checkLogin('U')==$sellerid){
			$posted_by='seller';
			$sender_name=$orderinformation->row()->seller_name;
			$sender_email=$orderinformation->row()->seller_mail;
			$receive_email=$orderinformation->row()->buyer_mail;
			$ccmail=$this->data['siteContactMail'];
		}else{
			$posted_by='admin';
			$sender_name=$this->data['siteTitle'].' Admin';
			$sender_email=$this->data['siteContactMail'];
			$receive_email=$orderinformation->row()->buyer_mail.','.$orderinformation->row()->seller_mail;
			$ccmail='';
		}		
		$postArr = array(
					'orderid'		=>	$orderid,
					'posted_by'		=>	$posted_by,
					'posted_id'		=>	$this->checkLogin('U'),
					'post_message'	=>	$post_message,
					'post_time'		=>	$post_time,
					'status'		=> 'Publish'
				);
		$this->order_model->simple_insert(ORDER_COMMENTS,$postArr);
		/*mailing process starts here*/
		$newsid='10';
		$template_values=$this->order_model->get_newsletter_template_details($newsid);
		$subject = 'From: '.$this->config->item('email_title');
		$discussionurl=base_url().'discussion/'.$orderid;
		$adminnewstemplateArr=array('email_title'=> $this->config->item('email_title'),'logo'=> $this->data['logo'],'footer_content'=> $this->config->item('footer_content'));
		extract($adminnewstemplateArr);
		$header .="Content-Type: text/plain; charset=ISO-8859-1\r\n";
				
		$message .= '<!DOCTYPE HTML>
		<html>
		<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<meta name="viewport" content="width=device-width"/><body>';
		include('./newsletter/registeration'.$newsid.'.php');	
		$message .= '</body>
		</html>';
		$email_values = array('mail_type'=>'html',
					'from_mail_id'=>$sender_email,
					'mail_name'=>$sender_name,
					'to_mail_id'=>$receive_email,
					'cc_mail_id'=>$ccmail,
					'subject_message'=>$template_values['news_subject'],
					'body_messages'=>$message
					);
		$email_send_to_common = $this->order_model->common_email_send($email_values);
		
		$ordercomments=$this->order_model->get_all_details(ORDER_COMMENTS,array('orderid'=>$orderid),array(array('field'=>'post_time','type'=>'desc')));
		foreach($ordercomments->result() as $comments){
			$posterinfo=$this->order_model->get_all_details(USERS,array('id'=>$comments->posted_id));
			if($posterinfo->row()->thumbnail!=''){
				$post_img=$posterinfo->row()->thumbnail;
			}else{
				$post_img='profile_pic.png';
			}
			/*time frame*/
			$datediff = time()-strtotime($comments->post_time); 
			$diffdate=floor($datediff/(60*60*24));
			if($diffdate!=0){
				if($diffdate<4){
					$cmtTime =$diffdate.' days ago';
				}else{
					$cmtTime =date('m/d/y',strtotime($comments->post_time));
				}
			}else{
				if(floor($datediff/(60*60))<1){
					if(floor($datediff/(60))>0){
						$cmtTime =floor($datediff/(60)).' mins ago';
					}else{
						$cmtTime ='just now';
					}
				}else{
					$cmtTime= floor($datediff/(60*60)).' hours ago';
				}
			}
			if($comments->posted_id==$this->checkLogin('U')){
				$post_by='You - '.$posterinfo->row()->user_name;
			}else{
				$post_by=$comments->posted_by.' - '.$posterinfo->row()->user_name;
			}
			$commentsDeatail.='<tr class="postCMT">
				<td class="post_img">
					<a href="view-people/'.$posterinfo->row()->user_name.'">
						<img src="images/users/thumb/'.$post_img.'" alt="'.$post_img.'" class="post_imgthumb" />
					</a>
				</td>
				<td class="post_msg" width="95%">
					<p class="post_by"><a href="view-people/'.$posterinfo->row()->user_name.'"><strong>'.ucfirst($post_by).'</strong></a></p>
					<p class="post_message">'.$comments->post_message.'</p>
					<p class="cmtTime">'.$cmtTime.'</p>
				</td>
			</tr>';
		}
		echo $commentsDeatail.'|<^>|'.$ordercomments->num_rows;;
	}
	public function digital_files($user_id='',$dealcode=''){
		$dealcode=$this->encrypt->decode(strtr($dealcode, '-.~', '+/='));
		$user_id=$this->encrypt->decode(strtr($user_id, '-.~', '+/='));
		
		$UserCheck = $this->order_model->get_all_details(USER_PAYMENT,array( 'user_id' => $user_id, 'dealCodeNumber' => $dealcode,'status'=>'Paid'));	
		if($UserCheck->num_rows()>0){
			$this->data['UserData']=$checkUser = $this->order_model->get_all_details(USERS,array( 'id' => $user_id));			
			###$this->data['orderInfo']=$orderInfo= $this->order_model->get_all_details(USER_PAYMENT,array( 'user_id' => $user_id, 'dealCodeNumber' => $dealcode,'status'=>'Paid'));	
			$this->data['orderInfo'] = $this->order_model->order_discussion_init($dealcode,$user_id);
			$this->data['heading'] = 'Digital Files Downloading'; 
			$this->load->view('site/order/digitalfile.php',$this->data);
		}else{
			$this->setErrorMessage('error','You are not a valid user');
			redirect(base_url());
		}
	}
	public function donwload($file_name='',$dealCode='',$user_id=''){
		$UserCheck = $this->order_model->get_all_details(USER_PAYMENT,array( 'user_id' => $user_id, 'dealCodeNumber' => $dealCode,'status'=>'Paid'));	
		$fileArrr=@explode(',',rtrim($UserCheck->row()->digital_files,','));
		$i=0;
		foreach($fileArrr as $files){
			if($files==$file_name){
				unset($fileArrr[$i]);
			}
			$i++;
		}
		if(!empty($fileArrr)){
			$newVal=implode(',',$fileArrr).',';
		}else{
			$newVal='';
		}
		$dataArr = array('digital_files'=>$newVal);
		$conditionArr = array('id'=>$UserCheck->row()->id);
		$this->order_model->update_details(USER_PAYMENT,$dataArr,$conditionArr);
		$dataArry = array('user_id'=>$UserCheck->row()->user_id,'order_id'=>$UserCheck->row()->dealCodeNumber,'file_name'=>$file_name,'download_time'=>date('Y-m-d H:i:s'),'p_id'=>$UserCheck->row()->product_id);
		$this->order_model->simple_insert(DIGITAL_FILE_HISTORY,$dataArry);
		
		$this->load->helper('download');
		$data = file_get_contents(base_url().'digital_files/'.$file_name);
		force_download($file_name, $data);
		#redirect($_SERVER['HTTP_REFERER']);		
	} 
	public function expire_link(){
		$this->setErrorMessage('error','This Link has been used already ');
		redirect();
	}
	
}

