<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Prasadam_report extends REF_Controller {
    public function __construct() {
        parent::__construct();
		$this->load->helper(array('form', 'url'));
        $this->load->library('upload');
        $this->load->model('reports/prasadam_report_model', '', TRUE);
        $this->uri_key_index = 0;
    }
    
    public function index() {
        $data = array();
        
        if (!empty($this->session->flashdata('success'))) 
            $data['success'] = $this->session->flashdata('success');
        else 
            $data['error'] = $this->session->flashdata('error');
        
        if((!empty($this->input->post('submit'))) && ($this->input->post('submit') == 'Get Data' || $this->input->post('submit') == 'Print Data' || $this->input->post('submit') == 'Excel Data' || $this->input->post('submit') == 'PDF Data' || $this->input->post('submit') == 'Chart Data')) {
            $start_date = $this->input->post('start_date');
            $end_date = $this->input->post('end_date');
            $period = $this->input->post('period');
            $date_type = $this->input->post('date_type');
        } elseif($this->input->post('submit') == 'View' || $this->input->post('print') == 'Print') {
            $start_date = $this->input->post('start_date');
            $end_date = $this->input->post('start_date');
			$period = $this->input->post('period');
            $date_type = 1;
        } else {
            $start_date = '';
            $end_date = '';
            $period = '';
            $date_type = 1;
        }
        $data['results'] = $this->prasadam_report_model->get_data($start_date,$end_date,$period,$date_type);
        if($this->input->post('print') == 'Print') {
            $start_date = $end_date = $this->input->post('start_date');
            $period = $this->input->post('period');
            
            //Get God Id's for all modules
            $abishegam 		= $this->prasadam_report_model->get_abishegam_god_prasadam($start_date,$end_date,$period);
			$homam	 		= $this->prasadam_report_model->get_homam_god_prasadam($start_date,$end_date,$period);
            $festival 		= $this->prasadam_report_model->get_festival_god_prasadam($start_date,$end_date,$period);
            $mega 			= $this->prasadam_report_model->get_mega_god_prasadam($start_date,$end_date,$period);
            $ubayam 		= $this->prasadam_report_model->get_ubayam_god_prasadam($start_date,$end_date,$period);
			$kattalai 		= $this->prasadam_report_model->get_kattalai_god_prasadam($start_date,$end_date,$period);
            $prasadam 		= $this->prasadam_report_model->get_prasadam_god_prasadam($start_date,$end_date,$period);
            $madappalli 	= $this->prasadam_report_model->get_madappalli_god_prasadam($start_date,$end_date,$period);
            //echo "<pre>"; print_r($kattalai);
            $array_merge = array_merge($abishegam,$homam,$festival,$mega,$ubayam,$kattalai,$prasadam,$madappalli);
            $result_data = array_unique($array_merge,SORT_REGULAR);
            #echo '<pre>';print_r($result_data);
            #die;
            $a = array();
            $head = array();
            $gods = array();
            $body = array();
            $head['attr'] = 'style="height: 180px; max-width: 50px; padding: 2px; '; //max-width: 80px;
            $head['sno'] = 0;
            $head[] = 'God Name' . '<style type="text/css">td { font-size: 20px !important; } td input{ font-size: 28px !important; letter-spacing: 2px; } </style>';
            
            //echo '<pre>';print_r($result_data); die;
            foreach($result_data as $key => $value) {
                
                //Get Prasadam details by God Id
                $ab_prasadam = $this->prasadam_report_model->get_ab_prasadam($value->id,$start_date,$end_date,$period);
				$hm_prasadam = $this->prasadam_report_model->get_hm_prasadam($value->id,$start_date,$end_date,$period);
                $ff_prasadam = $this->prasadam_report_model->get_ff_prasadam($value->id,$start_date,$end_date,$period);
                $mega_prasadam = $this->prasadam_report_model->get_mega_prasadam($value->id,$start_date,$end_date,$period);
                $ubayam_prasadam = $this->prasadam_report_model->get_ubayam_prasadam($value->id,$start_date,$end_date,$period);
				$kattalai_prasadam = $this->prasadam_report_model->get_kattalai_prasadam($value->id,$start_date,$end_date,$period);
                $prasadam_item = $this->prasadam_report_model->get_prasadam_item($value->id,$start_date,$end_date,$period);
                $madappalli_prasadam = $this->prasadam_report_model->get_madappalli_prasadam($value->id,$start_date,$end_date,$period);
                
                $array_item_merge = array_merge($ab_prasadam,$hm_prasadam,$ff_prasadam,$mega_prasadam,$ubayam_prasadam,$kattalai_prasadam,$prasadam_item,$madappalli_prasadam);
                
                $prasadam_qty  = array_unique($array_item_merge,SORT_REGULAR);
                
                foreach($prasadam_qty as $k => $itm_qty) {
                    $a[get_var_name($itm_qty->name).'-'.$itm_qty->prasadam_id][$value->id] = array('prasadam_id' => $itm_qty->prasadam_id, 'Naivedyam' => $itm_qty->name . ' / ' . tamil($itm_qty->tamil_name), 'qty' => $itm_qty->prasadam_qty);
                }
                
                $head[] = '<div style="transform: rotate(-90deg); white-space: nowrap; max-width: 37px; max-height: 60px; margin-left: 12px; margin-top: 190px; font-size:13px;">'.$value->god_name . '<div class="lang-tamil" style="font-size:18px;">'. $value->god_tamil . '</div></div>';
                
                $gods[$value->id] = $value->id;
            }
            
            $wid = floor(90/(count($head)-1));
            $head['attr'] .= ($wid > 0 ? 'width : '.$wid.'%;' : '') . ' "';
            
            $head[] = '<div style="transform: rotate(-90deg); white-space: nowrap; max-width: 37px; max-height: 60px; margin-left: 12px; margin-top: 190px;">Total<div class="lang-tamil""></div>';
           
            
            
            foreach($a as $index => $items) {
                $row = array();
                $total = 0;
                foreach($gods as $god_id => $god) :            
                    $qty = !empty( $items[$god_id] ) ? $items[$god_id]['qty'] : '-';
                    if( empty( $row[0] ) ) :
                        $row[0] = $items[$god_id]['prasadam'];
                    endif;
                    $row[] = $qty;
                    $total += $qty;
                endforeach;
                $row[] = $total;
                $body[] = $row;
            }
            #print_r(max($b));
            
            //echo '<pre>';print_r($body); die;
			
			$data['start_date'] 	= $start_date;
			$data['end_date']		= $end_date;
			$data['period'] 		= $period;
			$head_indoor			= array();
			$head_indoor['attr'] 	= 'style="height: 180px; max-width: 50px; padding: 2px; '; //max-width: 80px;
            $head_indoor['sno'] 	= 0;
            $head_indoor[] 			= 'Devotee Name' . '<style type="text/css">td { font-size: 20px !important; } td input{ font-size: 28px !important; letter-spacing: 2px; } </style>';
			$head_indoor[] 			= 'Time' . '<style type="text/css">td { font-size: 20px !important; } td input{ font-size: 28px !important; letter-spacing: 2px; } </style>';
			$indoor_prasadam	    = $this->prasadam_report_model->get_prasadam_records_indoor($start_date,$end_date,$period, $service_id = '43');
			if(count($indoor_prasadam) > 0) { 
				foreach($indoor_prasadam as $key=>$value) {
					$in[get_var_name($value->name)][$value->id] = array('id' => $value->id, 'prasadam_id' => $value->prasadam_id, 'Naivedyam' => $value->bp_dev_name_1, 'time' => date("h:i A", strtotime($value->bp_fn_time)), 'qty' => $value->prasadam_qty);
					
					$devotee_prasadam = $this->prasadam_report_model->get_prasadam_details($value->id);
					foreach($devotee_prasadam as $dev_pras){
						$head_indoor[] 								= '<div style="transform: rotate(-90deg); white-space: normal; max-width: 240px; max-height: 100px; margin-top: 5px; margin-left: -55px; margin-right: -55px; margin-bottom: 10px; text-align: left; word-break: break-all; font-size:13px;">'.$dev_pras->name . '<div class="lang-tamil" style="font-size:18px;">'. $dev_pras->tamil_name . '</div></div>';
						$inprasdam[$value->id][] 					= $value->id;
					}
					
				} 
             }			 
			$head_indoor['attr'] .= ($wid > 0 ? 'width : '.$wid.'%;' : '') . ' "';
            
            $head_indoor[] 		  = '<div style="transform: rotate(-90deg); white-space: normal; max-width: 240px; max-height: 100px; margin-top: 5px; margin-left: -55px; margin-right: -55px; margin-bottom: 10px; text-align: left; word-break: break-all;">Total<div class="lang-tamil""></div>';
			
			//echo "<pre>";print_r($in); print_r($inprasdam); //exit;
			foreach($in as $index => $items) {
                $row_in = array();
                $total_in = 0;
                foreach($inprasdam as $prasadam_id => $prasdam_dev) :
					foreach($prasdam_dev as $god) :            
						$qty_in = !empty( $items[$prasadam_id] ) ? $items[$prasadam_id]['qty'] : '-';
						if( empty( $row_in[0] ) ) :
							$row_in[0] = $items[$prasadam_id]['prasadam'];
						endif;
						if( empty( $row_in[1] ) ) :
							$row_in[1] = $items[$prasadam_id]['time'];
						endif;
						$row_in[] = $qty_in;
						$total_in += $qty_in;
					endforeach;
                endforeach;
                $row_in[] = $total_in;
                $body_in[] = $row_in;
            }
			//echo "<pre>"; print_r($row_in);print_r($body_in); exit;
            $args = array(
                'type'      	=> '6', // Default = 1 // Normal (Double print), '2' => Kattalai Archanai,   '3' = Hall Booking | Wedding Hall, '4' => 'Madapalli', '5' => Archanai, '6' => Common
                'rec_no'   	 	=> '',
                'title'     	=> 'Naivedyam Consolidated Report - ' . (date('d/m/Y',strtotime($this->input->post('start_date')))) . ((!empty($this->input->post('period')) && $this->input->post('period') == 1) ? ' (Morning)' : ' (Evening)'),
                'amount'    	=> array(''),
                'copy'      	=> FALSE,
                'data'      	=> array(
                    // Type = 6
						'tables' => array(
							'head'  => $head,
							'body'  => $body,
						),
						
						'in_tables' => array(
							'head'  => $head_indoor,
							'body'  => $body_in,
						),
                ),
            );
            
            
           //echo '<pre>';print_r($args);die;

            print_rec($args);
			
			$data['outdoor_prasadam']		= $this->prasadam_report_model->get_prasadam_records($start_date,$end_date,$period, $service_id = '44');			
			
			//echo "<pre>"; print_r($data['outdoor_prasadam']); exit;
			
			$data['title']					= 'Outdoor Naivedyam Consolidated Report - ' . (date('d/m/Y',strtotime($this->input->post('start_date')))) . ((!empty($this->input->post('period')) && $this->input->post('period') == 1) ? ' (Morning)' : ' (Evening)');
			if($data['outdoor_prasadam']){
				$out_html = $this->load->view('reports/prasadam/outdoor_pdf', $data, TRUE);
				print_rec($out_html, "outdoor_prasadam");  
			}
			
			$data['title']					= 'Distribution Naivedyam Consolidated Report - ' . (date('d/m/Y',strtotime($this->input->post('start_date')))) . ((!empty($this->input->post('period')) && $this->input->post('period') == 1) ? ' (Morning)' : ' (Evening)');
			$data['distripution_prasadam'] 	= $this->prasadam_report_model->get_prasadam_records($start_date,$end_date,$period, $service_id = '169');
			if($data['distripution_prasadam']){
				$dis_html = $this->load->view('reports/prasadam/distripution_pdf', $data, TRUE);
				print_rec($dis_html, "distripution_prasadam");
			}
                
        }
        $data['start_date'] = $start_date;
        $data['end_date'] = $end_date;
        $data['period'] = $period;
        $data['date_type'] = $date_type;
        $actions = $this->actions();
        $data['form_action'] = 'prasadam_report';
        $data['title'] = 'Naivedyam Report';
        
        $filters = array();
        if(!empty($this->input->post('filter_columns'))) {
            foreach($this->input->post('filter_columns') as $key=>$value) {
                array_push($filters,$this->input->post($value));
            } 
        }
        $data['filters'] = array_filter($filters);
        
        if($this->input->post('submit') == 'Chart Data'){			
            $data['dataType'] = $this->input->post('submit');
			$q 							= $this->db->get_where(TBL_SETTINGS_BASIC);
			$data['settings'] 			= $q->row_array();
			$q_des						= $this->db->get_where(TBL_SETTINGS_DESIGN);
            $data['settings'] 			= array_merge($data['settings'], $q_des->row_array());
			$user_data 					= get_session_userdata();
			$_SESSION['pdf_chart']		= "success";
            $_SESSION['pdf_chart_file']	= "prasadam_chart_report.pdf";
			include($_SERVER['DOCUMENT_ROOT'].'/smmt2020/application/views/reports/prasadam/chartpdf.php');      
        } elseif($this->input->post('submit') == 'Print Data'){
            if( IS_KSK ) :
                $html = $this->load->view('reports/prasadam/pdf', $data, TRUE);
                print_rec($html);
                redirect('prasadam_report','refresh');
            else :
                $this->render($data, 'reports/prasadam/pdf');
            endif;
        } elseif($this->input->post('print') == 'Print') {
           redirect('kiosk/index/bill','refresh');
        } elseif(((!empty($this->input->post('submit'))) && ($this->input->post('submit') == 'PDF Data'))) {
		  $data['dataType'] = $this->input->post('submit');
			$user_data 			= get_session_userdata();
			
            if (IS_KSK) :
                $html = $this->load->view('reports/prasadam/pdf', $data, TRUE);
                $args = array();
                if (!is_array($args)) :
                    $is_html = TRUE;
                    $args = array('raw_html' => $args, 'copy' => FALSE);
                endif;
                $type = !empty($args['type']) ? $args['type'] : '1';
                define('IS_SHORT', ($type == '5' || $args['short'] ? TRUE : FALSE));
                define('WIDTH', IS_SHORT ? '287' : '1000'); //'562');
                // $args['is_copy'] = ($type == '1' && !isset($args['copy'])) || $args['copy'] ? TRUE : FALSE;
                $args['is_copy'] = (( $type == '12' || $type == '13' || $type == '14' || $type == '15' || $type == '16' || $type == '17') && !isset($args['copy'])) || $args['copy'] ? TRUE : FALSE;
                $args['sepr'] = '&nbsp;/&nbsp;';
                $q = $this->db->get_where(TBL_SETTINGS_BASIC);
                $args['settings'] = $q->row_array();
                $settings=$args['settings'];
                $q = $this->db->get_where(TBL_SETTINGS_DESIGN);
                $args['settings'] = array_merge($args['settings'], $q->row_array());
//                print_r($args);
               // $header = $this->load->view('templates/print/pdfheader', $args, TRUE);
                $logo_url = !empty($args['settings']['logo']) && file_exists(DIR_COMPANY_LOGO. $args['settings']['logo']) ? DIR_COMPANY_LOGO . $args['settings']['logo'] : 'assets/images/logo.png';
              // $htmlall ='<div class="clear" style="clear:both;height:9em"></div>';
				$search_date=$date;               
                $htmlall ='<table width="100%" style="font-family:Verdana, Geneva, sans-serif">';
                $htmlall .='<tr>';
                $htmlall .=' <td width="5%"><div style="min-width: 115px;">';
                $htmlall .='<img src="'.$logo_url.'" style="width:100px" />';
                $htmlall .='</div></td>';
                $htmlall .=' <td width="80%" align="center">';
                $htmlall .=' <table border="0" width="100%">';
                $htmlall .=' <tr>';
                $htmlall .=' <td width="100%" align="center">';
                $htmlall .=' <span style="float:left;font-family:Arial, Helvetica, sans-serif;font-weight:bold; margin-bottom: 20px;"><span style="font-size:24px;"class="lang-tamil">';
             //   $htmlall .= $settings['tamil_name']; 
                $htmlall .='</span><br/><span style="font-size:20px;">';
                $htmlall .=$settings['temple_name'];
                $htmlall .='</span><br/><span style="font-size:14px;">';
                $htmlall .=$settings['address'];
                $htmlall .='</span><br/><span style="font-size:14px;">';
                $htmlall .='UEN : S75SS0033J | Tel:';
                $htmlall .= $settings['contact_no'];
                $htmlall .='</span><br/><span style="font-size:14px;">';
                $htmlall .=' www.arulmigumurugantemple.com </span>';
                $htmlall .=' <td width="15%">&nbsp;</td>';
             
            
                $htmlall .='</tr>';
                $htmlall .='</table>';
                $htmlall .='</td>';
                $htmlall .='<tr><td colspan="3"><hr></td></tr>';
                $htmlall .='</table>';
                $htmlall .='<table width="100%" border="0" width="100%" cellpadding="5" style="font-family:Verdana, Geneva, sans-serif">';
                $htmlall .='<tr>';
                $htmlall .='<td align="right" width="100%" style="font-size:13px;">';               
				$htmlall .='Printed On:';
                $htmlall .=$user_data['name']."-".date("Y-m-d H:i:s");
                $htmlall .='</td>';
                $htmlall .=' </tr>';
                $htmlall .='<tr>';
               
                $htmlall .='<td align="center" width="80%" style="font-weight:bold; font-size:18px;font-family:Arial, Helvetica, sans-serif;">';
                $htmlall .='Naivedyam Report </td>';
              
                $htmlall .=' </tr>';
                $htmlall .=' </table>';
              
                $html = $this->load->view('reports/prasadam/pdf', $data, TRUE);
                /*
				 if (count($data['nets_results']) > 0 || count($data['cheque_results']) > 0) {
                     $html .=$this->load->view('reports/daily_summary/pdf_nets', $data, TRUE);
                 }
               */
                $htmlall .= $html;
        
                $filename = "prasadam_report_" . date("Y-m-d");
                $pdfFilePath = date('d-m-Y').".pdf";
                $this->load->library('m_pdf');
                $pdf = $this->m_pdf->load();
                $pdf->SetAutoFont(AUTOFONT_ALL);
				//                $pdf->AddPage("L");
				 $pdf->AddPage('L', // L - landscape, P - portrait
				'', '', '', '',
				5, // margin_left
				5, // margin right
				5, // margin top
				5, // margin bottom
				3, // margin header
				3);
            	unlink(FCPATH.'uploads/prasadam_pdf/');
                $pdf->setFooter('{PAGENO}');
              	$pdf->WriteHTML($htmlall);
               	$pdf->Output(FCPATH.'uploads/prasadam_pdf/'.$pdfFilePath, "F");
               	$_SESSION['pdf_prasadam']="success";
               	$_SESSION['pdf_prasadam_file']=$pdfFilePath;
                redirect("prasadam_report","refresh");
                
               //exit(0);
            else :
                $this->render($data, 'reports/prasadam/pdf');
            endif;
        } elseif(((!empty($this->input->post('submit'))) && ($this->input->post('submit') == 'Excel Data'))) {
		    $this->load->view('reports/prasadam/excel', $data);
		} elseif(((!empty($this->input->post('submit'))) && ($this->input->post('submit') == 'View'))) {
		   $this->render($data, 'reports/prasadam/list_view');
        } else {
            $this->render($data, 'reports/prasadam/list');
        }
    }
	
	function uploadchartpdf(){		
		unlink(FCPATH.'uploads/prasadam_pdf/prasadam_chart_report.pdf');
		$filename					= 'pdf';
		$config						= array();
		$config['upload_path'] 		= FCPATH.'uploads/prasadam_pdf/';
		$config['allowed_types'] 	= '*';
		$config['max_size']    		= '15000000';
		$config['file_name']        = "prasadam_chart_report.pdf";
		$this->load->library('upload');
	
		$this->upload->initialize($config);
	
		if(!is_dir($path)){
			@mkdir($path, 0777, true);
		}
	
		if ( ! $this->upload->do_upload($filename)) {
			return "failed";
		} else {
			return "success";
		}
	}
   
} 
?>