<?php

class ControllerReportBalanceSheet extends HController {

    protected function getAlias() {
        return 'report/balance_sheet';
    }

    protected function getDefaultOrder() {
        return 'cao_level1_id';
    }

    protected function getDefaultSort() {
        return 'ASC';
    }

    /*   protected function init() {
           $this->data = $this->load->language($this->getAlias());
           $this->document->setTitle($this->data['heading_title']);
           $this->data['token'] = $this->session->data['token'];
       }*/

    protected function getList() {
        parent::getList();

        $this->data['date_to'] = stdDate();
        $this->data['href_print_report'] = $this->url->link($this->getAlias() .'/printReport', 'token=' . $this->session->data['token'], 'SSL');

        $this->template = $this->getAlias() . '.tpl';
        $this->response->setOutput($this->render());
    }

    public function printReport() {
        $this->init();

        $lang = $this->load->language($this->getAlias());
        $post = $this->request->post;
        $session = $this->session->data;

        $filter = array();
        $filter[] = 'Till Date:'.$post['date_to'];
        $filter[] = 'Case No:'.$post['manual_ref_no'];
        $filter[] = 'Level:'.$post['display_level'];

        $this->model['company']=$this->load->model('setup/company');
        $this->model['company_branch'] = $this->load->model('setup/company_branch');
        $this->model['image'] = $this->load->model('tool/image');

        $company=$this->model['company']->getRow(array('company_id' => $this->session->data['company_id']));
        $company_branch=$this->model['company_branch']->getRow(array('company_id' => $this->session->data['company_id']));
        if(file_exists($session['company_logo'])) {
            $company_image = $session['company_image'];
        } else {
            $company_image = '';
        }

        $this->model['balance_sheet'] = $this->load->model('report/balance_sheet');
        $where = "l.company_id='".$session['company_id']."'";
        $where .= " AND l.company_branch_id='".$session['company_branch_id']."'";
        $where .= " AND l.fiscal_year_id='".$session['fiscal_year_id']."'";
        $where .= " AND l.document_date<='".MySqlDate($post['date_to'])."'";
        if($post['manual_ref_no'] != '') {
            $where .= " AND l.manual_ref_no='".$post['manual_ref_no']."'";
        }

        $rows = $this->model['balance_sheet']->getBalanceSheet($where,array('c.gl_type_id','level1_code','level2_code','level3_code'));
        //d($rows);
        foreach($rows as $row){
            $arrRows[$row['gl_type']][$row['level1_display_name']][$row['level2_display_name']][] = array(
                'level3_display_name' => $row['level3_display_name'],
                'debit' => ($row['balance'] > 0 ? $row['balance'] : 0),
                'credit' => ($row['balance'] < 0 ? (-1 * $row['balance']) : 0),
                'balance' => $row['balance']
            );
        }
        //d(array($this->request->post,$where,$rows,$arrRows),true);
        //d($arrLedger, true);
        $pdf = new PDF('P', PDF_UNIT, 'A4', true, 'UTF-8', false);

        // set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('Huzaifa Khambaty');
        $pdf->SetTitle('Balance Sheet');
        $pdf->SetSubject('Balance Sheet');

        //Set Header
        $pdf->data = array(
            'company_name' => $session['company_name'],
            'report_name' => $lang['heading_title'],
            'company_logo' => $company_image,
            'as_on' => $post['date_to'],
            'filter' => $filter
        );

        // set margins
        //$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetMargins(15, 30, 5);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        // set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

        // add a page
        $pdf->AddPage();
        $total_debit = 0;
        $total_credit = 0;
        $total_balance = 0;
        foreach($arrRows as $gl_type => $level1) {
            $level0_balance = 0;
            $pdf->SetFont('times', 'B', 12);
            $pdf->Cell(20,10,$gl_type,0,0,'L');
            $pdf->ln(10);
            $pdf->SetFont('times', '', 12);
            foreach($level1 as $level1_display_name => $level2) {
                if($post['display_level'] > 1) {
                    $pdf->Cell(10,10,'',0,0,'');
                    $pdf->Cell(170,10,html_entity_decode($level1_display_name),0,0,'');
                    $pdf->ln(10);
                }
                $level1_debit=0;
                $level1_credit=0;
                $level1_total=0;

                foreach($level2 as $level2_display_name => $level3) {
                    if($post['display_level']==3) {
                        $pdf->SetFont('times', 'B', 12);
                        $pdf->Cell(20,10,'',0,0,'');
                        $pdf->Cell(130,10,html_entity_decode($level2_display_name),'TLR',0,'L');
                        $pdf->ln(6);
                    }
                    $level2_debit = 0;
                    $level2_credit = 0;
                    $level2_total = 0;
                    $pdf->SetFont('times', '', 12);
                    foreach($level3 as $record) {
                        if($post['display_level']==3) {
                            $pdf->Cell(10,10,'',0,0,'');
                            $pdf->Cell(10,10,'',0,0,'');
                            $pdf->Cell(10,10,'','L',0,'');
                            $pdf->Cell(90,10,html_entity_decode($record['level3_display_name']),'',0,'L',false,'',1);
                            if($record['balance'] < 0 ) {
                                $pdf->Cell(30,10,'('.number_format(-1*$record['balance'],2).')','R',0,'R');
                            } else {
                                $pdf->Cell(30,10,number_format($record['balance'],2),'R',0,'R');
                            }
                            $pdf->ln(6);
                        }
                        $level2_debit += $record['debit'];
                        $level2_credit += $record['credit'];
                        $level2_total += $record['balance'];

                        $total_debit += $record['debit'];
                        $total_credit += $record['credit'];
                        $total_balance += $record['balance'];
                        $level0_balance += $record['balance'];
                    }
                    if($post['display_level'] > 1) {
                        $pdf->SetFont('times', 'B', 12);
                        if($level2_total < 0) {
                            $level2_total_display = '('.number_format(-1*$level2_total,2).')';
                        } else {
                            $level2_total_display = number_format($level2_total,2);
                        }
                        $pdf->Cell(20,10,'',0,0,'');
                        if($post['display_level'] == 3) {
                            $pdf->Cell(100,10,html_entity_decode($level2_display_name),'BL',0,'L');
                            $pdf->Cell(30,10,$level2_total_display,'BR',0,'R');
                        } else {
                            $pdf->Cell(100,10,html_entity_decode($level2_display_name),'',0,'L');
                            $pdf->Cell(30,10,$level2_total_display,'',0,'R');
                        }
                        $pdf->ln(10);
                    }

                    $level1_debit += $level2_debit;
                    $level1_credit += $level2_credit;
                    $level1_total += $level2_total;
                    $pdf->ln(5);
                }
                $pdf->SetFont('times', '', 12);
                $pdf->Cell(10,10,'',0,0,'');
                $pdf->Cell(130,10,html_entity_decode($level1_display_name),0,0,'L');
                if($level1_total < 0) {
                    $pdf->Cell(30,10,'('.number_format(-1*$level1_total,2).')',0,0,'R');
                } else {
                    $pdf->Cell(30,10,number_format($level1_total,2),0,0,'R');
                }
                $pdf->ln(10);
            }
            $pdf->SetFont('times', 'B', 12);
            $pdf->Cell(140,10,html_entity_decode('Total '.$gl_type),0,0,'L');
            if($level0_balance < 0) {
                $pdf->Cell(30,10,'('.number_format(-1*$level0_balance,2).')',0,0,'R');
            } else {
                $pdf->Cell(30,10,number_format($level0_balance,2),0,0,'R');
            }
            $pdf->ln(10);
        }
        //Close and output PDF document
        $pdf->Output('PL-'.date('YmdHis').'.pdf', 'I');
    }
}

class PDF extends TCPDF {
    public $data = array();

    //Page header
    public function Header() {
        // Logo
//        if($this->data['company_logo'] != '') {
//            $image_file = DIR_IMAGE.$this->data['company_logo'];
//            //$this->Image($file, $x='', $y='', $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0, $fitbox=false, $hidden=false, $fitonpage=false);
//            $this->Image($image_file, 150, 10, 50, '', '', '', 'T', false, 300, '', false, false, 0, false, false, false);
//        }

        $image_file = DIR_IMAGE . "Logo WBA.png";
        $this->Image($image_file, 170, 8, 32, 10, '', '', 'R', false, 300, '', false, false, 1, false, false, false);

        // Set font
        //$this->SetFont('helvetica', 'B', 12);
        $this->Ln(2);
        // Title
        $this->SetFont('helvetica', 'B', 9);
        $this->Cell(60, 7, $this->data['filter'][0], 0, false, 'L', 0, '', 0, false, 'M', 'M');
        $this->SetFont('helvetica', 'B', 12);
        $this->Cell(60, 7, $this->data['company_name'], 0, false, 'C', 0, '', 0, false, 'M', 'M');
        $this->Ln(7);
        $this->SetFont('helvetica', 'B', 9);
        $this->Cell(60, 7, $this->data['filter'][1], 0, false, 'L', 0, '', 0, false, 'M', 'M');
        $this->SetFont('helvetica', 'B', 12);
        $this->Cell(60, 7, $this->data['report_name'], 0, false, 'C', 0, '', 0, false, 'M', 'M');
        $this->Ln(7);
        $this->SetFont('helvetica', 'B', 9);
        $this->Cell(60, 7, $this->data['filter'][2], 0, false, 'L', 0, '', 0, false, 'M', 'M');
        $this->SetFont('helvetica', 'B', 10);
        $this->Cell(60, 7, 'As on '.$this->data['as_on'], 0, false, 'C', 0, '', 0, false, 'M', 'M');
    }

    // Page footer
    public function Footer() {
        // Position at 15 mm from bottom
        $this->SetY(-15);
        // Set font
        $this->SetFont('helvetica', 'I', 8);
        // Page number
        $this->Cell(0, 10, 'Page '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
    }
}

?>