<?php

if (!defined('BASEPATH')

    )exit('No direct script access allowed');

class Closecash extends MY_Controller {

    function __construct() {
        parent::__construct();
        $this->load->library('Formatslist');
    }

    private function _gethostsequence($id = NULL) {
        $this->load->model('payment/payment_model');
        $catarr = $this->payment_model->gethostsequence();
        $data = '<option value="">Select</option>';
        for ($i = 0; $i < count($catarr); $i++) {
            if ($id != NULL && $id == $catarr[$i]->HOSTSEQUENCE)
                $data .= "<option id=\"option_custom\" selected=\"yes\" value=\"" . $catarr[$i]->HOSTSEQUENCE . "\">" . $catarr[$i]->HOSTSEQUENCE . "</option>\n";
            else
                $data .= "<option id=\"option_custom\" value=\"" . $catarr[$i]->HOSTSEQUENCE . "\">" . $catarr[$i]->HOSTSEQUENCE . "</option>\n";
        }
        return $data;
    }

    public function index() {
        $data['hostsequence'] = $this->_gethostsequence();
         $data['template'] = 'sales/closecash_view';
        $this->load->view('template',$data);
    }

// MATERIALREQUESTS LIST FOR  MANAGE
    public function getclosecash() {
        $aColumns = array( 'sl', 'HOST','HOSTSEQUENCE','DATESTART','DATEEND','TOTAL');
	// set limit
	$sLimit = "";
	if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
		$sLimit = "LIMIT " . $_GET['iDisplayStart'] . ", " . $_GET['iDisplayLength'];
	}
	//Ordering
	if (isset($_GET['iSortCol_0'])) {
		$sOrder = " ORDER BY ";
		for ($i = 0; $i < intval($_GET['iSortingCols']); $i++) {
			if ($_GET['bSortable_'.intval($_GET['iSortCol_'.$i])] == "true") {
				if ($aColumns[intval($_GET['iSortCol_'.$i])] != 'sl') {
					$sOrder .= $aColumns[intval($_GET['iSortCol_'.$i])]."
						".$_GET['sSortDir_' . $i].", ";
				}else{
					$sOrder.=    "DATESTART DESC  ";
				}
			}
		}
		$sOrder = substr_replace($sOrder, "", -2);
		if ($sOrder == "ORDER BY") {
				$sOrder = "";
		}
	}
	/*
	 * Filtering
	 */
	$sWhere = "";
	if ($_GET['sSearch'] != "") {
		$sWhere = "WHERE (";
		for ($i = 1; $i < 6; $i++) {
			if ($aColumns[$i] == 'HOST') {
                            $aColumns[$i] = 'HOST';
                        }else if($aColumns[$i] == 'HOSTSEQUENCE'){
                            $aColumns[$i] = 'HOSTSEQUENCE';
                        }else if($aColumns[$i] == 'DATESTART'){
                            $aColumns[$i] = 'DATESTART';
                        }else if($aColumns[$i] == 'DATEEND'){
                            $aColumns[$i] = 'DATEEND';
                        }else if($aColumns[$i] == 'TOTAL'){
                            $aColumns[$i] = 'TOTAL';
			}
			$sWhere .= $aColumns[$i] . " LIKE '%" . $_GET['sSearch'] . "%' OR ";
		}
		$sWhere = substr_replace($sWhere, "", -3);
		$sWhere .= ')';
	}
	// get data
	$order = str_replace("ORDER BY", '', $sOrder);
	$limit = ' ' . $sLimit;
	if ($sWhere != '') {
            $where = ' AND ';
            $where .= str_replace("WHERE", '', $sWhere);
	} else {
            $where = '';
	}
        $datequery  =   "";
        if($_GET["filter_begin"]) {
            $datequery  =   $datequery." AND CLOSEDCASH.DATESTART>='".date("Y-m-d H:i:s",strtotime($_GET["filter_begin"]." 00:00"))."'";
        }
        if($_GET["filter_end"]) {
            $datequery  =   $datequery." AND CLOSEDCASH.DATESTART<='".date("Y-m-d H:i:s",strtotime($_GET["filter_end"]." 23:59:59"))."'";
        }
	$sql = "SELECT `CLOSEDCASH`.`MONEY` AS `ID`, `CLOSEDCASH`.`HOST`, "
            . "`CLOSEDCASH`.`HOSTSEQUENCE`, `CLOSEDCASH`.`DATESTART`, `CLOSEDCASH`.`DATEEND`,"
            . " SUM(PAYMENTS.TOTAL) AS TOTAL FROM `CLOSEDCASH`"
            . " LEFT JOIN `RECEIPTS` ON `RECEIPTS`.`MONEY` = `CLOSEDCASH`.`MONEY`"
            . " LEFT JOIN `PAYMENTS` ON `PAYMENTS`.`RECEIPT` = `RECEIPTS`.`ID`";
	$sql.= " WHERE 1 " . $where .$datequery. " GROUP BY `CLOSEDCASH`.`MONEY`" . $sOrder . $limit;
        
//        echo $sql;exit;
        
	$arr = $this->common->customquery($sql);
	$totalCount_sql = "SELECT count(*) AS total FROM (SELECT `CLOSEDCASH`.`MONEY` AS `ID`, `CLOSEDCASH`.`HOST`, `CLOSEDCASH`.`HOSTSEQUENCE`, `CLOSEDCASH`.`DATESTART`, `CLOSEDCASH`.`DATEEND`, SUM(PAYMENTS.TOTAL) AS TOTAL
            FROM `CLOSEDCASH` LEFT JOIN `RECEIPTS` ON `RECEIPTS`.`MONEY` = `CLOSEDCASH`.`MONEY` LEFT JOIN `PAYMENTS` ON `PAYMENTS`.`RECEIPT` = `RECEIPTS`.`ID` GROUP BY `CLOSEDCASH`.`MONEY`) AS mytable";
	$totalCount_sql .= " WHERE 1 ";
	$totalCount = $this->common->customquery($totalCount_sql);
	$iTotal = $totalCount[0]->total;
	/*
	 * Output
	 */
	$output = array(
		"sEcho" => intval($_GET['sEcho']),
		"iTotalRecords" => $iTotal,
		"iTotalDisplayRecords" => $iTotal,
		"aaData" => array()
	);
	$j = $_GET['iDisplayStart']+1;
	if ($arr != '') {
		foreach ($arr as $key => $aRow) {
			$row = array();
//			$row[0] = $key + 1;
			$row[0] = $aRow->HOST;
			$row[1] = $aRow->HOSTSEQUENCE;
			$row[2] = $this->formatslist->datetimeFormat($aRow->DATESTART);
                        if($aRow->DATEEND)
                            $row[3] = $this->formatslist->datetimeFormat($aRow->DATEEND);
                        else
                            $row[3] = '';
			$row[4] = $this->formatslist->formatCurrencywithHash($aRow->TOTAL);
			$row[5] = $aRow->ID;
			$output['aaData'][] = $row;
			$j++;
		}
	} else {
		//
	}
	echo json_encode($output);
//        $this->load->model('sales/closecash_model');
//        $data['data'] =  $this->closecash_model->getclosecash();
//        echo json_encode($data);
        
    }
    public function getclosecashdetails2() {
        $this->load->library('session');
        $this->session->set_userdata('idlist',  $this->input->post('idlist'));
        return 1;
    }
    // RECEIPT DETAILS
    public function getclosecashdetails($idlistvalue) {
        $this->load->library('session');
        $ids = $idlistvalue;
        $this->load->model('sales/closecash_model');
        $data['receipt'] = $this->closecash_model->getreceiptlinesbyparam($this->uri->segment(3));
        $data['ticketlines'] = $this->closecash_model->getticketlinesbyparam($this->uri->segment(3));
        $data['paymentlines'] = $this->closecash_model->getpaymentlinesbyparam($this->uri->segment(3));
        $data['closedcashdetails'] = $this->closecash_model->getclosedcashdetails($ids);
        $data['closedcashamount'] = $this->closecash_model->getclosedcashamount($ids, 'cash', '', '', '', '', '', '', '', '', '', '');
        $data['closedcashamount'] = $this->closecash_model->getclosedcashamount($ids, 'cash', '', '', '', '', '', '', '', '', '', '');
        $data['closedcashinamount'] = $this->closecash_model->getclosedcashamount($ids, '', 'cashin', '', '', '', '', '', '', '', '', '');
        $data['closedcashoutamount'] = $this->closecash_model->getclosedcashamount($ids, '', '', 'cashout', '', '', '', '', '', '', '', '');
        $data['closedcacashcreditpaidamount'] = $this->closecash_model->getclosedcashamount($ids, '', '', '', 'cashcreditpaid', '', '', '', '', '', '', '');
        $data['closeddebtamount'] = $this->closecash_model->getclosedcashamount($ids, '', '', '', '', 'debt', '', '', '', '', '', '');
        $data['closedcreditpaidamount'] = $this->closecash_model->getclosedcashamount($ids, '', '', '', '', '', 'creditpaid', '', '', '', '', '');
        $data['closeddebtpaidamount'] = $this->closecash_model->getclosedcashamount($ids, '', '', '', '', '', 'debtpaid', '', '', '', '', '');
        $data['closedchequeamount'] = $this->closecash_model->getclosedcashamount($ids, '', '', '', '', '', '', 'cheque', '', '', '', '');
        $data['closedcardamount'] = $this->closecash_model->getclosedcashamount($ids, '', '', '', '', '', '', '', 'magcard', '', '', '');
        $data['closedfreeamount'] = $this->closecash_model->getclosedcashamount($ids, '', '', '', '', '', '', '', '', 'free', '', '');
        $data['closedrefundamount'] = $this->closecash_model->getclosedcashamount($ids, '', '', '', '', '', '', '', '', '', 'cashrefund', '');
        $data['closedonlineamount'] = $this->closecash_model->getclosedcashamount($ids, '', '', '', '', '', '', '', '', '', '', 'online');
        $data['receiptscount'] = $this->closecash_model->getreceiptscount($ids);
        $data['paymentscount'] = $this->closecash_model->getpaymentscount($ids);
        $data['total'] = $this->closecash_model->gettotal($this->uri->segment(3));
        $data['chequepayments'] = $this->closecash_model->getchequedetails($this->uri->segment(3));
        $data['taxdetails'] = $this->closecash_model->gettaxdetails($this->uri->segment(3));
        $data['debtsaledetails'] = $this->closecash_model->getdebtsaledetails($this->uri->segment(3));
        $data['debtpaiddetails'] = $this->closecash_model->getdebtpaiddetails($this->uri->segment(3));
        $data['salereport'] = $this->closecash_model->getsalereport($this->uri->segment(3));
        $data['salereturnreport'] = $this->closecash_model->getsalereturnreport($this->uri->segment(3));
        $data['company_det'] = $this->companyinfo_model->getcompanyinfo('0');
        $data['template'] = 'sales/closecash_details_view';
        
        $this->load->view('template',$data);
    }

    function printcc($idlistvalue) {
        $this->load->library('session');
        $this->load->helper('dompdf');
        $this->load->helper('file');
        $this->load->library('session');
        $ids = $idlistvalue;
        $this->load->model('sales/closecash_model');
        $data['receipt'] = $this->closecash_model->getreceiptlinesbyparam($this->uri->segment(3));
        $data['ticketlines'] = $this->closecash_model->getticketlinesbyparam($this->uri->segment(3));
        $data['paymentlines'] = $this->closecash_model->getpaymentlinesbyparam($this->uri->segment(3));
        $data['closedcashdetails'] = $this->closecash_model->getclosedcashdetails($ids);
        
        $data['closedcashamount'] = $this->closecash_model->getclosedcashamount($ids, 'cash', '', '', '', '', '', '', '', '', '', '');
        $data['closedcashamount'] = $this->closecash_model->getclosedcashamount($ids, 'cash', '', '', '', '', '', '', '', '', '', '');
        $data['closedcashinamount'] = $this->closecash_model->getclosedcashamount($ids, '', 'cashin', '', '', '', '', '', '', '', '', '');
        $data['closedcashoutamount'] = $this->closecash_model->getclosedcashamount($ids, '', '', 'cashout', '', '', '', '', '', '', '', '');
        $data['closedcacashcreditpaidamount'] = $this->closecash_model->getclosedcashamount($ids, '', '', '', 'cashcreditpaid', '', '', '', '', '', '', '');
        $data['closeddebtamount'] = $this->closecash_model->getclosedcashamount($ids, '', '', '', '', 'debt', '', '', '', '', '', '');
        $data['closedcreditpaidamount'] = $this->closecash_model->getclosedcashamount($ids, '', '', '', '', '', 'creditpaid', '', '', '', '', '');
        $data['closeddebtpaidamount'] = $this->closecash_model->getclosedcashamount($ids, '', '', '', '', '', 'debtpaid', '', '', '', '', '');
        $data['closedchequeamount'] = $this->closecash_model->getclosedcashamount($ids, '', '', '', '', '', '', 'cheque', '', '', '', '');
        $data['closedcardamount'] = $this->closecash_model->getclosedcashamount($ids, '', '', '', '', '', '', '', 'magcard', '', '', '');
        $data['closedfreeamount'] = $this->closecash_model->getclosedcashamount($ids, '', '', '', '', '', '', '', '', 'free', '', '');
        $data['closedrefundamount'] = $this->closecash_model->getclosedcashamount($ids, '', '', '', '', '', '', '', '', '', 'cashrefund', '');
        $data['closedonlineamount'] = $this->closecash_model->getclosedcashamount($ids, '', '', '', '', '', '', '', '', '', '', 'online');
        
        $data['receiptscount'] = $this->closecash_model->getreceiptscount($ids);
        $data['paymentscount'] = $this->closecash_model->getpaymentscount($ids);
        $data['total'] = $this->closecash_model->gettotal($this->uri->segment(3));
        $data['chequepayments'] = $this->closecash_model->getchequedetails($this->uri->segment(3));
        $data['taxdetails'] = $this->closecash_model->gettaxdetails($this->uri->segment(3));
        $data['debtsaledetails'] = $this->closecash_model->getdebtsaledetails($this->uri->segment(3));
        $data['debtpaiddetails'] = $this->closecash_model->getdebtpaiddetails($this->uri->segment(3));
        $data['salereport'] = $this->closecash_model->getsalereport($this->uri->segment(3));
        $data['salereturnreport'] = $this->closecash_model->getsalereturnreport($this->uri->segment(3));
        $data['companyinfo'] = $this->companyinfo_model->getcompanyinfo('0');
        $html = $this->load->view('sales/closecash_print', $data, true);
        $this->load->library('Pdf');
        $pdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
        $pdf->SetMargins(10, 10, 10, true);
        $pdf->SetCreator('Saleculator');
        $pdf->SetAuthor('Shameer C K');
        if ($data['closedcashdetails'][0]->DATEEND == NULL) {
            $reporttitle   =    "Partial Cash Report";
        } else {
            $reporttitle   =    "Close Cash Report";
        }
        $pdf->SetTitle($reporttitle);
        $pdf->SetSubject($reporttitle);
        $pdf->SetHeaderData(K_BLANK_IMAGE, PDF_HEADER_LOGO_WIDTH, $data['companyinfo']->COMPANYNAME."#".$reporttitle, $data['companyinfo']->ADDRESS1."\nPhone: ".$data['companyinfo']->PHONE1."\n".$data['companyinfo']->EMAIL.', '.$data['companyinfo']->WEBSITE."\nTax Id: ".$data['companyinfo']->TAXID);
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
        $pdf->SetFont('helvetica', '', 12);
        $pdf->AddPage();
        $pdf->writeHTML($html, true, false, true, false, '');
        $pdf->lastPage();
        $pdf->Output('COLSEDCASH.pdf', 'I');
    }
    
    
    
    // RECEIPT LOGO
    public function getlogo() {
        $this->load->model('sales/sales_model');
        $logo = $this->sales_model->getReceiptLogo();
        header('Content-Type: image/png');
        echo $logo[0]->CONTENT;
    }

    // RECEIPT HEADER
    public function getLines() {
        $this->load->model('sales/sales_model');
        $line = $this->sales_model->getHeaderLines();
        header('Content-Type: text');
        echo $line[0]->CONTENT;
    }
    public function getcashsequenceautocomplete() {
        $term = $this->input->post('term', TRUE);
        $this->load->model('sales/closecash_model');
        $rows = $this->closecash_model->getcashsequenceautocomplete($term);

        $keywords = array();
        foreach ($rows as $row)
            array_push($keywords, $row->HOSTSEQUENCE);

        echo json_encode($keywords);
    }
}
