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

class Latest_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')) ;
		$last_3_month_start_date = strtotime(date("Y-m-d", strtotime( date( 'Y-m-01' )." -3 months")));
		$last_month_end_date = strtotime(date("Y-m-t", strtotime( date( 'Y-m-01' )." -1 months")));
		$content_data['orders'] = $this->common_model->getAllMultipleJoin('shop_orders',array('order_id >'=>0, 'payed'=>1,'username !='=>'','is_booking'=>0,'shop_orders.created >='=>$last_3_month_start_date,'shop_orders.created <='=>$last_month_end_date, 'cancelled !='=>1, 'is_exchanged'=>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') ;
		
	  	//echo $this->db->last_query(); die;
		$content_data['booking_orders'] = $this->common_model->getAllMultipleJoin('shop_orders',array('order_id >'=>0, 'payed'=>1,'username !='=>'','is_booking'=>1,'shop_orders.created >='=>$last_3_month_start_date,'shop_orders.created <='=>$last_month_end_date, 'cancelled !='=>1, 'is_exchanged'=>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'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_events','evt_events.id = shop_booking_details.event_id'),array('loc_events_locations','evt_events.id = loc_events_locations.event_id'),array('loc_locations','loc_events_locations.location_id = loc_locations.id')),'shop_orders.created DESC','*,shop_orders.created as created','shop_orders.order_id,feu_userdetails.username, evt_events.event_unique_id, loc_locations.name,loc_locations.country,loc_locations.city, zipcode, title') ;
		//echo $this->db->last_query(); die;
		$data['content'] = $this->load->view('admin/orders/last_3_month_order', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}

	public function download_membership()
	{
		$last_3_month_start_date = strtotime(date("Y-m-d", strtotime( date( 'Y-m-01' )." -3 months")));
		$last_month_end_date = strtotime(date("Y-m-t", strtotime( date( 'Y-m-01' )." -1 months")));
		$orders = $this->common_model->getAllMultipleJoin('shop_orders',array('order_id >'=>0, 'payed'=>1,'username !='=>'','is_booking'=>0,'shop_orders.created >='=>$last_3_month_start_date,'shop_orders.created <='=>$last_month_end_date, 'cancelled !='=>1, 'is_exchanged'=>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') ;

		//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()
	{
		
		$last_3_month_start_date = strtotime(date("Y-m-d", strtotime( date( 'Y-m-01' )." -3 months")));
		$last_month_end_date = strtotime(date("Y-m-t", strtotime( date( 'Y-m-01' )." -1 months")));
		$orders = $this->common_model->getAllMultipleJoin('shop_orders',array('order_id >'=>0, 'payed'=>1,'username !='=>'','is_booking'=>1,'shop_orders.created >='=>$last_3_month_start_date,'shop_orders.created <='=>$last_month_end_date, 'cancelled !='=>1, 'is_exchanged'=>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'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_events','evt_events.id = shop_booking_details.event_id'),array('loc_events_locations','evt_events.id = loc_events_locations.event_id'),array('loc_locations','loc_events_locations.location_id = loc_locations.id')),'shop_orders.created DESC','*,shop_orders.created as created','shop_orders.order_id,feu_userdetails.username, evt_events.event_unique_id, loc_locations.name,loc_locations.country,loc_locations.city, zipcode, title') ;

		$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="padding:10px ; font-weight: bold; float: left; height: 19px; line-height: 19px;">Event ID</td>
					               	<td style="padding:10px ; font-weight: bold; float: left; height: 19px; line-height: 19px;">Event Title</td>
					               	<td style="padding:10px ; font-weight: bold; float: left; height: 19px; line-height: 19px;">Location</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) {
						            	$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'];
						                    }
						                }
						                $location = $data['name'];
				                        if($data['city']!='')
				                        {
				                          $location.=','.$data['city'];
				                        }
				                        if($data['country']!='')
				                        {
				                          $location.=','.$data['country'];
				                        }
				                        if($data['zipcode']!='')
				                        {
				                          $location.=','.$data['zipcode'];
				                        }
						            	$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;">Evt-'.$data['event_unique_id'].'</td>
								               	<td style="padding:10px ; float: left; height: 19px; line-height: 19px;">'.$data['title'].'</td>
								               	<td style="padding:10px ; float: left; height: 19px; line-height: 19px;">'.$location.'</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 add_exchange()
	{
		$order_id = $this->input->post('exchange_order_id');
		$exchange_date = date('Y-m-d', strtotime($this->input->post('exchange_date')));
		$exchange_note = $this->input->post('exchange_note');
		$uri = $this->input->post('uri');
		if($order_id!='' && $exchange_date!='')
		{
			//echo $exchange_date.'='.$exchange_note.'='.$order_id; die;
			$this->common_model->UpdateData('shop_orders',array('exchange_date'=>$exchange_date,'exchange_note'=>$exchange_note,'is_exchanged'=>1,'payed'=>1,'payment_method_id'=>15),array('order_id'=>$order_id));
		}
		$orderDetail = $this->common_model->getAllRowMultipleJoin('shop_orders',array('order_id'=>$order_id),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 = 'sumitb@digitalaptech.com';
			$to = $orderDetail['invoiceAddress'];
			$sub = getAdminLang('rebooking_confirmation',$orderDetail['userlanguage']);
			$body= '<p>'.getAdminLang('we_hereby_confirm_your_rebooking',$orderDetail['userlanguage']).'</p>';
			$body.= '<p>'.getAdminLang('description',$orderDetail['userlanguage']).':'.$orderDetail['exchange_note'].'</p><p>'.getAdminLang('date',$orderDetail['userlanguage']).': '.date('d-m-Y',strtotime($orderDetail['exchange_date'])).'</p><p>'.getAdminLang('booking_number',$orderDetail['userlanguage']).': CE-'.$orderDetail['order_id'].'</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*********************/

			//$this->utility->sendMail($to,$sub,$body);
		}	
		/****************Payment Mail******************/
		$this->utility->setMsg('Order payment status changed to exchanged','SUCCESS');	
		redirect(base_url().str_replace('-', '/', $uri));
	}
}