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

class Report extends CI_Controller {

	public function __construct() {
		parent::__construct();
		date_default_timezone_set("Asia/Kolkata");
		$this->load->model('Report_model');
		$this->load->model('Company_model');
		
		if(!$this->session->userdata('logged_in')) {
			redirect(base_url('Login'));
		}
 	}
 	
	public function generate() {
		$template['page'] = 'Report/generate';

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

        $template['page_desc'] = "Report Generation Page";
        $template['page_title'] = "Report Management";
        
        $template['company_data'] = $this->Company_model->getCompany('','0,1');

        $template['broker_data'] = '';
        if($this->session->userdata['user_type'] != 1){
        	$this->load->model('Broker_model');
        	$template['broker_data'] = $this->Broker_model->getBroker('','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('+',' ',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->Report_model->get_report($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);
	}
}
?>