<?php
/*ini_set('display_errors', 1);
error_reporting(E_ALL);*/
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Daily_summary_report extends REF_Controller {
    public function __construct() {
        parent::__construct();
		$this->load->helper(array('form', 'url'));
        $this->load->library('upload');
        $this->load->model('reports/daily_summary_model', '', TRUE);
        $this->load->model('general_settings_model', '', TRUE);
        $this->uri_key_index = 0;
    }
    
    public function index() {   //echo '<pre>';print_r($_POST);die;
        $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 Summary Data' || $this->input->post('submit') == 'Pdf Summary Data' || $this->input->post('submit') == 'Excel Summary Data' || $this->input->post('submit') == 'Get Details Data' || $this->input->post('submit') == 'Print Details Data' || $this->input->post('submit') == 'Pdf Details Data' || $this->input->post('submit') == 'Excel Details Data' || $this->input->post('submit') == 'Submit' || $this->input->post('submit') == 'Chart Summary Data' || $this->input->post('submit') == 'Chart Details Data')) {
            $date = $this->input->post('search_date');
            $data_type = ($this->input->post('submit') != 'Submit') ? $this->input->post('submit') : 'Get Summary Data';
            $abishegam = $this->daily_summary_model->get_abishegam_data($date,$data_type);
	    	$homam = $this->daily_summary_model->get_homam_data($date,$data_type);
            $festival = $this->daily_summary_model->get_festival_data($date,$data_type);
            $ubayam = $this->daily_summary_model->get_ubayam_data($date,$data_type);
            $mega = $this->daily_summary_model->get_mega_data($date,$data_type);
            $other = $this->daily_summary_model->get_other_service_data($date,$data_type);
            $gold_silver = $this->daily_summary_model->get_gold_silver_data($date,$data_type);
            $temple = $this->daily_summary_model->get_temple_activity_data($date,$data_type);
            $member_subscripe = $this->daily_summary_model->get_member_subscribe_data($date,$data_type);
            $building_fund  = $this->daily_summary_model->get_building_fund_data($date,$data_type);
            $outdoor = $this->daily_summary_model->get_outdoor_data($date,$data_type);
            $prasadam = $this->daily_summary_model->get_prasadam_data($date,$data_type);
            $madappalli = $this->daily_summary_model->get_madappalli_data($date,$data_type);
            $donation = $this->daily_summary_model->get_donation_data($date,$data_type);
            $hall_booking = $this->daily_summary_model->get_hall_booking_data($date,$data_type);
            $wedding_hall = $this->daily_summary_model->get_wed_hall_booking_data($date,$data_type);
            $archanai = $this->daily_summary_model->get_archanai_data($date,$data_type);
            $kattalai = $this->daily_summary_model->get_kattalai_data($date,$data_type);
            $membership = $this->daily_summary_model->get_membership_data($date,$data_type);
            $card_topup = $this->daily_summary_model->get_membership_card_topup_data($date,$data_type);
            $temple_shop = $this->daily_summary_model->get_temple_shop_data($date,$data_type);
			//$building_fund_daily = $this->daily_summary_model->get_building_fund_daily($date,$data_type);
            
        } elseif($this->input->post('print') == 'Print' || $this->input->post('submit') == 'Print Summary Data') {
                $date = $this->input->post('search_date');
                $data_type = 'Get Summary Data';
                $abishegam = $this->daily_summary_model->get_abishegam_data($date,$data_type);
				$homam = $this->daily_summary_model->get_homam_data($date,$data_type);
                $festival = $this->daily_summary_model->get_festival_data($date,$data_type);
                $ubayam = $this->daily_summary_model->get_ubayam_data($date,$data_type);
                $mega = $this->daily_summary_model->get_mega_data($date,$data_type);
                $other = $this->daily_summary_model->get_other_service_data($date,$data_type);
                $gold_silver = $this->daily_summary_model->get_gold_silver_data($date,$data_type);
                $temple = $this->daily_summary_model->get_temple_activity_data($date,$data_type);
                $member_subscripe = $this->daily_summary_model->get_member_subscribe_data($date,$data_type);
                $building_fund  = $this->daily_summary_model->get_building_fund_data($date,$data_type);
                $outdoor = $this->daily_summary_model->get_outdoor_data($date,$data_type);
                $prasadam = $this->daily_summary_model->get_prasadam_data($date,$data_type);
                $madappalli = $this->daily_summary_model->get_madappalli_data($date,$data_type);
                $donation = $this->daily_summary_model->get_donation_data($date,$data_type);
                $hall_booking = $this->daily_summary_model->get_hall_booking_data($date,$data_type);
                $wedding_hall = $this->daily_summary_model->get_wed_hall_booking_data($date,$data_type);
                $archanai = $this->daily_summary_model->get_archanai_data($date,$data_type);
                $kattalai = $this->daily_summary_model->get_kattalai_data($date,$data_type);
                $membership = $this->daily_summary_model->get_membership_data($date,$data_type);
                $card_topup = $this->daily_summary_model->get_membership_card_topup_data($date,$data_type);
                $temple_shop = $this->daily_summary_model->get_temple_shop_data($date,$data_type);

                $results = array_merge($abishegam,$archanai,$building_fund,$donation,$festival,$gold_silver,$hall_booking,$homam,$kattalai,$madappalli,$mega,$member_subscripe,$membership,$card_topup,$outdoor,$other,$prasadam,$temple,$temple_shop,$ubayam,$wedding_hall);
               
                $general = $this->general_settings_model->get_by_id();
                
                $body = array();
                $total_amt  = 0;
                $jj			= 0;
                foreach($results as $key=>$value) {
                   #$total_amt += $value['amount'];
                    $jo = ++$jj;
                   //Refund Amount
                    $Refund = $this->daily_summary_model->get_refund_amt_by_ids($value['type_id'],$value['service_id'],$value['id'],$date);
                  
                    if(!empty($Refund)) {
                        $recentAmt = $value['amount'] - $Refund;
                    }
                    else {
                       $recentAmt = $value['amount'];
                    }
                    
                    $total_amt += $recentAmt;
                    if(!empty($value['gst'])) {
                        $AmtwithGst = $recentAmt * ($value['gst'] / 100);
                    } else {
                        $AmtwithGst = 0;
                    }
                                                
                   $gst = (!empty($value['amount'])) ? number_format($recentAmt - $AmtwithGst,2,'.','') : '0.00';
                   $gst_amt = (!empty($value['gst'])) ? number_format($AmtwithGst,2,'.','') : '0.00';
                   //$body[] = array($value['rec_no'], $value['name'], $value['qty'], $value['price'], (($general->gst > 0) ? $gst,$gst_amt,number_format($recentAmt,2,'.','') : number_format($recentAmt,2,'.','')) );
                    if($general->gst > 0) {
                        $body[] = array($jo, $value['rec_no'], $value['name'], $value['qty'], $value['price'], '<span style="float: right;">' . $gst . '</span>', '<span style="float: right;">' . $gst_amt . '</span>','<span style="float: right;">' . number_format($recentAmt,2,'.','') . '</span>');
                    } else {
                        $body[] = array($jo, $value['rec_no'], $value['name'], $value['qty'], $value['price'], '<span style="float: right;">' . number_format($recentAmt,2,'.','') . '</span>');  
                    }
                   
                }
                
                
                $sub_body = $this->get_sub_body( $date );
                $sub_body[] = array('Total ' .(($general->gst > 0) ? '(with GST)' : '' ),  number_format(($total_amt),2,'.','')); 
				
				$footer_cnt	= '<div style="width: 100%; float: right;">
                                <div style="float: left; clear: both; width:33.3%;">
                                    <div>&nbsp;</div>
                                    <div>&nbsp;</div>
                                    <div>&nbsp;</div>
                                    <div><b style="font-size: 15px;">Verified By</b></div>
                                    <div>&nbsp;</div>
                                    <div>&nbsp;</div>
                                    <div>&nbsp;</div>
                                    <div>-----------------------------------------</div>
                               </div>
                               <div style="float: left; width:33.3%;">
                                    <div>&nbsp;</div>
                                    <div>&nbsp;</div>
                                    <div>&nbsp;</div>
                                    <div><b style="font-size: 15px;">Approved By</b></div>
                                    <div>&nbsp;</div>
                                    <div>&nbsp;</div>
                                    <div>&nbsp;</div>
                                    <div>-----------------------------------------</div>
                               </div>
                               <div style="float: left; width:33.3%;">
                                    <div>&nbsp;</div>
                                    <div>&nbsp;</div>
                                    <div>&nbsp;</div>
                                    <div><b style="font-size: 15px;">Confirmed By</b></div>
                                    <div>&nbsp;</div>
                                    <div>&nbsp;</div>
                                    <div>&nbsp;</div>
                                    <div>-----------------------------------------</div>
                               </div>
                           </div>';
				
				/*$sub_body = array();
				$sub_body[] = array('Total ' .(($general->gst > 0) ? '(with GST)' : '' ),  number_format(($total_amt),2,'.',''));
				$pay_detls = $this->get_sub_body( $date );
				$sub_body = array_merge($sub_body,$pay_detls);*/
                
                $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'     => 'Daily Summary Report - ' . (date('d/m/Y',strtotime($date))) ,//$main_service['service_name']. ' - '.$service['name'],
		    		'title'     => 'Daily Summary Report<br>Date: ' . date('d-m-Y',strtotime($date)) .' - '. ucfirst(date('l',strtotime($date))),
                    'amount'    => array(''),
                    'copy'      => FALSE,
					'footer_txt'=> $footer_cnt,
                    
                    'data'      => array(
                        // Type = 6
                        'tables' => array(
                            #'head'  => array('Receipt No', 'Name', 'Quantity', 'Unit Price',(($general->gst > 0) ? ('Before GST', 'GST Amount', 'Total') : 'Total')),
                            'head'  => array('S.No', 'Receipt No', 'Name', 'Qty', 'Unit Price',(($general->gst > 0) ? 'Before GST' : ''), (($general->gst > 0) ? 'GST Amount' : ''), 'Total'),
                            'body'  => $body,
                        ),
                   
                        'sub_tables' => array(
                            'head'  => array(''),
                            'body'  => $sub_body,
                        ),
                    ),
                );
                
                //echo '<pre>';print_r($args);die;
                print_rec($args); 
        } else  {
            $date = '';
            $data_type = 'Get Summary Data';
            $abishegam = $this->daily_summary_model->get_abishegam_data($date = '',$data_type);
			$homam = $this->daily_summary_model->get_homam_data($date = '',$data_type);
            $festival = $this->daily_summary_model->get_festival_data($date = '',$data_type);
            //error_log($this->db->last_query());
            $ubayam = $this->daily_summary_model->get_ubayam_data($date = '',$data_type);
            $mega = $this->daily_summary_model->get_mega_data($date = '',$data_type);
            $other = $this->daily_summary_model->get_other_service_data($date = '',$data_type);
            $gold_silver = $this->daily_summary_model->get_gold_silver_data($date = '',$data_type);
            $temple = $this->daily_summary_model->get_temple_activity_data($date = '',$data_type);
            $member_subscripe = $this->daily_summary_model->get_member_subscribe_data($date = '',$data_type);
            $building_fund  = $this->daily_summary_model->get_building_fund_data($date = '',$data_type);
            $outdoor = $this->daily_summary_model->get_outdoor_data($date = '',$data_type);
            $prasadam = $this->daily_summary_model->get_prasadam_data($date = '',$data_type);
            $madappalli = $this->daily_summary_model->get_madappalli_data($date = '',$data_type);
            $donation = $this->daily_summary_model->get_donation_data($date = '',$data_type);
            $hall_booking = $this->daily_summary_model->get_hall_booking_data($date = '',$data_type);
            $wedding_hall = $this->daily_summary_model->get_wed_hall_booking_data($date= '',$data_type);
            $archanai = $this->daily_summary_model->get_archanai_data($date= '',$data_type);
            $kattalai = $this->daily_summary_model->get_kattalai_data($date= '',$data_type);
            $membership = $this->daily_summary_model->get_membership_data($date= '',$data_type);
            $card_topup = $this->daily_summary_model->get_membership_card_topup_data($date= '',$data_type);
            $temple_shop = $this->daily_summary_model->get_temple_shop_data($date= '',$data_type);
        }
        
        $data['results'] 		= array_merge($abishegam,$archanai,$building_fund,$donation,$festival,$gold_silver,$hall_booking,$homam,$kattalai,$madappalli,$mega,$member_subscripe,$membership,$card_topup,$outdoor,$other,$prasadam,$temple,$temple_shop,$ubayam,$wedding_hall);
		
		//echo "<pre>"; print_r($abishegam); exit;
		
		//$data['building_fund'] 	= $building_fund_daily;
        #echo '<pre>';print_r($data['results']);die;
        /*
         * Tally Operation
         */
        if( ($this->input->post('submit') == 'Print Summary Data' || $this->input->post('print') == 'Print') && !empty( $data['results'] ) ) :
            if( $this->input->post('submit') == 'Print Summary Data' ) :
                 $sub_body = $this->get_sub_body( $date );
            else :
                // Remove Total
                unset($sub_body[count($sub_body)-1]);
            endif;
            
            $tally_results = array_merge( $data['results'], $sub_body );
            $this->daily_summary_model->tally( $tally_results, $date );
        endif;
        
        //error_log(print_r($data['results'],1));
        $data['search_date'] = $date;
        $data['type'] = $data_type;
        $data['mode'] = $this->daily_summary_model->payment_type_list();
        $actions = $this->actions();
        $data['form_action'] = 'daily_summary_report';
        $data['title'] = 'Daily Summary Report';
		$data['pdftype'] = '';
		$data['exceltype'] = '';
		$data['charttype'] = '';
		
		if($this->input->post('submit') == 'Get Summary Data'  || $this->input->post('submit') == 'Print Summary Data'){
			$data['pdftype'] 	= 'Pdf Summary Data';
			$data['exceltype'] 	= 'Excel Summary Data';
			$data['charttype'] 	= 'Chart Summary Data';
		}
		elseif($this->input->post('submit') == 'Get Details Data' || $this->input->post('submit') == 'Print Details Data'){
			$data['pdftype'] 	= 'Pdf Details Data';	
			$data['exceltype'] 	= 'Excel Details Data';
			$data['charttype'] 	= 'Chart Details Data';
		}else{
			$data['pdftype'] 	= 'Pdf Summary Data';
			$data['exceltype'] 	= 'Excel Summary Data';
			$data['charttype'] 	= 'Chart Summary Data';
		}
		
        
        $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 Summary Data' || $this->input->post('submit') == 'Chart Details 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();
			
			//echo "<pre>"; print_r($data); exit;
			$_SESSION['pdf_chart']		= "success";
            $_SESSION['pdf_chart_file']	= "daily_chart_summary_report.pdf";
			include($_SERVER['DOCUMENT_ROOT'].'/smmt/application/views/reports/daily_summary/chartpdf.php');
        } else if($this->input->post('submit') == 'Print Details Data' ){   //$this->input->post('submit') == 'Print Summary Data' || 
            $data['dataType'] = $this->input->post('submit');
            if( IS_KSK ) :
                $html = $this->load->view('reports/daily_summary/pdf', $data, TRUE);
                print_rec($html);
                redirect('daily_summary_report','refresh');
            else :
                $this->render($data, 'reports/daily_summary/pdf');
            endif;
        } else if ($this->input->post('submit') == 'Pdf Summary Data' || $this->input->post('submit') == 'Pdf Details Data') {
            $data['dataType'] 	= $this->input->post('submit');
			$user_data 			= get_session_userdata();
            if (IS_KSK) :
                $html = $this->load->view('reports/daily_summary/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());
                //echo "<pre>"; print_r($args); exit;
				//echo FCPATH.DIR_COMPANY_LOGO. $args['settings']['logo'];
               // $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 align="center" style="font-size:14px;">';
                $htmlall .=$settings['temple_name'];
                $htmlall .='</tr>';
                $htmlall .='</table>';
                $htmlall .='</td>';
                $htmlall .='<tr><td colspan="3"><hr></td></tr>';
                $htmlall .='</table>';
                $htmlall .='<table width="100%" border="0" cellpadding="5" style="font-family:Verdana, Geneva, sans-serif">';
                $htmlall .='<tr>';
                $htmlall .='<td width="25%">&nbsp;</td>';
                $htmlall .='<td align="center" width="50%" style="font-weight:bold; font-size:14px;">';
                $htmlall .='Daily Summary Report'. ' - '. date('d/m/Y', strtotime($search_date));
                $htmlall .='<td width="25%" style="font-size:13px;">';
				$htmlall .='Printed On:';
                $htmlall .=$user_data['name']."-".date("Y-m-d H:i:s");
                $htmlall .='</td>';
                $htmlall .=' </tr>';
                $htmlall .=' </table>';
                                  
                $html = $this->load->view('reports/daily_summary/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 = "daily_summary_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/daily_pdf/');
                $pdf->setFooter('{PAGENO}');
              	$pdf->WriteHTML($htmlall);
               	$pdf->Output(FCPATH.'uploads/daily_pdf/'.$pdfFilePath, "F");
               	$_SESSION['pdf_daily']="success";
               	$_SESSION['pdf_daily_file']=$pdfFilePath;
                redirect("daily_summary_report","refresh");
                
               //exit(0);
            else :
                $this->render($data, 'reports/daily_summary/pdf');
            endif;
        } elseif($this->input->post('print') == 'Print') {
           redirect('kiosk/index/bill','refresh');
        } elseif(((!empty($this->input->post('submit'))) && ($this->input->post('submit') == 'Excel Summary Data' || $this->input->post('submit') == 'Excel Details Data'))) {
		    $this->load->view('reports/daily_summary/excel', $data);
        } else {
            $this->render($data, 'reports/daily_summary/list');
        }
    }
    
    function get_sub_body( $date ) {
        
        $sub_body = array();
        $mode = $this->daily_summary_model->payment_type_list();
        
        $refundAmount = $this->daily_summary_model->get_refund_amount($date);
        //$sub_body[] = array('Refund Amount',  number_format(($refundAmount),2,'.',''));

        foreach($mode as $key=>$value) {
            $paidAmount = $this->daily_summary_model->get_total_paid_amt_by_type($value->id,$date);
            if($value->payment_mode == 'cash') { 
                $refundAmt = $this->daily_summary_model->get_refund_amount($date);
            } else { 
                $refundAmt = '0.00';
            }

            $Amount = (!empty($paidAmount->amount)) ? (($value->payment_mode == 'cash') ? number_format($paidAmount->amount - $refundAmt,2,'.','') :  $paidAmount->amount ) : '0.00';

            $sub_body[] = array(ucfirst($value->name), $Amount);
        }
        
        return $sub_body;
    }
	
	function uploadchartpdf(){		
		unlink(FCPATH.'uploads/daily_pdf/daily_chart_summary_report.pdf');
		$filename					= 'pdf';
		$config						= array();
		$config['upload_path'] 		= FCPATH.'uploads/daily_pdf/';
		$config['allowed_types'] 	= '*';
		$config['max_size']    		= '15000000';
		$config['file_name']        = "daily_chart_summary_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";
		}
	}
   
} 
?>