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

class Order extends CI_Controller {
	public function __construct(){
		parent::__construct();
		$this->load->model('common_model');
		$this->load->model('users_model');
		if(get_cookie('admin_id'))
		{
			$this->session->set_userdata('admin_id',get_cookie('admin_id'));
		}
		if(!$this->session->userdata('admin_id'))
		{
			redirect('admin/login');
		}
	}
	public function index(){
		$content_data = array();
		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		//$content_data['orders'] = $this->common_model->getAll('shop_orders',array('order_id >'=>0),'','created DESC') ;
		/*$qry = $this->db->query("SELECT *, `shop_orders`.`created` as `created`, case when payment_date is not null then payment_date else DATE(FROM_UNIXTIME(shop_orders.created)) end as required_date FROM `shop_orders` LEFT JOIN `usr_users` ON `usr_users`.`email` = `shop_orders`.`invoiceAddress` LEFT JOIN `feu_userdetails` ON `usr_users`.`id` = `feu_userdetails`.`user_id` LEFT JOIN `shop_carts` ON `shop_carts`.`id` = `shop_orders`.`cart_id` LEFT JOIN `shop_articles_carts` ON `shop_articles_carts`.`cart_id` = `shop_carts`.`id` WHERE `order_id` >0 GROUP BY `shop_orders`.`order_id`, `feu_userdetails`.`username` ORDER BY required_date DESC");
   
        $content_data['orders'] = $qry->result_array();*/
		//echo $this->db->last_query(); die;
		$data['content'] = $this->load->view('admin/orders/list', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	public function ajaxOrder(){
		if($this->input->post()){
            //dd($req->post());
            $draw = $this->input->post('draw');
            $row = $this->input->post('start');
            $rowperpage = $this->input->post('length'); // Rows display per page
            $columnIndex = $this->input->post('order')[0]['column']; // Column index
            $columnName = $this->input->post('columns')[$columnIndex]['data'] ? $this->input->post('columns')[$columnIndex]['data'] : 'id'; // Column name
            $columnSortOrder = $this->input->post('order')[0]['dir']; // asc or desc
            
            if($columnName == 'slno' || $columnName == 'check' || $columnName == 'terms_created') {
                $columnName = 'required_date';
                $columnSortOrder = 'DESC';
            }

            $orderClause = $columnName.' '.$columnSortOrder;
            $searchValue = $_POST['search']['value']; // Search value
            ## Total number of records without filtering
            $where = "`order_id` >0 ";
            if($searchValue != ''){
			   $where .= " AND (order_id like '%".$searchValue."%' or order_id_masked like '%".$searchValue."%' or trn_id like '%".$searchValue."%' or username like '%".$searchValue."%' or shop_orders.created like '%".$searchValue."%' or shop_orders.invoiceAddress like '%".$searchValue."%') ";
			}
			$main_sql = "SELECT *, `shop_orders`.`created` as `created`, case when payment_date is not null then payment_date else DATE(FROM_UNIXTIME(shop_orders.created)) end as required_date FROM `shop_orders` LEFT JOIN `usr_users` ON `usr_users`.`email` = `shop_orders`.`invoiceAddress` LEFT JOIN `feu_userdetails` ON `usr_users`.`id` = `feu_userdetails`.`user_id` LEFT JOIN `shop_carts` ON `shop_carts`.`id` = `shop_orders`.`cart_id` LEFT JOIN `shop_articles_carts` ON `shop_articles_carts`.`cart_id` = `shop_carts`.`id` WHERE ".$where." GROUP BY `shop_orders`.`order_id`, `feu_userdetails`.`username` ORDER BY ".$orderClause;
            $testtotalRecordSql = $this->db->query($main_sql);
   
        	$testtotalRecord = $testtotalRecordSql->num_rows();
            ## Total number of record with filtering
            $testtotalRecordwithFilter = $testtotalRecord;
            ## Fetch records
            //echo $orderClause.'='.$row.'='.$rowperpage; die;
            $testSql = $this->db->query($main_sql." LIMIT ".$row.','.$rowperpage);
            $tests = $testSql->result_array();
            //echo $this->db->last_query(); die;
            //echo '<pre>';print_r($tests);die;
            $data = array();
            $status_btn = '';
            $suspend_btn = '';
            $suspend_btn = '';
            if($tests){
                foreach($tests as $key => $test){
                	if($test['upgrade_date']>0){ 
                		$cdate = date('d-m-Y H:i:s',$test['upgrade_date']);
                	} else {
                		$cdate = $test['required_date'];
                	}
                	if($test['is_exchanged'] == 1){
                		$payment_method = 'Exchange';
                	} else {
                		if($test['payment_method_id']==12){ 
	                		$payment_method = 'Bank Transfer'; 
	                	} elseif($test['payment_method_id']==13){ 
	                		$payment_method = 'Saferpay'; 
	                	} elseif($test['payment_method_id']==14){ 
	                		$payment_method = 'Stripe'; 
	                	} else{ 
	                		$payment_method = 'Pay By Bank'; 
	                	}
                	}
                	
                	if($test['event_id']!=''){ 
                		$type = 'Booking'; 
                	} elseif ($test['is_booking']==1) { 
                		$type = 'Booking'; 
                	} else { 
                		$type = 'Membership'; 
                	}
                	if($test['is_exchanged'] == 1){
                		$status = 'No Payment';
                	} else {
	                	if($test['payed']==1){ 
	                		$status = 'Paid';
	                	} elseif($test['fail_reason']!=''){ 
	                		$status = $test['fail_reason'];
	                	} else{ 
	                		$status = 'Unpaid'; 
	                	}
	                }
                	$data[] = array( 
                        "slno"=>$key + $row + 1,
                        "check"=>'<input type="checkbox" name="checkbox[]" value="'.$test['order_id'].'">',
                        "order_id_masked"=>'<a href="'.base_url().'admin/order/view/'.base64_encode($test['order_id']).'">'.$test['order_id_masked'].'</a>',
                        "terms_created"=>($test['is_booking']==1) ? date('d-m-Y H:i:s',($test['created']-48)) : '',
                        "created"=> date('Y-m-d',$test['created']),
                        "payment_date"=>($test['payment_date'] && $test['payed']==1) ? $test['payment_date'] : $cdate,
                        "total_base"=>number_format($test['total_base']/100,2,',','.'),
                        "total_sum"=>number_format($test['total_sum']/100,2,',','.'),
                        "payment_method_id"=>$payment_method,
                        "is_booking"=> $type,
                        "username"=> '<a href="'.base_url().'admin/users/edit/'.base64_encode($test['user_id']).'">'.$test['username'].'</a>',
                        "cc_ref_id"=> ($test['payment_method_id']==13) ? $test['cc_ref_id'] : '',
                        "trn_id"=> $test['trn_id'],
                        "payed"=> $status,
                        "refund_trn_id"=> ($test['refund_trn_id']!='') ? 'Refunded' : 'NA' ,
                        "is_renewed"=> ($test['is_renewed'] == 1) ? 'Renew' : '' ,
                        "action"=>'<a href="'.base_url().'admin/order/view/'.base64_encode($test['order_id']).'" title="View"><span class="fa fa-eye"></span></a>'.
		                      	(($this->session->userdata('admin_id')=='19624' || $this->session->userdata('admin_id')=='25267' || $this->session->userdata('admin_id')=='11330') ? 
		                      '<a target="_blank" href="'.base_url().'admin/order/download/'.base64_encode($test['order_id']).'" title="Download"><span class="fa fa-download"></span></a>' : '').
		                      (($test['is_renewed']==1 && $test['payed']==0) ? 
		                      '<a target="_blank" href="'.base_url().'admin/order/change_membership/'.base64_encode($test['order_id']).'" title="Change Membership Type"><span class="fa fa-pencil-square"></span></a>' : '' )
                    );
                }
            }
            //echo '<pre>';print_r($data);die;
            $total_unpaid = $this->db->query($main_sql);
            $total_unpaid_order = $total_unpaid->result_array();
            $total_unpaid_booking = 0;
            if(count($total_unpaid_order)>0){
            	foreach ($total_unpaid_order as $key => $value) {
            		if($value['created'] > (time()-60*86400) && $value['is_booking']==1 && ($value['payed']==0 || ($value['payed']==1 && $value['refund_trn_id'] !=''))){
	                    $total_unpaid_booking = $total_unpaid_booking + $value['total_sum'];
	                }
            	}
            }
            $response = array(
                "draw" => intval($draw),
                "iTotalRecords" => $testtotalRecord,
                "iTotalDisplayRecords" => $testtotalRecordwithFilter,
                "aaData" => $data,
                "total_unpaid_booking"=>number_format($total_unpaid_booking/100,2,',','.')
            );

            echo json_encode($response);die;
        }
	}
	public function delete($enc_userID='')
	{
		if($enc_userID!='')
		{
			$orderId=base64_decode($enc_userID);
			$this->common_model->deleteData('shop_orders',array('order_id'=>$orderId));
			$this->utility->setMsg('Order deleted','SUCCESS');	
			redirect(base_url().'admin/order');
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/order');
		}
	}
	public function status($enc_userID='')
	{
		if($enc_userID!='')
		{
			$orderId=base64_decode($enc_userID);
			$this->common_model->UpdateData('shop_orders',array('payed'=>1,'payment_method_id'=>15),array('order_id'=>$orderId));
			$orderDetail = $this->common_model->getAllRowMultipleJoin('shop_orders',array('order_id'=>$orderId),array(array('usr_users','usr_users.email = shop_orders.invoiceAddress'),array('feu_userdetails','feu_userdetails.user_id = usr_users.id')),'','*,shop_orders.created as created_date');
			
			

			/****************Payment Mail******************/
			if(!empty($orderDetail))
			{
				$this->common_model->UpdateData('feu_userdetails',array('reality_authenticated'=>1),array('user_id'=>$orderDetail['user_id']));
				//$to = 'sayan@digitalaptech.com';
				$to = $orderDetail['invoiceAddress'];
				$sub = getAdminLang('Confirmation',$orderDetail['userlanguage']).': '.getAdminLang('Successful_payment',$orderDetail['userlanguage']);
				$body= '<p>'.getAdminLang('We_have_received_your_payment',$orderDetail['userlanguage']).'!</p>';
				$body.= '<p>'.getAdminLang('Invoice_Number',$orderDetail['userlanguage']).': CE-'.$orderDetail['order_id'].'</p><p>'.getAdminLang('Generated_On',$orderDetail['userlanguage']).': '.date('Y-m-d',$orderDetail['created_date']).'</p><p>'.getAdminLang('Paid_Amount',$orderDetail['userlanguage']).': '.($orderDetail['total_sum']/100).' EUR</p>';
				$body.= '<p>'.getAdminLang('Invoice_will_be_located',$orderDetail['userlanguage']).'</p>';
				$body.= '<p>'.getAdminLang('We_appreciate_very_much',$orderDetail['userlanguage']).'</p>';
				$body.= '<p>'.getAdminLang('Please_do_not_hesitate_to_contact',$orderDetail['userlanguage']).'</p>';
				
				
				$bodys=' <table cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#22222c" width="100%" style="max-width: 600px;">
	                    <tr>
	                       <td>
	                          <table cellspacing="0" cellpadding="0" border="0" width="100%">
	                             <tr>
	                                <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
	                                   <h2>Dear <span style="text-transform:capitalize">'.$orderDetail['username'].'</span> </h2>
	                                </td>
	                             </tr>
	                             <tr>
	                                <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
	                                   '.$body.'
	                                </td>
	                             </tr>
	                             <tr>
	                             	<td align="center" style="font-family: sans-serif; color: rgb(179, 151, 91); padding: 20px 40px; border-top: 1px solid rgb(79, 79, 79); background: rgb(19, 18, 24) none repeat scroll 0px 0px;">
	                             		'.getAdminLang('Best_regards',$orderDetail['userlanguage']).' <br>
	                             		<p style="margin:5px 0 0">'.getAdminLang('Your_team_of_castleevents',$orderDetail['userlanguage']).'</p> 
	                             	</td>
	                             </tr>
	                          </table>
	                       </td>
	                    </tr>
	                </table>';
	                
					$this->utility->sendOrderMail($to,$sub,$bodys);


					/*************Admin Mail*********************/
					$to1 = 'andrej@castleevents.com';
					$sub = 'Confirmation: Successful payment';
					//$sub = 'Your booking: Order CE-'.$orderDetail['order_id'];
					//$body= '<p>Dear '.$orderDetail['username'].',</p>';
					$body= '<p>Thank you for you payment.</p>';
					$body.= '<p>Invoice Number: CE-'.$orderDetail['order_id'].'</p><p>Generated on: '.date('Y-m-d',$orderDetail['created_date']).'</p><p>Paid Amount: '.($orderDetail['total_sum']/100).' EUR</p>';
					$body.= '<p>Invoice will be located in your profile settings area, please login at www.castleevents.com.</p>';
					$body.= '<p>We apprechiate your trust very much.</p>';
					$body.= '<p>Please do not hesitate to contact us for any other requests.</p>';
					//$body.= '<p>Best regards,</p><p>Your Castleevents Team </p>';


					$bodys=' <table cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#22222c" width="100%" style="max-width: 600px;">
		                    <tr>
		                       <td>
		                          <table cellspacing="0" cellpadding="0" border="0" width="100%">
		                             <tr>
		                                <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
		                                   <h2>Dear <span style="text-transform:capitalize">'.$orderDetail['username'].'</span> </h2>
		                                </td>
		                             </tr>
		                             <tr>
		                                <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
		                                   '.$body.'
		                                </td>
		                             </tr>
		                             <tr>
		                             	<td align="center" style="font-family: sans-serif; color: rgb(179, 151, 91); padding: 20px 40px; border-top: 1px solid rgb(79, 79, 79); background: rgb(19, 18, 24) none repeat scroll 0px 0px;">
		                             		Best regards <br>
		                             		<p style="margin:5px 0 0">Your Castleevents Team</p> 
		                             	</td>
		                             </tr>
		                          </table>
		                       </td>
		                    </tr>
		                </table>';


						$this->utility->sendCIMail($to1,$sub,$bodys);
					/*************Admin Mail*********************/

				//$this->utility->sendMail($to,$sub,$body);
			}	
			/****************Payment Mail******************/
			$this->utility->setMsg('Order payment status changed to paid','SUCCESS');	
			redirect(base_url().'admin/order');
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/order');
		}
	}
	public function reminder($enc_userID='')
	{
		if($enc_userID!='')
		{
			$orderId=base64_decode($enc_userID);
			$orderDetail = $this->common_model->getAllRow('shop_orders',array('order_id'=>$orderId));
			$cartDetail = $this->common_model->getAllRow('shop_carts',array('id'=>$orderDetail['cart_id']));
			$userDetail = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('user_id'=>$cartDetail['user_id']),array(array('usr_users','usr_users.id = feu_userdetails.user_id')));
			//print_r($cartDetail); die;
			$eventDetail = $this->common_model->getAllRowMultipleJoin('shop_booking_details',array('cart_id'=>$orderDetail['cart_id']),array(array('evt_events','evt_events.id = shop_booking_details.event_id')));
			$title = '';
			$event_id = 0;
			if(count($eventDetail)>0)
			{
				$title = $eventDetail['title'];
				$event_id = $eventDetail['event_id'];
			}
			$instArr = array(
								'order_id'=>$orderId,
								'order_created'=>$orderDetail['created'],
								'remind_date'=>date('Y-m-d'),
								'user_id'=>$userDetail['user_id'],
								'event_id'=>$event_id,
							);
			$this->common_model->insertData('order_to_reminder',$instArr);

			$order_to_reminder = $this->common_model->getAll('order_to_reminder',array('order_id'=>$orderId));
			$to = $userDetail['email'];
			$sub = getAdminLang('Payment_reminder',$userDetail['userlanguage']).' CE-'.$orderDetail['order_id'];
			$this->load->library('Utility');
			if(count($order_to_reminder)>=4)
			{
				$body= '<p>'.getAdminLang('After_reviewing_your_booking_for_our',$userDetail['userlanguage']).' '.$title.' '.getAdminLang('we_havent_found_the_payment',$userDetail['userlanguage']).'. </p>';
				$body.= '<p>'.getAdminLang('We_already_send_you_several_reminders',$userDetail['userlanguage']).'.</p>';
				$body.= '<p>'.getAdminLang('The_booking_for_our_event_was_a_binding_reservation',$userDetail['userlanguage']).':</p>';
				$body.= '<br/><p>'.getAdminLang('If_the_payment_has_been_made_recently',$userDetail['userlanguage']).'.</p>';
				$body.= '<br/><p>'.getAdminLang('Your_Castleevents_Team',$userDetail['userlanguage']).'.</p>';
				$bodys=' <table cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#22222c" width="100%" style="max-width: 600px;">
	                    <tr>
	                       <td>
	                          <table cellspacing="0" cellpadding="0" border="0" width="100%">
	                             <tr>
	                                <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
	                                   <h2>'.getAdminLang('Good_afternoon',$userDetail['userlanguage']).' <span style="text-transform:capitalize">'.$userDetail['username'].'</span> </h2>
	                                </td>
	                             </tr>
	                             <tr>
	                                <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
	                                   '.$body.'
	                                </td>
	                             </tr>
	                          </table>
	                       </td>
	                    </tr>
	                </table>';
			}
			else
			{
				$body= '<p>'.getAdminLang('We_would_like_to_remind_you',$userDetail['userlanguage']).' '.($orderDetail['total_sum']/100).' EUR '.getAdminLang('of_your_order_from',$userDetail['userlanguage']).' '.date('Y-m-d',$orderDetail['created']).' '.getAdminLang('is_still_unpaid_after',$userDetail['userlanguage']).' 7-'.getAdminLang('day_payment_obligation',$userDetail['userlanguage']).'. </p>';
				$body.= '<p>'.getAdminLang('Please_arrange_the_appropriate_payment_within',$userDetail['userlanguage']).' 3-'.getAdminLang('days_or_contact_us_to_make',$userDetail['userlanguage']).'.</p>';
				$body.= '<p><strong>IBAN:</strong> CH810023123110716660E</p>
	                     <p><strong>'.getAdminLang('Clearing',$userDetail['userlanguage']).':</strong> 231</p>
	                     <p><strong>'.getAdminLang('Swift',$userDetail['userlanguage']).':</strong> UBSWCHZH80A</p>
	                     <p><strong>'.getAdminLang('Payment_Reason',$userDetail['userlanguage']).':</strong> '.$orderDetail['order_id_masked'].'</p>
	                     <p><strong>'.getAdminLang('Amount',$userDetail['userlanguage']).':</strong> <span class="total">'.($orderDetail['total_sum']/100).' EUR</span></p>
	                     <p><strong>'.getAdminLang('Bank',$userDetail['userlanguage']).':</strong> UBS, Bahnhofstrasse 1, 5000 Aarau, '.getAdminLang('Switzerland',$userDetail['userlanguage']).'</p>
	                     <p><strong>'.getAdminLang('Recipient',$userDetail['userlanguage']).':</strong> Anexus AG, Industriestrasse 47, 6300 Zug, '.getAdminLang('Switzerland',$userDetail['userlanguage']).'</p>';
				$body.= '<p>'.getAdminLang('If_you_have_any_questions_about_your_order',$userDetail['userlanguage']).':</p>';
				$body.= '<p>'.getAdminLang('Customer_Services_Events',$userDetail['userlanguage']).'</p>';
				$body.= '<p>info@castleevents.com</p>';

				$body.= '<br/><p>'.getAdminLang('If_the_payment_has_been_made_recently',$userDetail['userlanguage']).'.</p>';
				$body.= '<br/><p>'.getAdminLang('Your_Castleevents_Team',$userDetail['userlanguage']).'.</p>';
				$bodys=' <table cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#22222c" width="100%" style="max-width: 600px;">
	                    <tr>
	                       <td>
	                          <table cellspacing="0" cellpadding="0" border="0" width="100%">
	                             <tr>
	                                <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
	                                   <h2>Dear <span style="text-transform:capitalize">'.$userDetail['username'].'</span> </h2>
	                                </td>
	                             </tr>
	                             <tr>
	                                <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
	                                   '.$body.'
	                                </td>
	                             </tr>
	                          </table>
	                       </td>
	                    </tr>
	                </table>';
			}
			//echo $bodys; die;
			$this->utility->sendCIMail($to,$sub,$bodys);
			//$this->utility->sendMail($to,$sub,$body);

			$this->utility->setMsg('Reminder sent successfully','SUCCESS');	
			redirect(base_url().'admin/order');
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/order');
		}
	}
	public function view($enc_userID='')
	{
		if($enc_userID!='')
		{
			$orderId=base64_decode($enc_userID);
			$content_data = array();
			$type = $this->common_model->getAllRowMultipleJoin('shop_orders',array('order_id'=>$orderId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_articles_carts','shop_articles_carts.cart_id = shop_carts.id')));
			$content_data['orderDetails'] = array();
			$content_data['order_to_reminder'] = array();
			if(!empty($type))
			{
				if(($type['event_id']<0 || $type['event_id']=='') && ($type['article_id'] > 5 || $type['article_id'] == ''))
				{
					$content_data['orderDetails'] = $this->common_model->getAllMultipleJoin('shop_orders',array('order_id'=>$orderId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('event_features','event_features.id = shop_booking_details.feature_id'),array('feu_userdetails','feu_userdetails.user_id = shop_carts.user_id')),'','shop_orders.*,feu_userdetails.username,feu_userdetails.user_id,shop_booking_details.*,shop_booking_details.price as base_price,event_features.id as fea_id, event_features.base_price as fea_base_price') ;
					$content_data['order_to_reminder'] = $this->common_model->getAllRow('order_to_reminder',array('order_id'=>$orderId),'','remind_date DESC','count(*) as total,remind_date');
				}
				else
				{
					$content_data['orderDetails'] = $this->common_model->getAllMultipleJoin('shop_orders',array('order_id'=>$orderId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_articles_carts','shop_articles_carts.cart_id = shop_carts.id'),array('shop_articles','shop_articles.id = shop_articles_carts.article_id'),array('feu_userdetails','feu_userdetails.user_id = shop_carts.user_id')),'','shop_orders.*,shop_articles.name,feu_userdetails.username,feu_userdetails.user_id,shop_articles_carts.quantity,shop_articles_carts.event_id,shop_articles_carts.article_id,shop_articles.base_price,shop_articles.alias') ;	
				}
				
			}
			$content_data['orderDetails'][0]['drinking_package'] = "";
			$content_data['orderDetails'][0]['cape'] = "";
			$content_data['orderDetails'][0]['checkin_amount'] = "";
			$content_data['orderDetails'][0]['checkin_trasaction_id'] = "";
			$content_data['orderDetails'][0]['checkin_date'] = "";
			$content_data['orderDetails'][0]['drink_price'] = "";
			$content_data['orderDetails'][0]['cape_price'] = "";
			$content_data['orderDetails'][0]['guest_id'] = "";
			$content_data['orderDetails'][0]['additional'] = "";
			if($content_data['orderDetails']) {
				$event_guest = $this->common_model->getAllRow('event_guest',array('order_id'=>$content_data['orderDetails'][0]['order_id']),'','id desc');
				if($event_guest){
					if($event_guest['drinking_package']==1){
						$content_data['orderDetails'][0]['drinking_package'] = 'Basic';
					} else {
						$content_data['orderDetails'][0]['drinking_package'] = 'Premium';
					}
					$content_data['orderDetails'][0]['cape'] = $event_guest['cape'];
					$content_data['orderDetails'][0]['checkin_amount'] = $event_guest['summury'];
					$content_data['orderDetails'][0]['checkin_trasaction_id'] = $event_guest['trasaction_id'];
					$content_data['orderDetails'][0]['checkin_date'] = $event_guest['confirmed'];
					$content_data['orderDetails'][0]['drink_price'] = $event_guest['drink_price'];
					$content_data['orderDetails'][0]['cape_price'] = $event_guest['cape_price'];
					$content_data['orderDetails'][0]['guest_id'] = $event_guest['id'];
					$content_data['orderDetails'][0]['additional'] = $event_guest['additional'];
				}
			}

			$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
			$data['content'] = $this->load->view('admin/orders/view', $content_data, TRUE);
			$this->load->view('admin/layout', $data);
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/order');
		}
	}
	public function shop_articles(){
		$content_data = array();
		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$content_data['shop_articles'] = $this->common_model->getAll('shop_articles',array('id >'=>3,'id <'=>6),'','id DESC') ;
		$content_data['shop_new_articles'] = $this->common_model->getAll('shop_new_articles','','','id ASC') ;
		$data['content'] = $this->load->view('admin/shop_articles/list', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	public function shop_article_delete($enc_userID='')
	{
		if($enc_userID!='')
		{
			$shop_articleId=base64_decode($enc_userID);
			$this->common_model->deleteData('shop_articles',array('id'=>$shop_articleId));
			$this->utility->setMsg('Shop Article deleted','SUCCESS');	
			redirect(base_url().'admin/order/shop_articles');
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/order/shop_articles');
		}
	}
	public function shop_article_edit($enc_userID='')
	{
		if($enc_userID!='')
		{
			$shop_articleId=base64_decode($enc_userID);
			if($this->input->post())
			{
				$name=$this->utility->info_cleanQuery($this->input->post('name'));
				$language=$this->utility->info_cleanQuery($this->input->post('language'));
				$content=$this->utility->info_cleanQuery($this->input->post('content'));
				$base_price=$this->utility->info_cleanQuery($this->input->post('base_price'));
				$reoccuring=$this->utility->info_cleanQuery($this->input->post('reoccuring'));
				if($shop_articleId==1 || $shop_articleId==2){
					$archDetails_con=array(
								'name'=>$name,
								//'alias'=>str_replace(' ','-',trim($name)),
								'base_price'=>$base_price
						);
					$this->common_model->UpdateData('shop_new_articles',$archDetails_con,array('id'=>$shop_articleId));
				} else {
					$archDetails_con=array(
								'name'=>$name,
								//'alias'=>str_replace(' ','-',trim($name)),
								'language_id'=>$language,
								'description'=>$content,
								'base_price'=>$base_price,
								'reoccuring'=>$reoccuring
						);
					$this->common_model->UpdateData('shop_articles',$archDetails_con,array('id'=>$shop_articleId));
				}
				

				$this->utility->setMsg('Shop Article details updated','SUCCESS');	
				redirect(base_url().'admin/order/shop_article_edit/'.$enc_userID);
			}

			$content_data = array();
			if($shop_articleId==1 || $shop_articleId==2){
				$content_data['shop_articlesDetails'] = $this->common_model->getAllRow('shop_new_articles',array('id'=>$shop_articleId)) ;
			} else {
				$content_data['shop_articlesDetails'] = $this->common_model->getAllRow('shop_articles',array('id'=>$shop_articleId)) ;
			}
			$content_data['languages'] = $this->common_model->getAll('sys_languages');
			$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
			$data['content'] = $this->load->view('admin/shop_articles/edit', $content_data, TRUE);
			$this->load->view('admin/layout', $data);
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/order/shop_articles');
		}
	}
	public function shop_article_add()
	{
		if($this->input->post())
		{
			$name=$this->utility->info_cleanQuery($this->input->post('name'));
			$language=$this->utility->info_cleanQuery($this->input->post('language'));
			$content=$this->utility->info_cleanQuery($this->input->post('content'));
			$base_price=$this->utility->info_cleanQuery($this->input->post('base_price'));
			$reoccuring=$this->utility->info_cleanQuery($this->input->post('reoccuring'));
			
			$archDetails_con=array(
						'name'=>$name,
						'created'=>time(),
						'alias'=>str_replace(' ','-',trim($name)),
						'language_id'=>$language,
						'description'=>$content,
						'base_price'=>$base_price,
						'reoccuring'=>$reoccuring
				);
			$this->common_model->insertData('shop_articles',$archDetails_con);

			$this->utility->setMsg('Shop Article details added','SUCCESS');	
			redirect(base_url().'admin/order/shop_articles/');
		}

		$content_data = array();
		$content_data['languages'] = $this->common_model->getAll('sys_languages');
		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$data['content'] = $this->load->view('admin/shop_articles/add', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
		
	}
	public function refund($enc_userID='')
	{
		if($enc_userID!='')
		{
			$orderId=base64_decode($enc_userID);
			$orderData = $this->common_model->getAllRow('shop_orders',array('order_id'=>$orderId));
			//$orderData['total_sum'] = 252471;
			/*********TEST*************/
	        /*$CustomerId = 246934; 
	        $TerminalId = 17951970; 
	        $username = 'API_246934_23183450';
	        $password = 'JsonApiPwd1_a8EpfvCy';*/
	        /*********TEST*************/

	        /*********LIVE*************/
	        $CustomerId = 403547;
	        $TerminalId = 17799239; 
	        $username = 'API_403547_78643204';
	        $password = 'JsonApiPwdAnexus1_a8EpfvCy';   
	        /*********LIVE*************/

	        /***********************Create Transaction Direct********************/
	            $JSONObj  = '{
				  "RequestHeader": {
				    "SpecVersion": "1.10",
				    "CustomerId": "'.$CustomerId.'",
	                "RequestId": "aScdFewDSRFrfas2wsad3",
				    "RetryIndicator": 0
				  },
				  "Refund": {
				    "Amount": {
				      "Value": "'.(int)$orderData['total_sum'].'",
				      "CurrencyCode": "EUR"
				    }
				  },
				  "CaptureReference": {
				    "CaptureId": "'.$orderData['trn_id'].'"
				  }
				}';
				//echo $JSONObj;die;
	            //$url = 'https://test.saferpay.com/api/Payment/v1/Transaction/Refund';
	            $url = 'https://www.saferpay.com/api/Payment/v1/Transaction/Refund';
	            
	            $JSONObj = json_decode($JSONObj);
	            $curl = curl_init($url);
	            curl_setopt($curl, CURLOPT_HEADER, false);
	            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	            curl_setopt($curl, CURLOPT_HTTPHEADER,array("Content-type: application/json"));
	            curl_setopt($curl, CURLOPT_POST, true);
	            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($JSONObj));
	            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
	            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
	            curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
	            $jsonResponse = curl_exec($curl);
	            $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
	            if ( $status != 200 ) {
	                if($status == 400) {
	                    $fail_reason = 'Validation error';
	                } elseif($status == 401) {
	                    $fail_reason = 'Authentication of the request failed';
	                } elseif($status == 402) {
	                    $fail_reason = 'Requested action failed';
	                } elseif($status == 403) {
	                    $fail_reason = 'Access denied';
	                } elseif($status == 406) {
	                    $fail_reason = 'Not acceptable (wrong accept header)';
	                } elseif($status == 415) {
	                    $fail_reason = 'Unsupported media type (wrong content-type header)';
	                } elseif($status == 500) {
	                    $fail_reason = 'Internal error';
	                }
	                $errorresponse = json_decode($jsonResponse, true);
	                if($errorresponse)
	                {
	                    if($errorresponse['ProcessorMessage'])
	                    {
	                        $fail_reason = $errorresponse['ProcessorMessage'];
	                    }
	                }
	                $this->utility->setMsg($fail_reason,'ERROR');
	                redirect(base_url().'admin/order/view/'.$enc_userID);
	            }
	            curl_close($curl);
	            $refundresponse = json_decode($jsonResponse, true);
	            
	            //echo "<pre>";
	            //print_r($refundresponse);die;
	        /***********************Create Transaction Direct********************/

	        /***********************Create Capture Direct********************/
	            $JSONObj  = '{
	              "RequestHeader": {
	                "SpecVersion": "1.10",
	                "CustomerId": "'.$CustomerId.'",
	                "RequestId": "aScdFewDSRFrfas2wsad3",
	                "RetryIndicator": 0
	              },
	              "TransactionReference": {
	                "TransactionId": "'.$refundresponse['Transaction']['Id'].'"
	              }
	            }';
	            //echo $JSONObj;die;
	            //$url = 'https://test.saferpay.com/api/Payment/v1/Transaction/Capture';
	            $url = 'https://www.saferpay.com/api/Payment/v1/Transaction/Capture';
	            
	            $JSONObj = json_decode($JSONObj);
	            $curl = curl_init($url);
	            curl_setopt($curl, CURLOPT_HEADER, false);
	            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	            curl_setopt($curl, CURLOPT_HTTPHEADER,array("Content-type: application/json"));
	            curl_setopt($curl, CURLOPT_POST, true);
	            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($JSONObj));
	            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
	            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
	            curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
	            $jsonResponse = curl_exec($curl);
	            $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
	            if ( $status != 200 ) {
	                if($status == 400) {
	                    $fail_reason = 'Validation error';
	                } elseif($status == 401) {
	                    $fail_reason = 'Authentication of the request failed';
	                } elseif($status == 402) {
	                    $fail_reason = 'Requested action failed';
	                } elseif($status == 403) {
	                    $fail_reason = 'Access denied';
	                } elseif($status == 406) {
	                    $fail_reason = 'Not acceptable (wrong accept header)';
	                } elseif($status == 415) {
	                    $fail_reason = 'Unsupported media type (wrong content-type header)';
	                } elseif($status == 500) {
	                    $fail_reason = 'Internal error';
	                }
	                $errorresponse = json_decode($jsonResponse, true);
	                if($errorresponse)
	                {
	                    if($errorresponse['ProcessorMessage'])
	                    {
	                        $fail_reason = $errorresponse['ProcessorMessage'];
	                    }
	                }
	                $this->utility->setMsg($fail_reason,'ERROR');
	                redirect(base_url().'admin/order/view/'.$enc_userID);
	            }
	        	$response = json_decode($jsonResponse, true);
            	if($response)
				{
					$this->common_model->UpdateData('shop_orders',array('refund_trn_id'=>$refundresponse['Transaction']['Id'],'refund_date'=>date('Y-m-d'),'cancelled'=>1, 'payed'=>0),array('order_id'=>$orderId));
					$this->common_model->UpdateData('shop_articles_carts',array('cancelled'=>1),array('cart_id'=>$orderData['cart_id']));
					$orderDetail = $this->common_model->getAllRowMultipleJoin('shop_orders',array('order_id'=>$orderId),array(array('usr_users','usr_users.email = shop_orders.invoiceAddress'),array('feu_userdetails','feu_userdetails.user_id = usr_users.id')));
					/****************Payment Mail******************/
					if(!empty($orderDetail))
					{
						//$to = 'sayan@digitalaptech.com';
						$to = $orderDetail['email'];
						$sub = getAdminLang('Membership_Order_Refund',$orderDetail['userlanguage']);
						$body= '<p>'.getAdminLang('Please_apologize_the_confusion',$orderDetail['userlanguage']).'</p>';
						$body.= '<p>'.getAdminLang('Thank_you_very_much_for',$orderDetail['userlanguage']).'</p>';
						$body.= '<p>'.getAdminLang('Please_let_us_know_if',$orderDetail['userlanguage']).'</p>';
						
						
						$bodys=' <table cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#22222c" width="100%" style="max-width: 600px;">
			                    <tr>
			                       <td>
			                          <table cellspacing="0" cellpadding="0" border="0" width="100%">
			                             <tr>
			                                <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
			                                   <h2>Dear <span style="text-transform:capitalize">'.$orderDetail['username'].'</span> </h2>
			                                </td>
			                             </tr>
			                             <tr>
			                                <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
			                                   '.$body.'
			                                </td>
			                             </tr>
			                             <tr>
			                             	<td align="center" style="font-family: sans-serif; color: rgb(179, 151, 91); padding: 20px 40px; border-top: 1px solid rgb(79, 79, 79); background: rgb(19, 18, 24) none repeat scroll 0px 0px;">
			                             		'.getAdminLang('Best_regards',$orderDetail['userlanguage']).' <br>
			                             		<p style="margin:5px 0 0">'.getAdminLang('Your_team_of_castleevents',$orderDetail['userlanguage']).'</p> 
			                             	</td>
			                             </tr>
			                          </table>
			                       </td>
			                    </tr>
			                </table>';


						$this->utility->sendCIMail($to,$sub,$bodys);
					}
					$this->utility->setMsg('Order refunded','SUCCESS');	
				}
				redirect(base_url().'admin/order/view/'.$enc_userID);
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/order/view/'.$enc_userID);
		}
	}
	public function upcoming_membership()
	{
		$content_data = array();
		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;

		
		if($this->input->post())
		{
			$qry = $this->db->query('select * from (select * from (SELECT  shop_orders.time,shop_articles_carts.article_id,shop_orders.created,shop_orders.cart_id,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus`,shop_orders.total_base, shop_orders.total_sum,shop_orders.payment_method_id,shop_orders.order_id_masked FROM `shop_articles` INNER JOIN `shop_articles_carts` ON `shop_articles_carts`.`article_id` = `shop_articles`.`id` INNER JOIN `shop_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` INNER JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` INNER JOIN `shop_orders` ON `shop_orders`.`cart_id` = `shop_carts`.`id` WHERE ( `shop_articles_carts`.`cancelled` != 1 OR `shop_articles_carts`.`cancelled` IS NULL ) AND `shop_orders`.`payed` = 1 ORDER BY `usr_users`.`id` DESC, `shop_carts`.`created` DESC) as a GROUP BY a.user_id ORDER BY a.user_id DESC) as b where case when time = 182 then (created >= '.(strtotime($this->input->post('fromDate'))-(182*86400)).' AND created <= '.(strtotime($this->input->post('toDate'))-(182*86400)).') when time = 365 then (created >= '.(strtotime($this->input->post('fromDate'))-(365*86400)).' AND created <='.(strtotime($this->input->post('toDate'))-(365*86400)).') END AND article_id in (5,4) order by b.created ASC');
        
			$content_data['orders'] = $qry->result_array();//print_r($content_data['orders']); die;
		}
		else
		{
			$qry = $this->db->query('select * from (select * from (SELECT shop_orders.time,shop_articles_carts.article_id,shop_orders.created,shop_orders.cart_id,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus`,shop_orders.total_base, shop_orders.total_sum,shop_orders.payment_method_id,shop_orders.order_id_masked FROM `shop_articles` INNER JOIN `shop_articles_carts` ON `shop_articles_carts`.`article_id` = `shop_articles`.`id` INNER JOIN `shop_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` INNER JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` INNER JOIN `shop_orders` ON `shop_orders`.`cart_id` = `shop_carts`.`id` WHERE ( `shop_articles_carts`.`cancelled` != 1 OR `shop_articles_carts`.`cancelled` IS NULL ) AND `shop_orders`.`payed` = 1 ORDER BY `usr_users`.`id` DESC, `shop_carts`.`created` DESC) as a GROUP BY a.user_id ORDER BY a.user_id DESC) as b where case when time = 365 then b.created >('.time().' - (365 * 86400)) when time = 182 then b.created >('.time().' - (182 * 86400)) end AND article_id in (5,4) AND created > ('.time().' - (365 * 86400)) order by b.created ASC');
        
			$content_data['orders'] = $qry->result_array();//print_r($content_data['orders']); die;
		}
		//echo $this->db->last_query(); die;
		$data['content'] = $this->load->view('admin/orders/upcominglist', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
		
	}
	public function add_payment_date()
	{
		$order_id = $this->input->post('payment_order_id');
		$payment_date = $this->input->post('payment_date');
		$uri = $this->input->post('uri');
		if($order_id!='' && $payment_date!='')
		{
			$this->common_model->UpdateData('shop_orders',array('payment_date'=>$payment_date),array('order_id'=>$order_id));
		}
		redirect(base_url().str_replace('-', '/', $uri));
	}
	public function all_delete()
	{
		if($this->input->post())
		{
			$ids = $this->input->post('checkbox');
			if($ids)
			{
				foreach ($ids as $key => $value) {
					if($value>0)
					{
						$orderId=$value;
						$this->common_model->deleteData('shop_orders',array('order_id'=>$orderId));
					}
				}
			}
			$this->utility->setMsg('Order deleted','SUCCESS');	
			redirect(base_url().'admin/order');
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/order');
		}
		die;
	}
	public function download($enc_userID='')
	{
		if($enc_userID!='')
		{
			$orderId=base64_decode($enc_userID);
			$type = $this->common_model->getAllRowMultipleJoin('shop_orders',array('order_id'=>$orderId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_articles_carts','shop_articles_carts.cart_id = shop_carts.id')));
			$orderDetails = array();
			if(!empty($type))
			{
				if(($type['event_id']<0 || $type['event_id']=='') && ($type['article_id'] > 5 || $type['article_id'] == ''))
				{
					$orderDetails = $this->common_model->getAllMultipleJoin('shop_orders',array('order_id'=>$orderId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('event_features','event_features.id = shop_booking_details.feature_id'),array('feu_userdetails','feu_userdetails.user_id = shop_carts.user_id')),'','shop_orders.*,feu_userdetails.username,feu_userdetails.user_id,feu_userdetails.accept_date,shop_booking_details.*,shop_booking_details.price as base_price,event_features.id as fea_id,event_features.base_price as fea_base_price,event_features.type as feature_type, shop_orders.created as created') ;
				}
				else
				{
					$orderDetails = $this->common_model->getAllMultipleJoin('shop_orders',array('order_id'=>$orderId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_articles_carts','shop_articles_carts.cart_id = shop_carts.id'),array('shop_articles','shop_articles.id = shop_articles_carts.article_id'),array('feu_userdetails','feu_userdetails.user_id = shop_carts.user_id')),'','shop_orders.*,shop_articles.name,feu_userdetails.username,feu_userdetails.user_id,feu_userdetails.accept_date,shop_articles_carts.quantity,shop_articles_carts.event_id,shop_articles.base_price,shop_articles.alias') ;	
				}
			}
			if($orderDetails)
			{ 
				$eventData = getValue('evt_events',array('id'=>$orderDetails[0]['event_id']));  
	            $title = '';
	            $date = '';
	            $book = '';
	            $location = '';
	            $userlastpaymnt = $this->common_model->getAllRowMultipleJoin('shop_orders',array('user_id'=>$orderDetails[0]['user_id'], 'payed'=>1, 'is_renewed' => 0, 'is_booking'=>0),array(array('shop_carts','shop_carts.id = shop_orders.cart_id')),'shop_orders.created desc') ;	
	            $renewal_accept_date = '';
	            if($userlastpaymnt){
	            	$renewal_accept_date = $userlastpaymnt['created'];
	            }
	            if(!empty($eventData)){ 
	            	$event_location = $this->common_model->getAllRow('loc_events_locations',array('event_id'=>$eventData['id']),array('loc_locations','loc_locations.id = loc_events_locations.location_id'));
	            	if($event_location)
	            	{
	            		$location = ', '.$event_location['name'];
	            	}
	            	$title = $eventData['title']; 
	            	$date = date('d-m-Y',$eventData['time_from']).''.$location;
	            	$book='Booking';
	            } 
	            elseif($orderDetails[0]['name']!=''){ 
	            	$title = ucfirst($orderDetails[0]['alias']).' Membership fee'; 
					if($orderDetails[0]['upgrade_date'] > 0 ){ $cdate = $orderDetails[0]['upgrade_date'];}else{$cdate = $orderDetails[0]['created'];} 
					
	            	$date = date('d-m-Y',$cdate);
	            	if($orderDetails[0]['time']==365)
	            	{
	            		$title .= ' 12 Months from '.$date;
	            	}
	            	else
	            	{
	            		$title .= ' 6 Months from '.$date;
	            	}
	            	$book='Order';
	            }

	            $status = '';
	            if($orderDetails[0]['payed']==1){ 
	            	$status = 'Paid'; 
	            } 
	            elseif($orderDetails[0]['is_renewed']==1){ 
	            	$status = 'Unpaid | Invoice mail sent'; 
	            } else{ 
	            	$status = 'Unpaid';
	            } 
	            $payment_method = '';
	            if($orderDetails[0]['payment_method_id']==13){ 
	            	$payment_method = 'Saferpay'; 
	            } elseif($orderDetails[0]['payment_method_id']==14){ 
	            	$payment_method = 'Credit Card'; 
	            } elseif($orderDetails[0]['payment_method_id']==12){ 
	            	$payment_method = 'Bank Transfer'; 
	            } else{ 
	            	$payment_method = 'Pay By Bank'; 
	            }
				
				$paid_date='';
				if($orderDetails[0]['payment_date']!=''){
					$paid_date = date('d-m-Y',strtotime($orderDetails[0]['payment_date']));					
				}
				$site_address_name = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_name'));
				$site_address_city = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_city'));
				$site_address_country_zip = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_country_zip'));

				$numberDetails = getValue('feu_userdetails',array('user_id'=>$orderDetails[0]['user_id']));
                $userPhones = getValue('usr_phones',array('user_id'=>$orderDetails[0]['user_id']));
                $number = '';
                if($numberDetails['mobile_number'] != '')
                {
                    if(strpos($numberDetails['mobile_number'],'+') === false)
                    {
                      $number = '+'.$numberDetails['mobile_number'];
                    }
                    else
                    {
                      $number = $numberDetails['mobile_number'];
                    }
                }
                elseif($userPhones)
                {
                    if(strpos($userPhones['mobile_number'],'+') === false)
                    {
                      $number = '+'.$userPhones['mobile_number'];
                    }
                    else
                    {
                      $number = $userPhones['mobile_number'];
                    }
                }

	            $html='<!DOCTYPE html>
					<html>
					   <head>
					      <title>invoice</title>
					   </head>
					   <body>
					      <div style="max-width:960px; width:100%; margin:0 auto 0; font-family: sans-serif; padding: 0 50px;">';
					        if($orderDetails[0]['payment_method_id']==13 || $orderDetails[0]['payment_method_id']==14){
						        $html.=' <div style="padding: 15px 0 20px; ">
						          <p style="margin:0;">'.$site_address_name['value'].'</p>
						          <p style="margin:0;">'.$site_address_city['value'].',</p>
						          <p style="margin:0;">'.$site_address_country_zip['value'].'</p>
						          <p style="padding-top: 10px;">UID: CHE-362.535.263</p>
						         </div>';
					     	}
					        $html.=' <h2 style="padding: 10px;border-bottom:1px solid #ccc; display: block;">INVOICE</h2>
					         <table style="padding:0px 10px 0 0px; width: 100%; margin-bottom: 36px;">
					            <tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 0">Order No</td>
					               <td style="padding:10px ;line-height: 0">'.$orderDetails[0]['order_id_masked'].'</td>
					            </tr>';
					            if($date)
					            {
					    $html.='<tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 5px">Date</td>
					               <td style="padding:10px ;line-height: 5px">'.$date.'</td>
					            </tr>';
					            }
					            if($orderDetails[0]['real_name']!='')
					            {
					    $html.='<tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 5px">Real Name</td>
					               <td style="padding:10px ;line-height: 5px">'.$orderDetails[0]['real_name'].'</td>
					            </tr>';
					            }
					    $html.=' <tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 5px">Username</td>
					               <td style="padding:10px ;line-height: 5px">'.(($orderDetails[0]['username']) ? $orderDetails[0]['username'] : ((getUserDataByEmail($orderDetails[0]['invoiceAddress'])) ? getUserDataByEmail($orderDetails[0]['invoiceAddress']) : '')).'</td>
					            </tr>';
					            if($number){
					    $html.='<tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 5px">Mobile Number</td>
					               <td style="padding:10px ;line-height: 5px">'.$number.'</td>
					            </tr>';
					        	}
					            if($this->session->userdata('admin_id')=='19624' || $this->session->userdata('admin_id')=='25267'){
					    $html.='<tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 5px">Email</td>
					               <td style="padding:10px ;line-height: 5px">'.$orderDetails[0]['invoiceAddress'].'</td>
					            </tr>';
					        	}
					    $html.='<tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 5px">'.$book.'</td>
					               <td style="padding:10px ;line-height: 5px">'.date('d-m-Y H:i:s',$orderDetails[0]['created']).'</td>
					            </tr>';
					            if($orderDetails[0]['is_renewed'] == 1 && $renewal_accept_date > 0){
					    $html.='<tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 5px">Accept Terms & Conditions</td>
					               <td style="padding:10px ;line-height: 5px">'.date('d-m-Y H:i:s',($renewal_accept_date)).'</td>
					            </tr>
					            ';
					        	} elseif($orderDetails[0]['is_renewed'] == 0 && $orderDetails[0]['terms_accept_date'] > 0){
					    $html.='<tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 5px">Accept Terms & Conditions</td>
					               <td style="padding:10px ;line-height: 5px">'.date('d-m-Y H:i:s',($orderDetails[0]['terms_accept_date'])).'</td>
					            </tr>
					            ';
					        	} else {
					    $html.='<tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 5px">Accept Terms & Conditions</td>
					               <td style="padding:10px ;line-height: 5px">'.date('d-m-Y H:i:s',($orderDetails[0]['created']-48)).'</td>
					            </tr>
					            ';
					        	}
					    $html.='<tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 5px">IPAddress</td>
					               <td style="padding:10px ;line-height: 5px">'.$orderDetails[0]['ip_address'].'</td>
					            </tr>
					            <tr>
					               <td  style="padding:10px ; font-weight: bold; width:38%;line-height: 5px">payment status</td>
					               <td  style="padding:10px ;line-height: 5px">'.$status.'</td>
					            </tr>';
								
								if($paid_date!=''){
								$html.='<tr>
					               <td  style="padding:10px ; font-weight: bold; width:38%;line-height: 5px">payment date</td>
					               <td  style="padding:10px ;line-height: 5px">'.$paid_date.'</td>
					            </tr>';
								}
					           $html.=' <tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 5px"> Payment Method </td>
					               <td style="padding:10px ;line-height: 5px">'.$payment_method.'</td>
					            </tr>
					         </table>
					         <div style="float: left;">

					         	<div style="width: 100%; float: left; ">         	
					 			   <div style="padding:10px ; font-weight: bold; width: 35%; height: 19px; line-height: 19px; float: left;">Description</div>
					               <div style="padding:10px ; font-weight: bold; width: 25%; float: left; height: 19px; line-height: 19px;">Number</div>
					               <div style=" font-weight: bold; padding:10px ; width: 30%; float: left; height: 19px; line-height: 19px;">Price</div>
					         	</div>';
					            if(!empty($orderDetails)){ 
                      				foreach ($orderDetails as $value) {
				                        if($value['price'] > 0)
				                        {
				                			$html .= '<div style="width: 100%; float: left;">';
							                $name = array(); 
								            if ($value['is_booking']==1)
								            {
								                $name = getValue('event_features_lang_values',array('event_feature_id'=>$value['fea_id'],'lang_id'=>2));
								                $dates = explode(',', $value['fea_id']);
								                $date='';
								                
								                if(!empty($dates))
								                {
								                  foreach ($dates as $dateVal) {
								                    $val = getValue('event_features',array('id'=>$value['fea_id']));
								                    $date .= date('d.m.Y',$val['date']).',';
								                  }
								                }
								                
								                if(!empty($name))
								                {
								                  	$value['name'] = $name['title'];
								                }
								                else
								                {
								                  if($value['feature_id']!='')
								                  {
								                    $extra_ids = explode(',', $value['feature_id']);
								                    if(count($extra_ids)>0)
								                    {
								                      $date = '';
								                      foreach ($extra_ids as $key => $res) {
								                        $result = getValue('event_features',array('id'=>$res));
								                        $date .= date('d.m.Y',$result['date']).',';
								                      }
								                      $value['quantity'] = count($extra_ids);
								                    }
								                  }
								                  $value['name'] = 'Extra Nights ('.rtrim($date,',').')';
								                }
								            }
								            $eventData = getValue('evt_events',array('id'=>$value['event_id']));
								            
								            $html .= '<div style="padding:10px ; font-weight: bold;  width: 35%; float: left; height: 21px; line-height: 5px;">';
								            if($value['is_booking']==1){ 
								            	if($value['feature_type']==1)
								            	{
								            		$html .= 'Event services';
								            	}
								            	elseif($value['feature_type']==2)
								            	{
								            		$html .= 'Room ('.$name['title'].')';
								            	}
								            	elseif($value['feature_type']==3)
								            	{
								            		$html .= 'Extra Night';
								            	}
								            	elseif($value['feature_type']==4)
								            	{
								            		$html .= 'Limousine services';
								            	}
								            } elseif (count($eventData)>0) { 
								            	$html .= $eventData['title']; 
								            } else{ 
								            	$html .= $title; 
								            }
								            $html .= '</div>
								                <div style="padding:10px ; width: 25%; float: left; height: 21px; line-height: 5px;">'.$value['quantity'].'</div>
								                <div style="padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">';
								                	if($value['is_booking']==1 || count($eventData)>0){
						                              	if($value['feature_type']==1){ 
						                                	if($orderDetails[0]['user_discount']>0){
							                                  $html .=  number_format($value['price'], 2,',', '.'); 
							                                } elseif($value['fea_base_price']>0){
							                                  $html .=  number_format($value['price']+($orderDetails[0]['discount']/100), 2,',', '.'); 
							                                } else {
							                                  $html .=  number_format(($value['price']+($orderDetails[0]['discount']/100)), 2,',', '.'); 
							                                }
						                              	} else if($value['feature_type']==2 && $orderDetails[0]['room_discount']>0){ 
						                                	if($orderDetails[0]['room_discount']>0){
							                                  $html .=  number_format($value['price']+($orderDetails[0]['room_discount']/100), 2,',', '.'); 
							                                } else {
							                                  $html .=  number_format(($value['price']), 2,',', '.'); 
							                                } 
						                              	} 
						                              	else { 
						                                	$html .= number_format($value['price'], 2,',', '.'); 
						                              	} 
						                            } 
						                            else{
						                              	$html .= number_format($orderDetails[0]['total_base']/100, 2,',', '.'); 
						                            }
								            $html .= ' &euro;</div>';
								            if($value['feature_type']==1){ 
						                      	if($orderDetails[0]['discount']>0){ 
						                      		$total_discounts = 'Discount ';
                            						$total_discount = '';
						                            if($orderDetails[0]['party_discount']>0){ 
						                                $total_discount .= '(Early bird-'.$orderDetails[0]['party_discount'].'%)';
						                            } 
						                            if($orderDetails[0]['user_discount']>0){ 
						                                $total_discount .= ', (User-'.$orderDetails[0]['user_discount'].'%)';
						                            }
						                            if($orderDetails[0]['party_discount']==0 && $orderDetails[0]['user_discount']==0){
						                              $total_discount .= '('.round($orderDetails[0]['discount']/$value['price']).'%)';
						                            }  
						                            
								                    $html .= '</div>
								                    	<div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height:5px;">&nbsp;</div>
										                <div style="padding:10px ; width: 25%; float: left; height: 21px; line-height: 15px;font-weight: bold;">'.$total_discounts.trim($total_discount,',').'</div>
										                <div style="padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">'.number_format($orderDetails[0]['discount']/100, 2,',', '.').'&euro; </div>
										            </div>';
								                } 
							                    $html .='<div style="width: 100%; float: left;">         	
									 			   <div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
									               <div style="padding:10px ;     width: 25%; float: left; height: 21px; line-height: 5px; font-weight: bold;">Sub total:</div>
									               <div style="     border-top: 0; padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">';
									               	if($orderDetails[0]['user_discount']>0){ 
									            $html .= number_format($value['price']- ($orderDetails[0]['discount']/100), 2,',', '.'); 
									               	} elseif($value['fea_base_price']>0){ 
									            $html .= number_format($value['price'], 2,',', '.'); 
									               	} else { 
									            $html .= number_format($value['price'], 2,',', '.'); 
									               	}
									            $html .=' &euro; </div>
			         								</div>';
						                    } 
						                    if($value['feature_type']==2){ 
						                      	if($orderDetails[0]['room_discount']>0){ 
						                      		$total_discounts = 'Discount ';
                            						$total_discount = '';
						                            if($orderDetails[0]['user_discount']>0){ 
						                                $total_discount .= '(User-'.$orderDetails[0]['user_discount'].'%)';
						                            } 
						                            
								                    $html .= '</div>
								                    	<div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height:5px;">&nbsp;</div>
										                <div style="padding:10px ; width: 25%; float: left; height: 21px; line-height: 15px;font-weight: bold;">'.$total_discounts.trim($total_discount,',').'</div>
										                <div style="padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">'.number_format($orderDetails[0]['room_discount']/100, 2,',', '.').'&euro; </div>
										            </div>';
								                 
								                    $html .='<div style="width: 100%; float: left;">         	
										 			   <div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
										               <div style="padding:10px ;     width: 25%; float: left; height: 21px; line-height: 5px; font-weight: bold;">Sub total:</div>
										               <div style="     border-top: 0; padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">';
										               	if($value['fea_base_price']>0){ 
										            $html .= number_format($value['fea_base_price']-($orderDetails[0]['room_discount']/100), 2,',', '.'); 
										               	} else { 
										            $html .= number_format($value['base_price'], 2,',', '.'); 
										               	}
										            $html .=' &euro; </div>
				         								</div>';
			         							}
						                    } 
								        }
								        else
								        {
								        	$html .= '<div style="padding:10px ;     font-weight: bold;  width: 35%; float: left; height: 21px; line-height: 15px;">';
								            $html .= $title; 
								            $html .= '</div>
								                <div style="padding:10px ; width: 25%; float: left; height: 21px; line-height: 5px;">1</div>
								                <div style="padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">'.number_format($orderDetails[0]['total_base']/100, 2,',', '.').' &euro;</div>
								            ';
								        } 
								    } 
								}
								if($orderDetails[0]['is_booking']==0){
						            $html .='<div style="width: 100%; float: left; ">         	
							 			   <div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
							               <div style="padding:10px ;     width: 25%; float: left; height: 21px; line-height: 5px; font-weight: bold;">Sub total:</div>
							               <div style="     border-top: 0; padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">'.number_format($orderDetails[0]['total_base']/100, 2,',', '.').' &euro;</div>
	         								</div>';
         						}
         						if($orderDetails[0]['vat']>0)
         						{		
						            $html .='<div style="width: 100%; float: left;">         	
							 			   <div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
							               <div style="padding:10px ;      width: 25%; float: left; height: 21px; line-height: 5px; font-weight: bold;">Vat:</div>
							               <div style="     border-top: 0;   padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">'.number_format($orderDetails[0]['vat']/100, 2,',', '.').' &euro;</div>
	         								</div>';
         						}	
         						/*Reservation*/	
         						$reservation_total = '';	
         						if($orderDetails[0]['is_recomended'] == 1) {
					        		$setting = getValue('sys_settings', array('key'=>'reservation_fee'));
									$reservation_charge = $setting ? $setting['value'] : 0;
									$reservation_total = ' (40% Deposit)';
								}	
         						$html .='<div style="width: 100%; float: left;">         	
						 			   <div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
						               <div style="padding:10px ;    width: 25%; float: left; height: 21px; line-height: 5px; font-weight: bold;">Payment Fee:</div>
						               <div style="     border-top: 0; padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">'.number_format($orderDetails[0]['payment_fee']/100, 2,',', '.').' &euro;</div>
         								</div>
         								<div style="width: 100%; float: left;">         	
						 			   <div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
						               <div style="padding:10px ;    width: 25%; float: left; height: 21px; line-height: 5px; font-weight: bold;">Grand Total'.$reservation_total.':</div>
						               <div style="     border-top: 0; padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">'.number_format($orderDetails[0]['total_sum']/100, 2,',', '.').' &euro;</div>
         								</div></div>

         								<div style="width: 100%; float: left;">         	
						 			   <div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
						               <div style="padding:10px ;    width: 25%; float: left; height: 21px; line-height: 5px; font-weight: bold;">&nbsp;</div>
						               <div style="     border-top: 0; padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
         								</div></div></div></div></div></div>';
         					/*Reservation*/	
     						if($orderDetails[0]['is_recomended'] == 1) {
				        		$html .= '<div style="width: 100%; float: left;">         	
					 			   <div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
					               <div style="padding:10px ;    width: 25%; float: left; height: 21px; line-height: 5px; font-weight: bold;">Rest payment at arrival:</div>
					               <div style="     border-top: 0; padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">'.number_format($orderDetails[0]['reservation_rest_amount']/100, 2,',', '.').' &euro;</div>
     								</div></div>';
							}
         					if($orderDetails[0]['payment_method_id']==12 || $orderDetails[0]['payment_method_id']==15){
         						$html .='<div style="clear: both; width: 100%; margin:0 auto 0; max-width: 960px; padding: 0 50px;"><h2 style="padding: 5px 10px 5px 10px;border-bottom:1px solid #ccc; display: block;">RECIPIENT</h2>
         								<table style="padding:0px 10px 0 0px; width: 100%;">
         									<tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0;">'.$site_address_name['value'].'</td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0;">Bank Details:</td>
								            </tr>
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">'.$site_address_city['value'].'</td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								            </tr>
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">'.$site_address_country_zip['value'].'</td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">UBS, Bahnhofstrasse 61</td>
								            </tr>
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">5000 Aarau, Switzerland</td>
								            </tr>
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								            </tr>
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								            </tr>
								            
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">UID: CHE-362.535.263</td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">IBAN: CH810023123110716660E</td>
								            </tr>
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">Clearing: 231</td>
								            </tr>
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">Swift: UBSWCHZH80A</td>
								            </tr>
								        </table></div>';	
								}									
					    $html .='</div>
					   </body>
					</html>';
			}		
            //echo $html;die;
            $pdfFilePath = $orderDetails[0]['order_id_masked'].".pdf";
	        $this->load->library('m_pdf');

	        $this->m_pdf->pdf->useOnlyCoreFonts = true;    // false is default
			$this->m_pdf->pdf->SetTitle("Castleevents Title");
			$this->m_pdf->pdf->SetAuthor("Author");
			$this->m_pdf->pdf->SetDisplayMode('fullpage'); 
			$this->m_pdf->pdf->WriteHTML($html);
			$this->m_pdf->pdf->Output($pdfFilePath, "D");    
	        die;
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/order');
		}
	}

	public function download_for_user($enc_userID='')
	{
		if($enc_userID!='')
		{
			$orderId=base64_decode($enc_userID);
			$type = $this->common_model->getAllRowMultipleJoin('shop_orders',array('order_id'=>$orderId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_articles_carts','shop_articles_carts.cart_id = shop_carts.id')));
			$orderDetails = array();
			if(!empty($type))
			{
				if(($type['event_id']<0 || $type['event_id']=='') && ($type['article_id'] > 5 || $type['article_id'] == ''))
				{
					$orderDetails = $this->common_model->getAllMultipleJoin('shop_orders',array('order_id'=>$orderId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('event_features','event_features.id = shop_booking_details.feature_id'),array('feu_userdetails','feu_userdetails.user_id = shop_carts.user_id')),'','shop_orders.*,feu_userdetails.username,feu_userdetails.user_id,shop_booking_details.*,shop_booking_details.price as base_price,event_features.id as fea_id,event_features.base_price as fea_base_price,event_features.type as feature_type, shop_orders.created as created') ;
				}
				else
				{
					$orderDetails = $this->common_model->getAllMultipleJoin('shop_orders',array('order_id'=>$orderId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_articles_carts','shop_articles_carts.cart_id = shop_carts.id'),array('shop_articles','shop_articles.id = shop_articles_carts.article_id'),array('feu_userdetails','feu_userdetails.user_id = shop_carts.user_id')),'','shop_orders.*,shop_articles.name,feu_userdetails.username,feu_userdetails.user_id,shop_articles_carts.quantity,shop_articles_carts.event_id,shop_articles.base_price,shop_articles.alias') ;	
				}
			}
			if($orderDetails)
			{ 
				$eventData = getValue('evt_events',array('id'=>$orderDetails[0]['event_id']));  
	            $title = '';
	            $date = '';
	            $book = '';
	            $location = '';



	            if(!empty($eventData)){ 
	            	$event_location = $this->common_model->getAllRow('loc_events_locations',array('event_id'=>$eventData['id']),array('loc_locations','loc_locations.id = loc_events_locations.location_id'));
	            	if($event_location)
	            	{
	            		$location = ', '.$event_location['name'];
	            	}
	            	$title = $eventData['title']; 
	            	$date = date('d-m-Y',$eventData['time_from']).''.$location;
	            	$book='Booking';
	            } 
	            elseif($orderDetails[0]['name']!=''){ 
	            	$title = ucfirst($orderDetails[0]['alias']).' Membership fee'; 
					if($orderDetails[0]['upgrade_date'] > 0 ){ $cdate = $orderDetails[0]['upgrade_date'];}else{$cdate = $orderDetails[0]['created'];} 
					
	            	$date = date('d-m-Y',$cdate);
	            	if($orderDetails[0]['time']==365)
	            	{
	            		$title .= ' 12 Months from '.$date;
	            	}
	            	else
	            	{
	            		$title .= ' 6 Months from '.$date;
	            	}
	            	$book='Order';
	            }

	            $status = '';
	            if($orderDetails[0]['payed']==1){ 
	            	$status = 'Paid'; 
	            } 
	            elseif($orderDetails[0]['is_renewed']==1){ 
	            	$status = 'Unpaid | Invoice mail sent'; 
	            } else{ 
	            	$status = 'Unpaid';
	            } 
	            $payment_method = '';
	            if($orderDetails[0]['payment_method_id']==13){ 
	            	$payment_method = 'Saferpay'; 
	            } elseif($orderDetails[0]['payment_method_id']==14){ 
	            	$payment_method = 'Credit Card'; 
	            } elseif($orderDetails[0]['payment_method_id']==12){ 
	            	$payment_method = 'Bank Transfer'; 
	            } else{ 
	            	$payment_method = 'Pay By Bank'; 
	            }
				
				$paid_date='';
				if($orderDetails[0]['payment_date']!=''){
					$paid_date = date('d-m-Y',strtotime($orderDetails[0]['payment_date']));					
				}
				$site_address_name = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_name'));
				$site_address_city = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_city'));
				$site_address_country_zip = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_country_zip'));

				$numberDetails = getValue('feu_userdetails',array('user_id'=>$orderDetails[0]['user_id']));
                $userPhones = getValue('usr_phones',array('user_id'=>$orderDetails[0]['user_id']));
                $number = '';
                if($numberDetails['mobile_number'] != '')
                {
                    if(strpos($numberDetails['mobile_number'],'+') === false)
                    {
                      $number = '+'.$numberDetails['mobile_number'];
                    }
                    else
                    {
                      $number = $numberDetails['mobile_number'];
                    }
                }
                elseif($userPhones)
                {
                    if(strpos($userPhones['mobile_number'],'+') === false)
                    {
                      $number = '+'.$userPhones['mobile_number'];
                    }
                    else
                    {
                      $number = $userPhones['mobile_number'];
                    }
                }

	            $html='<!DOCTYPE html>
					<html>
					   <head>
					      <title>invoice</title>
					   </head>
					   <body>
					      <div style="max-width:960px; width:100%; margin:0 auto 0; font-family: sans-serif; padding: 0 50px;">';
					        if($orderDetails[0]['payment_method_id']==13 || $orderDetails[0]['payment_method_id']==14){
						        $html.=' <div style="padding: 15px 0 20px; ">
						          <p style="margin:0;">'.$site_address_name['value'].'</p>
						          <p style="margin:0;">'.$site_address_city['value'].',</p>
						          <p style="margin:0;">'.$site_address_country_zip['value'].'</p>
						          <p style="padding-top: 10px;">UID: CHE-362.535.263</p>
						         </div>';
					     	}
					        $html.=' <h2 style="padding: 10px;border-bottom:1px solid #ccc; display: block;">INVOICE</h2>
					         <table style="padding:0px 10px 0 0px; width: 100%; margin-bottom: 36px;">
					            <tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 0">Order No</td>
					               <td style="padding:10px ;line-height: 0">'.$orderDetails[0]['order_id_masked'].'</td>
					            </tr>';
					            if($date)
					            {
					    $html.='<tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 5px">Date</td>
					               <td style="padding:10px ;line-height: 5px">'.$date.'</td>
					            </tr>';
					            }
					    $html.=' <tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 5px">Username</td>
					               <td style="padding:10px ;line-height: 5px">'.(($orderDetails[0]['username']) ? $orderDetails[0]['username'] : ((getUserDataByEmail($orderDetails[0]['invoiceAddress'])) ? getUserDataByEmail($orderDetails[0]['invoiceAddress']) : '')).'</td>
					            </tr>
					            <tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 5px">'.$book.'</td>
					               <td style="padding:10px ;line-height: 5px">'.date('d-m-Y H:i:s',$orderDetails[0]['created']).'</td>
					            </tr>
					            <tr>
					               <td  style="padding:10px ; font-weight: bold; width:38%;line-height: 5px">payment status</td>
					               <td  style="padding:10px ;line-height: 5px">'.$status.'</td>
					            </tr>';
								
								if($paid_date!=''){
								$html.='<tr>
					               <td  style="padding:10px ; font-weight: bold; width:38%;line-height: 5px">payment date</td>
					               <td  style="padding:10px ;line-height: 5px">'.$paid_date.'</td>
					            </tr>';
								}
					           $html.=' <tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 5px"> Payment Method </td>
					               <td style="padding:10px ;line-height: 5px">'.$payment_method.'</td>
					            </tr>
					         </table>
					         <div style="float: left;">

					         	<div style="width: 100%; float: left; ">         	
					 			   <div style="padding:10px ; font-weight: bold; width: 35%; height: 19px; line-height: 19px; float: left;">Description</div>
					               <div style="padding:10px ; font-weight: bold; width: 25%; float: left; height: 19px; line-height: 19px;">Number</div>
					               <div style=" font-weight: bold; padding:10px ; width: 30%; float: left; height: 19px; line-height: 19px;">Price</div>
					         	</div>';
					            if(!empty($orderDetails)){ 
                      				foreach ($orderDetails as $value) {
				                        if($value['price'] > 0)
				                        {
				                			$html .= '<div style="width: 100%; float: left;">';
							                $name = array(); 
								            if ($value['is_booking']==1)
								            {
								                $name = getValue('event_features_lang_values',array('event_feature_id'=>$value['fea_id'],'lang_id'=>2));
								                $dates = explode(',', $value['fea_id']);
								                $date='';
								                
								                if(!empty($dates))
								                {
								                  foreach ($dates as $dateVal) {
								                    $val = getValue('event_features',array('id'=>$value['fea_id']));
								                    $date .= date('d.m.Y',$val['date']).',';
								                  }
								                }
								                
								                if(!empty($name))
								                {
								                  	$value['name'] = $name['title'];
								                }
								                else
								                {
								                  if($value['feature_id']!='')
								                  {
								                    $extra_ids = explode(',', $value['feature_id']);
								                    if(count($extra_ids)>0)
								                    {
								                      $date = '';
								                      foreach ($extra_ids as $key => $res) {
								                        $result = getValue('event_features',array('id'=>$res));
								                        $date .= date('d.m.Y',$result['date']).',';
								                      }
								                      $value['quantity'] = count($extra_ids);
								                    }
								                  }
								                  $value['name'] = 'Extra Nights ('.rtrim($date,',').')';
								                }
								            }
								            $eventData = getValue('evt_events',array('id'=>$value['event_id']));
								            
								            $html .= '<div style="padding:10px ; font-weight: bold;  width: 35%; float: left; height: 21px; line-height: 5px;">';
								            if($value['is_booking']==1){ 
								            	if($value['feature_type']==1)
								            	{
								            		$html .= 'Event services';
								            	}
								            	elseif($value['feature_type']==2)
								            	{
								            		$html .= 'Room ('.$name['title'].')';
								            	}
								            	elseif($value['feature_type']==3)
								            	{
								            		$html .= 'Extra Night';
								            	}
								            	elseif($value['feature_type']==4)
								            	{
								            		$html .= 'Limousine services';
								            	}
								            } elseif (count($eventData)>0) { 
								            	$html .= $eventData['title']; 
								            } else{ 
								            	$html .= $title; 
								            }
								            $html .= '</div>
								                <div style="padding:10px ; width: 25%; float: left; height: 21px; line-height: 5px;">'.$value['quantity'].'</div>
								                <div style="padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">';
								                	if($value['is_booking']==1 || count($eventData)>0){
						                              	if($value['feature_type']==1){ 
						                                	if($orderDetails[0]['user_discount']>0){
							                                  $html .=  number_format($value['price'], 2,',', '.'); 
							                                } elseif($value['fea_base_price']>0){
							                                  $html .=  number_format($value['price']+($orderDetails[0]['discount']/100), 2,',', '.'); 
							                                } else {
							                                  $html .=  number_format(($value['price']+($orderDetails[0]['discount']/100)), 2,',', '.'); 
							                                } 
						                              	} else if($value['feature_type']==2 && $orderDetails[0]['room_discount']>0){ 
						                                	if($orderDetails[0]['room_discount']>0){
							                                  $html .=  number_format($value['price']+($orderDetails[0]['room_discount']/100), 2,',', '.'); 
							                                } else {
							                                  $html .=  number_format(($value['price']), 2,',', '.'); 
							                                } 
						                              	} 
						                              	else { 
						                                	$html .= number_format($value['price'], 2,',', '.'); 
						                              	} 
						                            } 
						                            else{
						                              	$html .= number_format($orderDetails[0]['total_base']/100, 2,',', '.'); 
						                            }
								            $html .= ' &euro;</div>';
								            if($value['feature_type']==1){ 
						                      	if($orderDetails[0]['discount']>0){ 
								                    $total_discounts = 'Discount ';
								                    $total_discount = '';
						                            if($orderDetails[0]['party_discount']>0){ 
						                                $total_discount .= '(Early bird-'.$orderDetails[0]['party_discount'].'%)';
						                            } 
						                            if($orderDetails[0]['user_discount']>0){ 
						                                $total_discount .= ', (User-'.$orderDetails[0]['user_discount'].'%)';
						                            }
						                            if($orderDetails[0]['party_discount']==0 && $orderDetails[0]['user_discount']==0){
						                              $total_discount .= '('.round($orderDetails[0]['discount']/$value['price']).'%)';
						                            }  
						                            
								                    $html .= '</div>
								                    	<div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
										                <div style="padding:10px ; width: 25%; float: left; height: 21px; line-height: 15px;font-weight: bold;">'.$total_discounts.trim($total_discount,',').'</div>
										                <div style="padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">'.number_format($orderDetails[0]['discount']/100, 2,',', '.').'&euro; </div>
										            </div>';
								                } 
							                    $html .='<div style="width: 100%; float: left;">         	
									 			   <div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
									               <div style="padding:10px ;     width: 25%; float: left; height: 21px; line-height: 5px; font-weight: bold;">Sub total:</div>
									               <div style="     border-top: 0; padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">';
									               	if($orderDetails[0]['user_discount']>0){ 
									            $html .= number_format($value['price']- ($orderDetails[0]['discount']/100), 2,',', '.'); 
									               	} elseif($value['fea_base_price']>0){ 
									            $html .= number_format($value['price'], 2,',', '.'); 
									               	} else { 
									            $html .= number_format($value['price'], 2,',', '.'); 
									               	}
									            $html .=' &euro; </div>
			         								</div>';
						                    }
						                    if($value['feature_type']==2){ 
						                      	if($orderDetails[0]['room_discount']>0){ 
								                    $total_discounts = 'Discount ';
								                    $total_discount = '';
						                            if($orderDetails[0]['user_discount']>0){ 
						                                $total_discount .= '(User-'.$orderDetails[0]['user_discount'].'%)';
						                            } 
						                            
								                    $html .= '</div>
								                    	<div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
										                <div style="padding:10px ; width: 25%; float: left; height: 21px; line-height: 15px;font-weight: bold;">'.$total_discounts.trim($total_discount,',').'</div>
										                <div style="padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">'.number_format($orderDetails[0]['room_discount']/100, 2,',', '.').'&euro; </div>
										            </div>';
								                
								                    $html .='<div style="width: 100%; float: left;">         	
										 			   <div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
										               <div style="padding:10px ;     width: 25%; float: left; height: 21px; line-height: 5px; font-weight: bold;">Sub total:</div>
										               <div style="     border-top: 0; padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">';
										               	if($value['fea_base_price']>0){ 
										            $html .= number_format($value['fea_base_price']-($orderDetails[0]['room_discount']/100), 2,',', '.'); 
										               	} else { 
										            $html .= number_format($value['base_price'], 2,',', '.'); 
										               	}
										            $html .=' &euro; </div>
				         								</div>';
				         						}
						                    }  
								        }
								        else
								        {
								        	$html .= '<div style="padding:10px ;     font-weight: bold;  width: 35%; float: left; height: 21px; line-height: 15px;">';
								            $html .= $title; 
								            $html .= '</div>
								                <div style="padding:10px ; width: 25%; float: left; height: 21px; line-height: 5px;">1</div>
								                <div style="padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">'.number_format($orderDetails[0]['total_base']/100, 2,',', '.').' &euro;</div>
								            ';
								        } 
								    } 
								}
								if($orderDetails[0]['is_booking']==0){
						            $html .='<div style="width: 100%; float: left; ">         	
							 			   <div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
							               <div style="padding:10px ;     width: 25%; float: left; height: 21px; line-height: 5px; font-weight: bold;">Sub total:</div>
							               <div style="     border-top: 0; padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">'.number_format($orderDetails[0]['total_base']/100, 2,',', '.').' &euro;</div>
	         								</div>';
         						}
         						if($orderDetails[0]['vat']>0)
         						{		
						            $html .='<div style="width: 100%; float: left;">         	
							 			   <div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
							               <div style="padding:10px ;      width: 25%; float: left; height: 21px; line-height: 5px; font-weight: bold;">Vat:</div>
							               <div style="     border-top: 0;   padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">'.number_format($orderDetails[0]['vat']/100, 2,',', '.').' &euro;</div>
	         								</div>';
         						}
         						/*Reservation*/	
         						$reservation_total = '';	
         						if($orderDetails[0]['is_recomended'] == 1) {
					        		$setting = getValue('sys_settings', array('key'=>'reservation_fee'));
									$reservation_charge = $setting ? $setting['value'] : 0;
									$reservation_total = ' (40% Deposit)';
								}			
         						$html .='<div style="width: 100%; float: left;">         	
						 			   <div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
						               <div style="padding:10px ;    width: 25%; float: left; height: 21px; line-height: 5px; font-weight: bold;">Payment Fee:</div>
						               <div style="     border-top: 0; padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">'.number_format($orderDetails[0]['payment_fee']/100, 2,',', '.').' &euro;</div>
         								</div>
         								<div style="width: 100%; float: left;">         	
						 			   <div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
						               <div style="padding:10px ;    width: 25%; float: left; height: 21px; line-height: 5px; font-weight: bold;">Grand Total '.$reservation_total.':</div>
						               <div style="     border-top: 0; padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">'.number_format($orderDetails[0]['total_sum']/100, 2,',', '.').' &euro;</div>
         								</div></div>

         								<div style="width: 100%; float: left;">         	
						 			   <div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
						               <div style="padding:10px ;    width: 25%; float: left; height: 21px; line-height: 5px; font-weight: bold;">&nbsp;</div>
						               <div style="     border-top: 0; padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
         								</div></div></div></div></div></div>';
         					/*Reservation*/	
     						if($orderDetails[0]['is_recomended'] == 1) {
				        		$html .= '<div style="width: 100%; float: left;">         	
					 			   <div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
					               <div style="padding:10px ;    width: 25%; float: left; height: 21px; line-height: 5px; font-weight: bold;">Rest payment at arrival:</div>
					               <div style="     border-top: 0; padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">'.number_format($orderDetails[0]['reservation_rest_amount']/100, 2,',', '.').' &euro;</div>
     								</div></div>';
							}
         					if($orderDetails[0]['payment_method_id']==12 || $orderDetails[0]['payment_method_id']==15){
         						$html .='<div style="clear: both; width: 100%; margin:0 auto 0; max-width: 960px; padding: 0 50px;"><h2 style="padding: 5px 10px 5px 10px;border-bottom:1px solid #ccc; display: block;">RECIPIENT</h2>
         								<table style="padding:0px 10px 0 0px; width: 100%;">
         									<tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0;">'.$site_address_name['value'].'</td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0;">Bank Details:</td>
								            </tr>
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">'.$site_address_city['value'].'</td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								            </tr>
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">'.$site_address_country_zip['value'].'</td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">UBS, Bahnhofstrasse 61</td>
								            </tr>
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">5000 Aarau, Switzerland</td>
								            </tr>
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								            </tr>
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								            </tr>
								            
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">UID: CHE-362.535.263</td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">IBAN: CH810023123110716660E</td>
								            </tr>
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">Clearing: 231</td>
								            </tr>
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">Swift: UBSWCHZH80A</td>
								            </tr>
								        </table></div>';	
								}									
					    $html .='</div>
					   </body>
					</html>';
			}		
            //echo $html;die;
            $pdfFilePath = $orderDetails[0]['order_id_masked'].".pdf";
	        $this->load->library('m_pdf');

	        $this->m_pdf->pdf->useOnlyCoreFonts = true;    // false is default
			$this->m_pdf->pdf->SetTitle("Castleevents Title");
			$this->m_pdf->pdf->SetAuthor("Author");
			$this->m_pdf->pdf->SetDisplayMode('fullpage'); 
			$this->m_pdf->pdf->WriteHTML($html);
			$this->m_pdf->pdf->Output($pdfFilePath, "D");    
	        die;
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/order');
		}
	}

	public function unpaid_invoices(){
		$content_data = array();
		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$content_data['orders'] = $this->common_model->getAllMultipleJoin('shop_orders',array('order_id >'=>0, 'payed'=>0,'username !='=>'','is_booking'=>0),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('usr_users','usr_users.id = shop_carts.user_id'),array('feu_userdetails','usr_users.id = feu_userdetails.user_id')),'shop_orders.created DESC','*,shop_orders.created as created','shop_orders.order_id,feu_userdetails.username') ;
		
	  	$datarange= strtotime(date('2018-01-01'));
		
		$content_data['booking_orders'] = $this->common_model->getAllMultipleJoin('shop_orders',array('order_id >'=>0, 'payed'=>0,'username !='=>'','is_booking'=>1),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('usr_users','usr_users.id = shop_carts.user_id'),array('feu_userdetails','usr_users.id = feu_userdetails.user_id')),'shop_orders.created DESC','*,shop_orders.created as created','shop_orders.order_id,feu_userdetails.username') ;
		if($content_data['booking_orders'])
		{
			
			foreach ($content_data['booking_orders'] as $key => $value) {
				$reminder = 0;
				$reminder_date = '';
				$reminderDetails = $this->common_model->getAll('order_to_reminder',array('order_id'=>$value['order_id']),'','remind_date DESC');
				if($reminderDetails)
				{
					$reminder = count($reminderDetails);
					$reminder_date = date('d-m-Y',strtotime($reminderDetails[0]['remind_date']));
				}
				$content_data['booking_orders'][$key]['reminder']=$reminder;
				$content_data['booking_orders'][$key]['reminder_date']=$reminder_date;
			}
		}
		//echo $this->db->last_query(); die;
		$data['content'] = $this->load->view('admin/orders/unpaid_invoices', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	public function download_membership($page = 0)
	{
		$itemsPerPage = 500;
		$offset = (($page+1) - 1) * $itemsPerPage;
		$sql = "SELECT *, `shop_orders`.`created` as `created` FROM `shop_orders` LEFT JOIN `shop_carts` ON `shop_carts`.`id` = `shop_orders`.`cart_id` LEFT JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` LEFT JOIN `feu_userdetails` ON `usr_users`.`id` = `feu_userdetails`.`user_id` WHERE `order_id` >0 AND `payed` =0 AND `username` != '' AND `is_booking` =0 GROUP BY `shop_orders`.`order_id`, `feu_userdetails`.`username` ORDER BY `shop_orders`.`created` DESC LIMIT ".$offset.", ".$itemsPerPage;
		
		$ordersData = $this->db->query($sql) ;
		$orders = $ordersData->result_array();
		//echo $this->db->last_query();die;
		$site_address_name = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_name'));
		$site_address_city = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_city'));
		$site_address_country_zip = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_country_zip'));
		if($orders)
		{ 
			$html='<style>
				   	body {font-family: sans-serif;
					    font-size: 10pt;
					}
					p { margin: 0pt;
					}
					td { vertical-align: top; }
					.items td {
					    border-left: 0.1mm solid #000000;
					    border-right: 0.1mm solid #000000;
					}
					table thead td { background-color: #b3975b;
					    border: 0.1mm solid #000000;
					    color: #fff;
					}
					.items td.blanktotal {
					    background-color: #FFFFFF;
					    border: 0mm none #000000;
					    border-top: 0.1mm solid #000000;
					    border-right: 0.0mm solid #000000;
					}
					.items td.totals {
					    text-align: right;
					    border-top: 0.1mm solid #000000;
					    border-right: 0.0mm solid #000000;
					    border-left: 0.0mm solid #000000;
					}
					.items td.totals1 {
					    text-align: right;
					    border-top: 0.0mm solid #000000;
					    border-right: 0.0mm solid #000000;
					    border-left: 0.0mm solid #000000;
					}
				   </style>
				   <div style="padding: 50px 10px 70px;">
			          <p style="margin:0;">'.$site_address_name['value'].'</p>
			          <p style="margin:0;">'.$site_address_city['value'].',</p>
			          <p style="margin:0;">'.$site_address_country_zip['value'].'</p>
			          <p style="padding-top: 10px;">UID: CHE-362.535.263</p>
			        </div>							  
				         <h2 style="padding: 10px;border-bottom:1px solid #ccc; display: block;">UNPAID MEMBERSHIP INVOICE</h2>
				         <table class="items" width="100%" style="font-size: 9pt; border-collapse: collapse;" cellpadding="8">
						    <thead>
						        <tr>
							        <td style="padding:10px ; font-weight: bold; height: 19px; line-height: 19px; float: left;">Order no.</td>
					               	<td style="padding:10px ; font-weight: bold; float: left; height: 19px; line-height: 19px;">Date</td>
					               	<td style=" font-weight: bold; padding:10px ; float: left; height: 19px; line-height: 19px;">Total(&euro;)</td>
					               	<td style=" font-weight: bold; padding:10px ; float: left; height: 19px; line-height: 19px;">Payment</td>
					               	<td style=" font-weight: bold; padding:10px ; float: left; height: 19px; line-height: 19px;">Username</td>
					               	<td style=" font-weight: bold; padding:10px ; float: left; height: 19px; line-height: 19px;">Mobile</td>
				         		</tr>
				         	</thead>';
				            if(!empty($orders)){ 
					         		$member_total=0;
						            foreach ($orders as $key=>$data) {
						            	if($key<500)
						            	{
						            	$numberDetails = getValue('feu_userdetails',array('user_id'=>$data['user_id']));
						                $userPhones = getValue('usr_phones',array('user_id'=>$data['user_id']));
						                $number = '';
						                if($numberDetails['mobile_number'] != '')
						                {
						                    if(strpos($numberDetails['mobile_number'],'+') === false)
						                    {
						                      $number = '+'.$numberDetails['mobile_number'];
						                    }
						                    else
						                    {
						                      $number = $numberDetails['mobile_number'];
						                    }
						                }
						                elseif($userPhones)
						                {
						                    if(strpos($userPhones['mobile_number'],'+') === false)
						                    {
						                      $number = '+'.$userPhones['mobile_number'];
						                    }
						                    else
						                    {
						                      $number = $userPhones['mobile_number'];
						                    }
						                }
						            	$member_total+=$data['total_sum'];
			$html.='					<tbody style="border-bottom:1px solid #000;">
											<tr style="width: 100%; float: left; padding-left:10px;">         	
								 			   	<td style="padding:10px ; height: 19px; line-height: 19px; float: left;">'.$data['order_id_masked'].'</td>
								               	<td style="padding:10px ; float: left; height: 19px; line-height: 19px;">'.date('d-m-Y',$data['created']).'</td>
								               	<td style=" padding:10px ; float: left; height: 19px; line-height: 19px;">'.number_format($data['total_sum']/100,2,',','.').'</td>';
								               	if($data['payment_method_id']==12){ 
			$html.=					               	'<td style="padding:10px ; height: 19px; line-height: 19px; float: left;">Bank Transfer</td>'; 
												} 
												elseif($data['payment_method_id']==13){ 
			$html.=									'<td style="padding:10px ; height: 19px; line-height: 19px; float: left;">Saferpay</td>'; 
												} 
												elseif($data['payment_method_id']==14){ 
			$html.=									'<td style="padding:10px ; height: 19px; line-height: 19px; float: left;">Stripe</td>'; 
												} 
												else{ 
			$html.=									'<td style="padding:10px ; height: 19px; line-height: 19px; float: left;">Pay By Bank</td>'; 
												}
			$html.=					        '<td style="word-break: break-all; padding:10px ; float: left; height: 19px; line-height: 19px;">';
								               	if($this->session->userdata('admin_id')=='19624' || $this->session->userdata('admin_id')=='25267'){ 
			$html.=					               	$data['username']; 
												} 
			$html.=					        '</td>
											<td style=" padding:10px ; float: left; height: 19px; line-height: 19px;">'.(($number!='+0')?$number:'').'</td>
											</tr>';	
										}
									}
						        }
			$html.='			</tbody>
							</table>
							<table  width="100%" style="font-size: 9pt; border-collapse: collapse;" cellpadding="8">
                               <tbody>
                                   <tr style="background:#ddd;">
									<td style="padding:10px; border-top:2px solid #000; width:30%; font-weight: bold;">Total</td>
									<td style="padding:10px; border-top:2px solid #000; font-weight: bold;">'.number_format($member_total/100, 2,',', '.').' &euro;</td>
								 </tr>
                               </tbody>
							</table>';
		}		
        //echo $html;die;
        $title = 'First';
        if($page==0)
        {
        	$title = 'First';
        }
        if($page==1)
        {
        	$title = 'Second';
        }
        if($page==2)
        {
        	$title = 'Third';
        }
        $pdfFilePath = "Unpaid Membership_".$title.".pdf";
        $this->load->library('m_pdf');

        $this->m_pdf->pdf->useOnlyCoreFonts = true;    // false is default
		//$this->m_pdf->pdf->SetProtection(array('print'));
		$this->m_pdf->pdf->SetTitle("Castleevents Title");
		$this->m_pdf->pdf->SetAuthor("Author");
		/*$this->m_pdf->pdf->SetWatermarkText("Castleevents.com");
		$this->m_pdf->pdf->showWatermarkText = true;
		$this->m_pdf->pdf->watermark_font = 'DejaVuSansCondensed';
		$this->m_pdf->pdf->watermarkTextAlpha = 0.1;*/
		$this->m_pdf->pdf->SetDisplayMode('fullpage'); 
		$this->m_pdf->pdf->WriteHTML($html);
		$this->m_pdf->pdf->Output($pdfFilePath, "D");  
        die;
	}
	public function download_booking()
	{
		
		$datarange= strtotime(date('2018-01-01'));
		$orders = $this->common_model->getAllMultipleJoin('shop_orders',array('order_id >'=>0, 'payed'=>0,'username !='=>'','is_booking'=>1),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('usr_users','usr_users.id = shop_carts.user_id'),array('feu_userdetails','usr_users.id = feu_userdetails.user_id')),'shop_orders.created DESC','*,shop_orders.created as created','shop_orders.order_id,feu_userdetails.username') ;
		if($orders)
		{
			foreach ($orders as $key => $value) {
				$reminder = 0;
				$reminder_date = '';
				$reminderDetails = $this->common_model->getAll('order_to_reminder',array('order_id'=>$value['order_id']),'','remind_date DESC');
				if($reminderDetails)
				{
					$reminder = count($reminderDetails);
					$reminder_date = date('d-m-Y',strtotime($reminderDetails[0]['remind_date']));
				}
				$orders[$key]['reminder']=$reminder;
				$orders[$key]['reminder_date']=$reminder_date;
			}
		}
		$site_address_name = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_name'));
		$site_address_city = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_city'));
		$site_address_country_zip = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_country_zip'));
		if($orders)
		{ 
			$html='<style>
				   	body {font-family: sans-serif;
					    font-size: 10pt;
					}
					p { margin: 0pt;
					}
					td { vertical-align: top; }
					.items td {
					    border-left: 0.1mm solid #000000;
					    border-right: 0.1mm solid #000000;
					}
					table thead td { background-color: #b3975b;
					    border: 0.1mm solid #000000;
					    color: #fff;
					}
					.items td.blanktotal {
					    background-color: #FFFFFF;
					    border: 0mm none #000000;
					    border-top: 0.1mm solid #000000;
					    border-right: 0.0mm solid #000000;
					}
					.items td.totals {
					    text-align: right;
					    border-top: 0.1mm solid #000000;
					    border-right: 0.0mm solid #000000;
					    border-left: 0.0mm solid #000000;
					}
					.items td.totals1 {
					    text-align: right;
					    border-top: 0.0mm solid #000000;
					    border-right: 0.0mm solid #000000;
					    border-left: 0.0mm solid #000000;
					}
				   </style>
				   <div style="padding: 50px 10px 70px;">
			          <p style="margin:0;">'.$site_address_name['value'].'</p>
			          <p style="margin:0;">'.$site_address_city['value'].',</p>
			          <p style="margin:0;">'.$site_address_country_zip['value'].'</p>
			          <p style="padding-top: 10px;">UID: CHE-362.535.263</p>
			        </div>							  
				         <h2 style="padding: 10px;border-bottom:1px solid #ccc; display: block;">UNPAID BOOKING INVOICE</h2>
				         <table class="items" width="100%" style="font-size: 9pt; border-collapse: collapse;" cellpadding="8">
						    <thead>
						        <tr>
							        <td style="padding:10px ; font-weight: bold; height: 19px; line-height: 19px; float: left;">Order no.</td>
					               	<td style="padding:10px ; font-weight: bold; float: left; height: 19px; line-height: 19px;">Date</td>
					               	<td style=" font-weight: bold; padding:10px ; float: left; height: 19px; line-height: 19px;">Total(&euro;)</td>
					               	<td style=" font-weight: bold; padding:10px ; float: left; height: 19px; line-height: 19px;">Payment</td>
					               	<td style=" font-weight: bold; padding:10px ; float: left; height: 19px; line-height: 19px;">Username</td>
					               	<td style=" font-weight: bold; padding:10px ; float: left; height: 19px; line-height: 19px;">Mobile</td>
					               	<td style=" font-weight: bold; padding:10px ; float: left; height: 19px; line-height: 19px;">Total Reminders</td>
					               	<td style=" font-weight: bold; padding:10px ; float: left; height: 19px; line-height: 19px;">Last Remind Date</td>
				         		</tr>
				         	</thead>';
				            if(!empty($orders)){ 
					         		$member_total=0;
						            foreach ($orders as $key=>$data) {
						            	$numberDetails = getValue('feu_userdetails',array('user_id'=>$data['user_id']));
						                $userPhones = getValue('usr_phones',array('user_id'=>$data['user_id']));
						                $number = '';
						                if($numberDetails['mobile_number'] != '')
						                {
						                    if(strpos($numberDetails['mobile_number'],'+') === false)
						                    {
						                      $number = '+'.$numberDetails['mobile_number'];
						                    }
						                    else
						                    {
						                      $number = $numberDetails['mobile_number'];
						                    }
						                }
						                elseif($userPhones)
						                {
						                    if(strpos($userPhones['mobile_number'],'+') === false)
						                    {
						                      $number = '+'.$userPhones['mobile_number'];
						                    }
						                    else
						                    {
						                      $number = $userPhones['mobile_number'];
						                    }
						                }
						            	$member_total+=$data['total_sum'];
			$html.='					<tbody style="border-bottom:1px solid #000;">
											<tr style="width: 100%; float: left; padding-left:10px;">         	
								 			   	<td style="padding:10px ; height: 19px; line-height: 19px; float: left;">'.$data['order_id_masked'].'</td>
								               	<td style="padding:10px ; float: left; height: 19px; line-height: 19px;">'.date('d-m-Y',$data['created']).'</td>
								               	<td style=" padding:10px ; float: left; height: 19px; line-height: 19px;">'.number_format($data['total_sum']/100,2,',','.').'</td>';
								               	if($data['payment_method_id']==12){ 
			$html.=					               	'<td style="padding:10px ; height: 19px; line-height: 19px; float: left;">Bank Transfer</td>'; 
												} 
												elseif($data['payment_method_id']==13){ 
			$html.=									'<td style="padding:10px ; height: 19px; line-height: 19px; float: left;">Saferpay</td>'; 
												} 
												elseif($data['payment_method_id']==14){ 
			$html.=									'<td style="padding:10px ; height: 19px; line-height: 19px; float: left;">Stripe</td>'; 
												} 
												else{ 
			$html.=									'<td style="padding:10px ; height: 19px; line-height: 19px; float: left;">Pay By Bank</td>'; 
												}
			$html.=					        '<td style="word-break: break-all; padding:10px ; float: left; height: 19px; line-height: 19px;">';
								               	if($this->session->userdata('admin_id')=='19624' || $this->session->userdata('admin_id')=='25267'){ 
			$html.=					               	$data['username']; 
												} 
			$html.=					        '</td>
											<td style=" padding:10px ; float: left; height: 19px; line-height: 19px;">'.(($number!='+0')?$number:'').'</td>
											<td style="padding:10px ; height: 19px; line-height: 19px; float: left;">'.$data['reminder'].'</td>
											<td style="padding:10px ; height: 19px; line-height: 19px; float: left;">'.$data['reminder_date'].'</td>
											</tr>';	
									}
						        }
			$html.='			</tbody>
							</table>
							<table  width="100%" style="font-size: 9pt; border-collapse: collapse;" cellpadding="8">
                               <tbody>
                                   <tr style="background:#ddd;">
									<td style="padding:10px; border-top:2px solid #000; width:30%; font-weight: bold;">Total</td>
									<td style="padding:10px; border-top:2px solid #000; font-weight: bold;">'.number_format($member_total/100, 2,',', '.').' &euro;</td>
								 </tr>
                               </tbody>
							</table>';
		}		
        //echo $html;die;
        $pdfFilePath = "Unpaid Booking.pdf";
        $this->load->library('m_pdf');

        $this->m_pdf->pdf->useOnlyCoreFonts = true;    // false is default
		//$this->m_pdf->pdf->SetProtection(array('print'));
		$this->m_pdf->pdf->SetTitle("Castleevents Title");
		$this->m_pdf->pdf->SetAuthor("Author");
		/*$this->m_pdf->pdf->SetWatermarkText("Castleevents.com");
		$this->m_pdf->pdf->showWatermarkText = true;
		$this->m_pdf->pdf->watermark_font = 'DejaVuSansCondensed';
		$this->m_pdf->pdf->watermarkTextAlpha = 0.1;*/
		$this->m_pdf->pdf->SetDisplayMode('fullpage'); 
		$this->m_pdf->pdf->WriteHTML($html);
		$this->m_pdf->pdf->Output($pdfFilePath, "D"); 
        die;
	}
	public function download_upcoming()
	{
		if($this->input->post())
		{
			$qry = $this->db->query('select * from (select * from (SELECT  shop_orders.time,shop_articles_carts.article_id,shop_orders.created,shop_orders.cart_id,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus`,shop_orders.total_base, shop_orders.total_sum,shop_orders.payment_method_id,shop_orders.order_id_masked FROM `shop_articles` INNER JOIN `shop_articles_carts` ON `shop_articles_carts`.`article_id` = `shop_articles`.`id` INNER JOIN `shop_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` INNER JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` INNER JOIN `shop_orders` ON `shop_orders`.`cart_id` = `shop_carts`.`id` WHERE ( `shop_articles_carts`.`cancelled` != 1 OR `shop_articles_carts`.`cancelled` IS NULL ) AND `shop_orders`.`payed` = 1 ORDER BY `usr_users`.`id` DESC, `shop_carts`.`created` DESC) as a GROUP BY a.user_id ORDER BY a.user_id DESC) as b where case when time = 182 then (created >= '.(strtotime($this->input->post('fromDate'))-(182*86400)).' AND created <= '.(strtotime($this->input->post('toDate'))-(182*86400)).') when time = 365 then (created >= '.(strtotime($this->input->post('fromDate'))-(365*86400)).' AND created <='.(strtotime($this->input->post('toDate'))-(365*86400)).') END AND article_id in (5,4) order by b.created ASC');
        
			$orders = $qry->result_array();//print_r($content_data['orders']); die;
		}
		else
		{
			$qry = $this->db->query('select * from (select * from (SELECT shop_orders.time,shop_articles_carts.article_id,shop_orders.created,shop_orders.cart_id,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus`,shop_orders.total_base, shop_orders.total_sum,shop_orders.payment_method_id,shop_orders.order_id_masked FROM `shop_articles` INNER JOIN `shop_articles_carts` ON `shop_articles_carts`.`article_id` = `shop_articles`.`id` INNER JOIN `shop_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` INNER JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` INNER JOIN `shop_orders` ON `shop_orders`.`cart_id` = `shop_carts`.`id` WHERE ( `shop_articles_carts`.`cancelled` != 1 OR `shop_articles_carts`.`cancelled` IS NULL ) AND `shop_orders`.`payed` = 1 ORDER BY `usr_users`.`id` DESC, `shop_carts`.`created` DESC) as a GROUP BY a.user_id ORDER BY a.user_id DESC) as b where case when time = 365 then b.created >('.time().' - (365 * 86400)) when time = 182 then b.created >('.time().' - (182 * 86400)) end AND article_id in (5,4) AND created > ('.time().' - (365 * 86400)) order by b.created ASC');
        
			$orders = $qry->result_array();//print_r($content_data['orders']); die;
		}
		//echo $this->db->last_query();die;
		$site_address_name = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_name'));
		$site_address_city = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_city'));
		$site_address_country_zip = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_country_zip'));
		if($orders)
		{ 
			$html='<style>
				   	body {font-family: sans-serif;
					    font-size: 10pt;
					}
					p { margin: 0pt;
					}
					td { vertical-align: top; }
					.items td {
					    border-left: 0.1mm solid #000000;
					    border-right: 0.1mm solid #000000;
					}
					table thead td { background-color: #b3975b;
					    border: 0.1mm solid #000000;
					    color: #fff;
					}
					.items td.blanktotal {
					    background-color: #FFFFFF;
					    border: 0mm none #000000;
					    border-top: 0.1mm solid #000000;
					    border-right: 0.0mm solid #000000;
					}
					.items td.totals {
					    text-align: right;
					    border-top: 0.1mm solid #000000;
					    border-right: 0.0mm solid #000000;
					    border-left: 0.0mm solid #000000;
					}
					.items td.totals1 {
					    text-align: right;
					    border-top: 0.0mm solid #000000;
					    border-right: 0.0mm solid #000000;
					    border-left: 0.0mm solid #000000;
					}
				   </style>
				   <div style="padding: 50px 10px 70px;">
			          <p style="margin:0;">'.$site_address_name['value'].'</p>
			          <p style="margin:0;">'.$site_address_city['value'].',</p>
			          <p style="margin:0;">'.$site_address_country_zip['value'].'</p>
			          <p style="padding-top: 10px;">UID: CHE-362.535.263</p>
			        </div>							  
				         <h2 style="padding: 10px;border-bottom:1px solid #ccc; display: block;">UPCOMING MEMBERSHIP INVOICE</h2>
				         <table class="items" width="100%" style="font-size: 9pt; border-collapse: collapse;" cellpadding="8">
						    <thead>
						        <tr>
							        <td style="padding:10px ; font-weight: bold; height: 19px; line-height: 19px; float: left;">Order no.</td>
					               	<td style="padding:10px ; font-weight: bold; float: left; height: 19px; line-height: 19px;">Date</td>
					               	<td style=" font-weight: bold; padding:10px ; float: left; height: 19px; line-height: 19px;">Total(&euro;)</td>
					               	<td style=" font-weight: bold; padding:10px ; float: left; height: 19px; line-height: 19px;">Payment</td>
					               	<td style=" font-weight: bold; padding:10px ; float: left; height: 19px; line-height: 19px;">Username</td>
					               	<td style=" font-weight: bold; padding:10px ; float: left; height: 19px; line-height: 19px;">Mobile</td>
				         		</tr>
				         	</thead>';
				            if(!empty($orders)){ 
					         		$member_total=0;
						            foreach ($orders as $key=>$data) {
						            	if($key<500)
						            	{
						            	$numberDetails = getValue('feu_userdetails',array('user_id'=>$data['user_id']));
						                $userPhones = getValue('usr_phones',array('user_id'=>$data['user_id']));
						                $number = '';
						                if($numberDetails['mobile_number'] != '')
						                {
						                    if(strpos($numberDetails['mobile_number'],'+') === false)
						                    {
						                      $number = '+'.$numberDetails['mobile_number'];
						                    }
						                    else
						                    {
						                      $number = $numberDetails['mobile_number'];
						                    }
						                }
						                elseif($userPhones)
						                {
						                    if(strpos($userPhones['mobile_number'],'+') === false)
						                    {
						                      $number = '+'.$userPhones['mobile_number'];
						                    }
						                    else
						                    {
						                      $number = $userPhones['mobile_number'];
						                    }
						                }
						            	$member_total+=$data['total_sum'];
			$html.='					<tbody style="border-bottom:1px solid #000;">
											<tr style="width: 100%; float: left; padding-left:10px;">         	
								 			   	<td style="padding:10px ; height: 19px; line-height: 19px; float: left;">'.$data['order_id_masked'].'</td>
								               	<td style="padding:10px ; float: left; height: 19px; line-height: 19px;">'.date('d-m-Y',$data['created']).'</td>
								               	<td style=" padding:10px ; float: left; height: 19px; line-height: 19px;">'.number_format($data['total_sum']/100,2,',','.').'</td>';
								               	if($data['payment_method_id']==12){ 
			$html.=					               	'<td style="padding:10px ; height: 19px; line-height: 19px; float: left;">Bank Transfer</td>'; 
												} 
												elseif($data['payment_method_id']==13){ 
			$html.=									'<td style="padding:10px ; height: 19px; line-height: 19px; float: left;">Saferpay</td>'; 
												} 
												elseif($data['payment_method_id']==14){ 
			$html.=									'<td style="padding:10px ; height: 19px; line-height: 19px; float: left;">Stripe</td>'; 
												} 
												else{ 
			$html.=									'<td style="padding:10px ; height: 19px; line-height: 19px; float: left;">Pay By Bank</td>'; 
												}
			$html.=					        '<td style="word-break: break-all; padding:10px ; float: left; height: 19px; line-height: 19px;">';
								               	if($this->session->userdata('admin_id')=='19624' || $this->session->userdata('admin_id')=='25267'){ 
			$html.=					               	$numberDetails['username']; 
												} 
			$html.=					        '</td>
											<td style=" padding:10px ; float: left; height: 19px; line-height: 19px;">'.(($number!='+0')?$number:'').'</td>
											</tr>';	
										}
									}
						        }
			$html.='			</tbody>
							</table>
							<table  width="100%" style="font-size: 9pt; border-collapse: collapse;" cellpadding="8">
                               <tbody>
                                   <tr style="background:#ddd;">
									<td style="padding:10px; border-top:2px solid #000; width:30%; font-weight: bold;">Total</td>
									<td style="padding:10px; border-top:2px solid #000; font-weight: bold;">'.number_format($member_total/100, 2,',', '.').' &euro;</td>
								 </tr>
                               </tbody>
							</table>';
		}		
        //echo $html;die;
        $pdfFilePath = "Upcoming Membership.pdf";
        $this->load->library('m_pdf');

        $this->m_pdf->pdf->useOnlyCoreFonts = true;    // false is default
		//$this->m_pdf->pdf->SetProtection(array('print'));
		$this->m_pdf->pdf->SetTitle("Castleevents Title");
		$this->m_pdf->pdf->SetAuthor("Author");
		/*$this->m_pdf->pdf->SetWatermarkText("Castleevents.com");
		$this->m_pdf->pdf->showWatermarkText = true;
		$this->m_pdf->pdf->watermark_font = 'DejaVuSansCondensed';
		$this->m_pdf->pdf->watermarkTextAlpha = 0.1;*/
		$this->m_pdf->pdf->SetDisplayMode('fullpage'); 
		$this->m_pdf->pdf->WriteHTML($html);
		$this->m_pdf->pdf->Output($pdfFilePath, "D");  
        die;
	}

	public function checkin_status($enc_userID='')
	{
		if($enc_userID!='')
		{
			$orderId=base64_decode($enc_userID);
			$this->common_model->UpdateData('shop_orders',array('checkin_payed'=>1),array('order_id'=>$orderId));
			$orderDetail = $this->common_model->getAllRowMultipleJoin('shop_orders',array('order_id'=>$orderId),array(array('usr_users','usr_users.email = shop_orders.invoiceAddress'),array('feu_userdetails','feu_userdetails.user_id = usr_users.id')),'','*,shop_orders.created as created_date');
			
			/****************Payment Mail******************/
			if(!empty($orderDetail))
			{
				//$to = 'sayan@digitalaptech.com';
				$to = $orderDetail['invoiceAddress'];
				$sub = getAdminLang('Confirmation',$orderDetail['userlanguage']).': '.getAdminLang('Successful_payment',$orderDetail['userlanguage']);
				$body= '<p>'.getAdminLang('We_have_received_your_payment',$orderDetail['userlanguage']).'!</p>';
				$body.= '<p><p>'.getAdminLang('Paid_Amount',$orderDetail['userlanguage']).': '.($orderDetail['checkin_amount']).' EUR</p>';
				$body.= '<p>'.getAdminLang('Invoice_will_be_located',$orderDetail['userlanguage']).'</p>';
				$body.= '<p>'.getAdminLang('We_appreciate_very_much',$orderDetail['userlanguage']).'</p>';
				$body.= '<p>'.getAdminLang('Please_do_not_hesitate_to_contact',$orderDetail['userlanguage']).'</p>';
				
				
				$bodys=' <table cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#22222c" width="100%" style="max-width: 600px;">
	                    <tr>
	                       <td>
	                          <table cellspacing="0" cellpadding="0" border="0" width="100%">
	                             <tr>
	                                <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
	                                   <h2>Dear <span style="text-transform:capitalize">'.$orderDetail['username'].'</span> </h2>
	                                </td>
	                             </tr>
	                             <tr>
	                                <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
	                                   '.$body.'
	                                </td>
	                             </tr>
	                             <tr>
	                             	<td align="center" style="font-family: sans-serif; color: rgb(179, 151, 91); padding: 20px 40px; border-top: 1px solid rgb(79, 79, 79); background: rgb(19, 18, 24) none repeat scroll 0px 0px;">
	                             		'.getAdminLang('Best_regards',$orderDetail['userlanguage']).' <br>
	                             		<p style="margin:5px 0 0">'.getAdminLang('Your_team_of_castleevents',$orderDetail['userlanguage']).'</p> 
	                             	</td>
	                             </tr>
	                          </table>
	                       </td>
	                    </tr>
	                </table>';
	                
					$this->utility->sendOrderMail($to,$sub,$bodys);


					/*************Admin Mail*********************/
					$to1 = 'andrej@castleevents.com';
					$sub = 'Confirmation: Successful payment';
					//$sub = 'Your booking: Order CE-'.$orderDetail['order_id'];
					//$body= '<p>Dear '.$orderDetail['username'].',</p>';
					$body= '<p>Thank you for you payment.</p>';
					$body.= '<p>Invoice Number: CE-'.$orderDetail['order_id'].'</p><p>Generated on: '.date('Y-m-d',$orderDetail['created_date']).'</p><p>Paid Amount: '.($orderDetail['checkin_amount']).' EUR</p>';
					$body.= '<p>Invoice will be located in your profile settings area, please login at www.castleevents.com.</p>';
					$body.= '<p>We apprechiate your trust very much.</p>';
					$body.= '<p>Please do not hesitate to contact us for any other requests.</p>';
					//$body.= '<p>Best regards,</p><p>Your Castleevents Team </p>';


					$bodys=' <table cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#22222c" width="100%" style="max-width: 600px;">
		                    <tr>
		                       <td>
		                          <table cellspacing="0" cellpadding="0" border="0" width="100%">
		                             <tr>
		                                <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
		                                   <h2>Dear <span style="text-transform:capitalize">'.$orderDetail['username'].'</span> </h2>
		                                </td>
		                             </tr>
		                             <tr>
		                                <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
		                                   '.$body.'
		                                </td>
		                             </tr>
		                             <tr>
		                             	<td align="center" style="font-family: sans-serif; color: rgb(179, 151, 91); padding: 20px 40px; border-top: 1px solid rgb(79, 79, 79); background: rgb(19, 18, 24) none repeat scroll 0px 0px;">
		                             		Best regards <br>
		                             		<p style="margin:5px 0 0">Your Castleevents Team</p> 
		                             	</td>
		                             </tr>
		                          </table>
		                       </td>
		                    </tr>
		                </table>';


					$this->utility->sendCIMail($to1,$sub,$bodys);
					/*************Admin Mail*********************/

				//$this->utility->sendMail($to,$sub,$body);
			}	
			/****************Payment Mail******************/
			$this->utility->setMsg('Checkin payment status changed to paid','SUCCESS');	
			redirect(base_url().'admin/order/view/'.$enc_userID);
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/order/view/'.$enc_userID);
		}
	}

	public function update_total_amount(){
		$total_amount = $this->input->post('total_amount')*100;
		if($total_amount > 0){
			$order_id = $this->input->post('order_id');
			//pr($this->input->post());
			$order_details = $this->common_model->getAllRow('shop_orders',array('order_id'=>$order_id));
			$order_booking_details = $this->common_model->getAllRow('shop_booking_details',array('cart_id'=>$order_details['cart_id'],'feature_type'=>1));
			
			$total_sum_diff = ($order_details['total_sum'] - $total_amount);
			$total_base = $order_details['total_base'] - $total_sum_diff;
			$entry_fee = $order_booking_details['price'] - ($total_sum_diff/100);
			//echo $total_sum_diff.'='.$total_base.'='.$entry_fee;die;
			$this->common_model->UpdateData('shop_orders',array('total_sum'=>$total_amount, 'total_base'=>$total_base, 'total_amount_updated'=>1, 'total_amount_updated_at'=>time()),array('order_id'=>$order_id));

			$this->common_model->UpdateData('shop_booking_details',array('price'=>$entry_fee),array('cart_id'=>$order_details['cart_id'],'feature_type'=>1));
			//echo $this->db->last_query();die;
			$this->utility->setMsg('Order Toyal Amount updated successfully','SUCCESS');	
		}
		
		redirect(base_url().'admin/order/view/'.base64_encode($order_id));
	}


	public function update_real_name(){
		$real_name = $this->input->post('real_name');
		$order_id = $this->input->post('order_id');
		//pr($this->input->post());
		$this->common_model->UpdateData('shop_orders',array('real_name'=>$real_name),array('order_id'=>$order_id));
		//echo $this->db->last_query();die;
		$this->utility->setMsg('Order Real Name updated successfully','SUCCESS');	
		redirect(base_url().'admin/order/view/'.base64_encode($order_id));
	}

	public function checkin_download($enc_userID='')
	{
		if($enc_userID!='')
		{
			$orderId=base64_decode($enc_userID);
			$getEventListDataSql = $this->db->query("SELECT * from (SELECT `feu_userdetails`.`username`, `checkin_amount`, `confirmed`, `shop_orders`.`created`, `title`, `trasaction_id`, `order_id_masked`, `evt_events`.`id` as `evt_id`, `checkin_payment_method_id`,event_guest.order_id,`event_guest`.`id`,invoiceAddress,drinking_package,cape,drink_price, additional,cape_price,checkin_payed FROM `shop_orders` LEFT JOIN `event_guest` ON `event_guest`.`order_id` = `shop_orders`.`order_id` LEFT JOIN `feu_userdetails` ON `feu_userdetails`.`username` = `event_guest`.`username` LEFT JOIN `evt_events` ON `evt_events`.`id` = `event_guest`.`event_id` WHERE `checkin_amount` >0 AND `feu_userdetails`.`username` != '' AND `cancelled` =0 AND event_guest.order_id = ".$orderId." ORDER BY `event_guest`.`id` DESC) as a GROUP BY a.`order_id` order by a.id DESC");
			$getEventListData = $getEventListDataSql->row_array();
			if($getEventListData)
			{ 
				$site_address_name = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_name'));
				$site_address_city = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_city'));
				$site_address_country_zip = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_country_zip'));

				if($getEventListData['checkin_payment_method_id']==1){
					$payment_method_id = 'Six Payment Services';
				} else if($getEventListData['checkin_payment_method_id']==2){
					$payment_method_id = 'Premium users need not pay';
				} else {
					$payment_method_id = 'Banküberweisung';
				}

	            $html='<!DOCTYPE html>
					<html>
					   <head>
					      <title>invoice</title>
					   </head>
					   <body>
					      <div style="max-width:960px; width:100%; margin:0 auto 0; font-family: sans-serif; padding: 0 50px;">';
					            $html.=' <div style="padding: 15px 0 20px; ">
						          <p style="margin:0;">'.$site_address_name['value'].'</p>
						          <p style="margin:0;">'.$site_address_city['value'].',</p>
						          <p style="margin:0;">'.$site_address_country_zip['value'].'</p>
						          <p style="padding-top: 10px;">UID: CHE-362.535.263</p>
						         </div>';
					        $html.=' <h2 style="padding: 10px;border-bottom:1px solid #ccc; display: block;">CHECKIN INVOICE</h2>
					         <table style="padding:0px 10px 0 0px; width: 100%; margin-bottom: 36px;">
					            <tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 0">Order No</td>
					               <td style="padding:10px ;line-height: 0">'.$getEventListData['order_id_masked'].'</td>
					            </tr>';
					            
					    $html.='<tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 5px">Date</td>
					               <td style="padding:10px ;line-height: 5px">'.date('d-m-Y',strtotime($getEventListData['confirmed'])).'</td>
					            </tr>';
					            
					    $html.=' <tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 5px">Username</td>
					               <td style="padding:10px ;line-height: 5px">'.$getEventListData['username'].'</td>
					            </tr>';
					            
					            if($this->session->userdata('admin_id')=='19624' || $this->session->userdata('admin_id')=='25267'){
					    $html.='<tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 5px">Email</td>
					               <td style="padding:10px ;line-height: 5px">'.$getEventListData['invoiceAddress'].'</td>
					            </tr>';
					        	}
					    $html.='<tr>
					               <td  style="padding:10px ; font-weight: bold; width:38%;line-height: 5px">payment status</td>
					               <td  style="padding:10px ;line-height: 5px">'.(($getEventListData['checkin_payed']==1) ? 'Paid' : 'Unpaid').'</td>
					            </tr>';
					           $html.=' <tr>
					               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 5px"> Payment Method </td>
					               <td style="padding:10px ;line-height: 5px">'.$payment_method_id.'</td>
					            </tr>';
					            if($getEventListData['checkin_payed']==1 && $getEventListData['checkin_payment_method_id']==1){
						            $html.=' <tr>
						               <td style="padding:10px ; font-weight: bold; width:38%;line-height: 5px"> Transaction ID </td>
						               <td style="padding:10px ;line-height: 5px">'.$getEventListData['trasaction_id'].'</td>
						            </tr>';
						        }
					         $html.='</table>
					         <div style="float: left;">

					         	<div style="width: 100%; float: left; ">         	
					 			   <div style="padding:10px ; font-weight: bold; width: 35%; height: 19px; line-height: 19px; float: left;">Description</div>
					               <div style="padding:10px ; font-weight: bold; width: 25%; float: left; height: 19px; line-height: 19px;">Number</div>
					               <div style=" font-weight: bold; padding:10px ; width: 30%; float: left; height: 19px; line-height: 19px;">Price</div>
					         	</div>';
					            
					            if($getEventListData['drinking_package']){
					            	$html .='<div style="width: 100%; float: left; "><div style="padding:10px ; font-weight: bold; width: 35%; height: 19px; line-height: 19px; float: left;">'.(($getEventListData['drinking_package']==1) ? 'Basic' : 'Premium').' package</div>
					               <div style="padding:10px ; font-weight: bold; width: 25%; float: left; height: 19px; line-height: 19px;">1</div>
					               <div style=" font-weight: bold; padding:10px ; width: 30%; float: left; height: 19px; line-height: 19px;">'.number_format($getEventListData['drink_price'], 2,',', '.').'</div></div>';
					            }
					            if($getEventListData['cape']>0){
					            	$cape_price = 0;
					            	if($getEventListData['id'] < 323) { 
					            		$cape_price = number_format((50*$getEventListData['cape']), 2,',', '.'); 
					            	} else { 
					            		$cape_price = number_format($getEventListData['cape_price'], 2,',', '.'); 
					            	}
					            	$html .='<div style="width: 100%; float: left; "><div style="padding:10px ; font-weight: bold; width: 35%; height: 19px; line-height: 19px; float: left;">Cape</div>
					               <div style="padding:10px ; font-weight: bold; width: 25%; float: left; height: 19px; line-height: 19px;">'.$getEventListData['cape'].'</div>
					               <div style=" font-weight: bold; padding:10px ; width: 30%; float: left; height: 19px; line-height: 19px;">'.$cape_price.'</div></div>';
					            }
					            if($getEventListData['additional']>0){
					            	$html .='<div style="width: 100%; float: left; "><div style="padding:10px ; font-weight: bold; width: 35%; height: 19px; line-height: 19px; float: left;">Extras</div>
					               <div style="padding:10px ; font-weight: bold; width: 25%; float: left; height: 19px; line-height: 19px;">1</div>
					               <div style=" font-weight: bold; padding:10px ; width: 30%; float: left; height: 19px; line-height: 19px;">'.number_format($getEventListData['additional'], 2,',', '.').'</div></div>';
					            }
					            $checkin_total = 0;
				            	if($getEventListData['id'] < 323) { 
				            		$checkin_total = number_format(((50*$getEventListData['cape'])+$getEventListData['drink_price']), 2,',', '.'); 
				            	} else { 
				            		$checkin_total = number_format($getEventListData['checkin_amount'], 2,',', '.'); 
				            	}
								$html .='<div style="width: 100%; float: left;">         	
						 			   <div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
						               <div style="padding:10px ;    width: 25%; float: left; height: 21px; line-height: 5px; font-weight: bold;">Grand Total:</div>
						               <div style="     border-top: 0; padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">'.$checkin_total.' &euro;</div>
         								</div></div>

         								<div style="width: 100%; float: left;">         	
						 			   <div style="padding:10px ;     font-weight: bold; width: 35%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
						               <div style="padding:10px ;    width: 25%; float: left; height: 21px; line-height: 5px; font-weight: bold;">&nbsp;</div>
						               <div style="     border-top: 0; padding:10px ; width: 30%; float: left; height: 21px; line-height: 5px;">&nbsp;</div>
         								</div></div></div></div></div></div>';
         					if($getEventListData['checkin_payment_method_id']==3 || $getEventListData['checkin_payment_method_id']==0){
         						$html .='<div style="clear: both; width: 100%; margin:0 auto 0; max-width: 960px; padding: 0 50px;"><h2 style="padding: 5px 10px 5px 10px;border-bottom:1px solid #ccc; display: block;">RECIPIENT</h2>
         								<table style="padding:0px 10px 0 0px; width: 100%;">
         									<tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0;">'.$site_address_name['value'].'</td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0;">Bank Details:</td>
								            </tr>
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">'.$site_address_city['value'].'</td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								            </tr>
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">'.$site_address_country_zip['value'].'</td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">UBS, Bahnhofstrasse 61</td>
								            </tr>
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">5000 Aarau, Switzerland</td>
								            </tr>
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								            </tr>
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								            </tr>
								            
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">UID: CHE-362.535.263</td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">IBAN: CH810023123110716660E</td>
								            </tr>
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">Clearing: 231</td>
								            </tr>
								            <tr>
								               <td style="font-size: 15px; width: 38%;font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px"></td>
								               <td style="font-size: 15px; font-weight: 100; padding:2px 5px 0 5px; margin: 0; line-height: 15px">Swift: UBSWCHZH80A</td>
								            </tr>
								        </table></div>';	
								}									
					    $html .='</div>
					   </body>
					</html>';
			}		
            //echo $html;die;
            $pdfFilePath = "Checkin_".$orderDetails[0]['order_id_masked'].".pdf";
	        $this->load->library('m_pdf');

	        $this->m_pdf->pdf->useOnlyCoreFonts = true;    // false is default
			$this->m_pdf->pdf->SetTitle("Castleevents Title");
			$this->m_pdf->pdf->SetAuthor("Author");
			$this->m_pdf->pdf->SetDisplayMode('fullpage'); 
			$this->m_pdf->pdf->WriteHTML($html);
			$this->m_pdf->pdf->Output($pdfFilePath, "D");    
	        die;
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/order');
		}
	}
	public function change_membership($enc_userID='')
	{
		if($enc_userID!='')
		{
			$orderId=base64_decode($enc_userID);
			$content_data = array();
			$content_data['order_details'] = $this->common_model->getAllRowMultipleJoin('shop_orders',array('order_id'=>$orderId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_articles_carts','shop_articles_carts.cart_id = shop_carts.id')));

			if($content_data['order_details']['time']==365){
				$content_data['memberships'] = $this->common_model->getAll('shop_articles',array('id >'=>3,'id <'=>6),'','id Desc') ;
				$content_data['memberships_half'] = array();
			} else {
				$content_data['memberships'] = $this->common_model->getAll('shop_articles',array('id >'=>3,'id <'=>6),'','id Desc') ;
        		$content_data['memberships_half'] = $this->common_model->getAll('shop_new_articles','','','id Asc') ;
			}
			
			if($this->input->post()){
				//pr($orderId);
				$type = $this->input->post('type');
				if($type != ''){
					$ord_totalsum = 0;
					$ord_paymentfee = 0;
					$ord_vat = 0;
					$membership_type = 0;
					$time = 0;
					if($type == 1){
	                    $ord_totalbase = $content_data['memberships_half'][0]['base_price'];
	                    $membership_type = 5;
	                    $time = 182;
	                }elseif($type == 2){
	                    $ord_totalbase =  $content_data['memberships_half'][1]['base_price'];
	                    $membership_type = 4;
	                    $time = 182;
	                }elseif($type == 5){
	                    $ord_totalbase =  $content_data['memberships'][0]['base_price'];
	                    $membership_type = 5;
	                    $time = 365;
	                }else{
	                    $ord_totalbase =  $content_data['memberships'][1]['base_price'];
	                    $membership_type = 4;
	                    $time = 365;
	                }
	                //echo $ord_totalbase.'+'.$membership_type.'|';
					$ord_paymentfee=(int)($ord_totalbase*2.5)/100;
					$ord_totalsum = (int)($ord_totalbase+$ord_paymentfee+$ord_vat);

					$this->common_model->UpdateData('shop_orders',array('total_base'=>$ord_totalbase, 'payment_fee'=>$ord_paymentfee, 'total_sum'=>$ord_totalsum, 'time'=>$time),array('order_id'=>$orderId));
					$this->common_model->UpdateData('shop_articles_carts',array('article_id'=>$membership_type),array('cart_id'=>$content_data['order_details']['cart_id']));
					redirect(base_url().'admin/order/change_membership/'.$enc_userID);
				} else {
					$this->utility->setMsg('Please select a type','ERROR');	
					redirect(base_url().'admin/order');
				}
			}
			$data['content'] = $this->load->view('admin/orders/change_membership', $content_data, TRUE);
			$this->load->view('admin/layout', $data);
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/order');
		}
	}
}
