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

class Booking extends CI_Controller {

	public function __construct() {
		parent::__construct();
    	date_default_timezone_set("Asia/Riyadh");
		$this->load->model('Booking_model');

		if(!$this->session->userdata('logged_in')) {
			redirect(base_url());
		}
	}
	
	public function viewBookings(){
		$template['page'] = 'Booking/viewBooking';
        $template['menu'] = 'Booking Management';
        $template['smenu'] = 'View Bookings';
        $template['pTitle'] = "View Bookings";
        $template['pDescription'] = "View and Manage Bookings";
        $template['page_head'] = "Booking Management";

        $provider_id = ($this->session->userdata('user_type')==2)?$this->session->userdata('id'):'';
        $template['booking_data'] = $this->Booking_model->getBookingData('',$provider_id,'0,1,2,3,5');

		$this->load->view('template',$template);
	}

	public function getBookingData(){
		$resArr = array('status'=>0);
		if(!isset($_POST)||empty($_POST)||!isset($_POST['booking_id'])||empty($_POST['booking_id'])){
			echo json_encode($resArr);exit;
		}
		$booking_id = (!is_numeric($_POST['booking_id']))?
								  decode_param($_POST['booking_id']):$_POST['booking_id'];

		$view_all = (isset($_POST['view_all'])&&$_POST['view_all'] != '')?$_POST['view_all']:'0,1,2,3,5';
        $provider_id = ($this->session->userdata('user_type')==2)?$this->session->userdata('id'):'';
		$bookData['bookData'] = $this->Booking_model->getBookingData($booking_id,$provider_id,$view_all);

        $viewPage = $this->load->view('Booking/viewBookingDetails',$bookData,true);

        echo $viewPage;exit;
	}

    function changeStatus(){
        if(!isset($_POST) || !isset($_POST['booking_id']) || empty($_POST['booking_id'])){
            echo json_encode(array('status'=>'0'));exit;
        }
        $booking_id = decode_param($_POST['booking_id']);
        $resp = $this->Booking_model->changeStatus($booking_id,'4');
        if($resp){
            echo json_encode(array('status'=>'1'));exit;
        }
        echo json_encode(array('status'=>'0'));exit;
    }

	function generateReport(){

		$template['page'] = 'Booking/generate';

		$template['menu'] = "Report Management";
		$template['sub_menu'] = "Report Generate";

        $template['page_desc'] = "Report Generation Page";
        $template['page_title'] = "Report Management";
        
        $template['providerData'] = '';
        if($this->session->userdata('user_type') == 1){
			$this->load->model('Provider_model');
        	$template['providerData'] = $this->Provider_model->getProviderData('','0,1');
        }

		$this->load->view('template',$template);
	}

	public function rGenerate(){
		$return_arr = array('status'=>'0');
		if(!isset($_POST) || empty($_POST) || !isset($_POST['fields']) || empty($_POST['fields']) || 
		   !isset($_POST['action']) || empty($_POST['action'])){
			echo json_encode($return_arr);exit;
		}
		$action = $_POST['action'];
		$fields = str_replace(array('+','%2C'),array(' ',','),trim($_POST['fields'],','));

		$where_cond = array();
		if(isset($_POST['where_cond']) && !empty($_POST['where_cond'])){
			parse_str($_POST['where_cond'], $where_cond);
		}
		$report_data = $this->Booking_model->getDetailBookData($fields,$where_cond);

		if(!empty($report_data) && !is_array($report_data)){
			$return_arr['status'] = $report_data;
			echo json_encode($return_arr);exit;
		}

		$report_data  = $this->formatReportData($report_data);
		if(!empty($report_data)){
			if($action == 'view'){
				$return_arr['status'] = 1;
				$return_arr['report_data'] = $report_data;
			}
			if($action == 'export'){
				$return_arr['status'] = 1;
				$this->exportExcel($report_data);
			}
		}
		echo json_encode($return_arr);exit;
	}

	function exportExcel($reportData = array()){
		if(empty($reportData)){
			return 0;
		}
        $this->load->helper('csv');
        $fileName = 'reportExport_'.time().'.csv';  

        $dataRow = array();
        $headerFlg = 0;
        foreach ($reportData AS $data) {
        	$row = array();
        	if($headerFlg == 0){
        		foreach($data AS $index => $value){
        			$row[] = $index;
        		}
        		$dataRow[] = $row;

        		$row = array();
        		$headerFlg = 1;
        	}
        	foreach ($data AS $rowVal) {
        		$row[] = $rowVal;
        	}
    		$dataRow[] = $row;
        }
        if(empty($dataRow)){
        	return 0;
        }
        $this->session->set_userdata('file_name',$fileName);
		$this->session->set_userdata('report_data',$dataRow);

		return 1;
	}

	function downloadCSV(){
        $dataRow = $this->session->userdata('report_data');
        $fileName = $this->session->userdata('file_name');

        $this->session->set_userdata('file_name','');
        $this->session->set_userdata('report_data','');

        if(empty($dataRow) || empty($fileName)){
                return;
        }
        
        //Download CSV\\
        $temp_memory = fopen('php://memory', 'w');
        foreach ($dataRow as $line) {
            fputcsv($temp_memory, $line, ',');
        }
        fseek($temp_memory, 0);
        header('Content-Type: application/csv');
        header('Content-Disposition: attachement; filename="' . $fileName . '";');
        fpassthru($temp_memory);
	}

	function formatReportData($reportData = array()){
		if(empty($reportData)){
			return 0;
		}

		foreach($reportData AS $key => $data){
			if(isset($data['Book_Status'])){
				switch ($data['Book_Status']) {
					case '0': $reportData[$key]['Book_Status'] = 'Cancelled'; break;
					case '1': $reportData[$key]['Book_Status'] = 'Booked'; break;
					case '2': $reportData[$key]['Book_Status'] = 'Completed'; break;
					case '3': $reportData[$key]['Book_Status'] = 'Pending'; break;
					case '4': $reportData[$key]['Book_Status'] = 'Deleted'; break;
					case '5': $reportData[$key]['Book_Status'] = 'Payment Failed'; break;
				}
			}

			if(isset($data['Reserved_By'])){
				switch ($data['Reserved_By']) {
					case '1': $reportData[$key]['Reserved_By'] = 'Super Admin '; break;
					case '2': $reportData[$key]['Reserved_By'] = 'Provider '; break;
					case '3': $reportData[$key]['Reserved_By'] = 'Customer'; break;
				}
			}

			if(isset($data['trans_status'])){
				switch ($data['trans_status']) {
					case '0': $reportData[$key]['trans_status'] = 'Failed '; break;
					case '1': $reportData[$key]['trans_status'] = 'Completed '; break;
					case '2': $reportData[$key]['trans_status'] = 'Processing '; break;
					case '3': $reportData[$key]['trans_status'] = 'Payment Timeout '; break;
				}
			}

			if(isset($data['has_payment'])){
				$reportData[$key]['has_payment'] = ($data['has_payment'] == 1)?'Yes ':'No ';
			}

			if(!empty($data['Ticket_Details'])){
				$tktDtls = json_decode($data['Ticket_Details'],true);
				if(isset($tktDtls['price'],$tktDtls['no_ticket'],$tktDtls['total_price']) && 
				   !empty($tktDtls['price'])&&!empty($tktDtls['no_ticket'])&&!empty($tktDtls['total_price'])){

					$pDiv = (isset($tktDtls['color'])&&!empty($tktDtls['color']))?
							$tktDtls['color'].' Block : ':'';
					$pDiv .= $tktDtls['price'].' * '.$tktDtls['no_ticket'].'(Seats) = '.$tktDtls['total_price'];

					$reportData[$key]['Ticket_Details'] = $pDiv;
				} else {
					$reportData[$key]['Ticket_Details'] = '';
				}
			} else {
				$reportData[$key]['Ticket_Details'] = '';
			}
		}
		return $reportData;
	}
}
?>
