<?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/Kolkata");
		$this->load->model('Booking_model');

		if(!$this->session->userdata('logged_in')) {
			redirect(base_url());
		}
	}

	public function viewBookings(){
		$template['page'] = 'Booking/viewBooking';
        $template['menu'] = 'Organizer Management';
        $template['smenu'] = 'View Organizers';
        $template['pTitle'] = "View Organizers";
        $template['pDescription'] = "View and Manage Organizers";
        $template['page_head'] = "Organizer 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');

		$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']) || 
		   !is_numeric($booking_id = decode_param($_POST['booking_id']))){
			echo json_encode($resArr);exit;
		}
		$view_all = (isset($_POST['view_all']) && $_POST['view_all'] != '')?$_POST['view_all']:'0,1,2,3';
        $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($booking_id = '',$status = '1'){
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
		if(empty($booking_id) || !is_numeric($booking_id = decode_param($booking_id))){
			$this->session->set_flashdata('message',$flashMsg);
        	redirect(base_url('Booking/viewBookings'));
		}
		$status = $this->Booking_model->changeStatus($booking_id,$status);
		if(!$status){
			$this->session->set_flashdata('message',$flashMsg);
		}
		redirect(base_url('Booking/viewBookings'));
	}

	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;
		}

		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;
            }
            if($this->session->userdata['user_type'] != 1){
            	$company_id = $this->session->userdata['id'];
            	$this->db->query("UPDATE `company_payment_details` 
            						SET `report_count`=report_count+1, 
            							`outstanding_amount`=outstanding_amount+report_charge 
            					  WHERE `company_id`=".$company_id);
            }
            //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);
	}
}
?>