<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Sales extends MY_Controller {

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

    public function index() {
         $data['template'] = 'sales/sales_receipts_view';
        $this->load->view('template',$data);
    }
      public function deletedreceipts() {
        $this->load->view('settings/header');
        $this->load->view('deletedreceipts_veiw', null);
        $this->load->view('settings/footer');
    }

    // RECEIPTS LIST
    public function getreceipts() {
        $aColumns = array( 'sl', 'TICKET_DATE','TICKET_NO','CUSTOMER','MONEY','TAX','NAME');
	// 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])] == 'TICKET_NO' || $aColumns[intval($_GET['iSortCol_'.$i])] == 'CUSTOMER' ||  $aColumns[intval($_GET['iSortCol_'.$i])] == 'NAME') {
                        $sOrder .= $aColumns[intval($_GET['iSortCol_'.$i])]."
                            ".$_GET['sSortDir_' . $i].", ";
                    }else{
                        $sOrder.=    "TICKET_DATE DESC  ";
                    }
                }
            }
            $sOrder = substr_replace($sOrder, "", -2);
            if ($sOrder == "ORDER BY") {
                    $sOrder = "";
            }
	}
	/*
	 * Filtering
	 */
	$sWhere = "";
	if ($_GET['sSearch'] != "") {
            $sWhere = "WHERE (";
            for ($i = 1; $i < 7; $i++) {
                if($aColumns[$i] == 'TICKET_NO'){
                    $sWhere .= " TICKETS.TICKETID LIKE '%" . $_GET['sSearch'] . "%' OR ";
                }else if($aColumns[$i] == 'CUSTOMER'){
                    $sWhere .= " CUSTOMERS.NAME LIKE '%" . $_GET['sSearch'] . "%' OR ";
                }else if($aColumns[$i] == 'NAME'){
                    $sWhere .= " PEOPLE.NAME LIKE '%" . $_GET['sSearch'] . "%' OR ";
                }
            }
//              print_r($aColumns);exit;
            $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= "";
        }
        
        if($_GET["filter_begin"]) {
            $where  =   $where." AND RECEIPTS.DATENEW>='".date("Y-m-d H:i:s",strtotime($_GET["filter_begin"]." 00:00"))."'";
        }
        if($_GET["filter_end"]) {
            $where  =   $where." AND RECEIPTS.DATENEW<='".date("Y-m-d H:i:s",strtotime($_GET["filter_end"]." 23:59:59"))."'";
        }
        $sql = "SELECT TICKETS.ID AS RECEIPTID, SUM(TAXLINES.AMOUNT) AS TAX, TICKETS.TICKETID AS TICKET_NO, RECEIPTS.DATENEW AS TICKET_DATE,
            PAYMENTS.PAYMENT AS PAYMENTTYPE,PEOPLE.NAME,
            CUSTOMERS.NAME AS CUSTOMER,
            (PAYMENTS.TOTAL) AS MONEY
            FROM RECEIPTS JOIN TICKETS ON RECEIPTS.ID=TICKETS.ID LEFT JOIN PAYMENTS ON RECEIPTS.ID=PAYMENTS.RECEIPT 
            LEFT JOIN CUSTOMERS ON TICKETS.CUSTOMER=CUSTOMERS.ID LEFT JOIN TAXLINES ON RECEIPTS.ID=TAXLINES.RECEIPT
            LEFT JOIN PEOPLE ON TICKETS.PERSON = PEOPLE.ID";
	$sql.= " WHERE 1 " . $where." GROUP BY RECEIPTS.DATENEW " . $sOrder. $limit;
        
//        echo $sql;exit;
        
	$arr = $this->common->customquery($sql);
        $totalCount_sql = "SELECT COUNT(*) AS total FROM TICKETS";
	$totalCount = $this->common->customquery($totalCount_sql);
	$iTotal = $totalCount[0]->total;
        $j = 1;
	if ($arr != '') {
            foreach ($arr as $key => $aRow) {
                
            }
        }
	/*
	 * 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] = $j;
                $row[1] = $this->formatslist->datetimeFormat($aRow->TICKET_DATE);
                $row[2] = $aRow->TICKET_NO;
                $row[3] = $aRow->CUSTOMER;
                $row[4] = $this->formatslist->formatCurrencywithHash($aRow->MONEY);
                $row[5] = $this->formatslist->formatCurrencywithHash($aRow->TAX);
                $row[6] = $aRow->NAME;
                $row[7] = $aRow->RECEIPTID;
                $output['aaData'][] = $row;
                $j++;
            }
	} else {
            //
	}
	echo json_encode($output);
    }

    // RECEIPTS LIST
    public function getdeletedreceipts() {
       $datefrom = $this->input->post('datefrom');
        $dateto = $this->input->post('dateto');
        $ticket= $this->input->post('ticket');
        $type = $this->input->post('type');
        $customer = $this->input->post('customers');
        $user = $this->input->post('user');
        if($customer)
        {
            $this->load->model('partner/customers_model');
        $cid = $this->customers_model->getcidbn($customer);
        }
        else
        {
            $cid = "";
        }

        $this->load->model('sales/sales_model');
        echo $this->sales_model->getdeletedreceipts($datefrom, $dateto, $ticket, $type, $cid, $user);
    }

    // RECEIPT DETAILS
    public function getreceiptlines() {
        if (!$this->uri->segment(4) || $this->uri->segment(4) == "")
        {
            redirect(site_url() . 'sales/sales');
        }
        else
        {
        $this->load->model('sales/sales_model');
        $data['receipt'] = $this->sales_model->getreceiptlinesbyparam($this->uri->segment(4));
        $data['ticketlines'] = $this->sales_model->getticketlinesbyparam($this->uri->segment(4));
        $data['paymentlines'] = $this->sales_model->getpaymentlinesbyparam($this->uri->segment(4));
        $data['company_det'] = $this->companyinfo_model->getcompanyinfo('0');
        $data['template'] = 'sales/sales_receipt_details_view';
        $this->load->view('template',$data);
        }
    }

// 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 getproductcostandqoh(){
        $pname = $this->input->post('product');
        $this->load->model('inventory/stock_model');
        $result= $this->stock_model->getproductcostandqoh($pname, '0');
        $data = '{"uom": "' . $result[0]->UOM . '", "cost": "' . $result[0]->COST . '", "qoh": "' . $result[0]->QOH . '"}';
        echo $data;
    }
    public function getproductcostandqohandtax(){
        $pname = $this->input->post('product');
        $this->load->model('inventory/stock_model');
        $result= $this->stock_model->getproductcostandqoh($pname, '0');
        //TAX CALCULATION START ON PRODUCT CHANGE HUSSAIN 26/9/2011
        $taxcat = $this->stock_model->getproducttaxcat($pname);
        $price = $result[0]->COST;
        $tax1 = 0;
        $tax2 = 0;
        $tax3=0;
        $count = $this->stock_model->getcount($taxcat[0]->TAXCAT);
        $ptax = $this->stock_model->getproducttax($taxcat[0]->TAXCAT);
        for ($i = 0; $i < $count[0]->COUNT; $i++) {
            $rate = $ptax[$i]->RATE;
            if($rate != 0) {
                if($ptax[$i]->RATECASCADE == 0)
                    $tax1 = $tax1 + ($price * $rate);
                else if($ptax[$i]->RATECASCADE != 0)
                    $tax2 = ($tax1+$price) * $rate;
                    $tax3 = $tax1 + $tax2;
            }
            else {
                $tax3=0;
            }

}
//TAX CALCULATION END
$data = '{"uom": "' . $result[0]->UOM . '", "cost": "' . $result[0]->COST . '", "qoh": "' . $result[0]->QOH . '", "tax": "' . $tax3 . '"}';
echo $data;
}

public function gettaxamountforunitprice(){
$price = $this->input->post('price');
$pname = $this->input->post('product');
$this->load->model('inventory/stock_model');
//TAX CALCULATION START ON UNIT PRICE CHANGE HUSSAIN 03/10/2011
$taxcat = $this->stock_model->getproducttaxcat($pname);

$tax1 = 0;
$tax2 = 0;
$tax3=0;
$count = $this->stock_model->getcount($taxcat[0]->TAXCAT);
$ptax = $this->stock_model->getproducttax($taxcat[0]->TAXCAT);
for ($i = 0; $i < $count[0]->COUNT; $i++) {

        $rate = $ptax[$i]->RATE;
        if($rate != 0)
        {
            if($ptax[$i]->RATECASCADE == 0)
                $tax1 = $tax1 + ($price * $rate);
            else if($ptax[$i]->RATECASCADE != 0)
                $tax2 = ($tax1+$price) * $rate;
                $tax3 = $tax1 + $tax2;
        } else {
            $tax3=0;
        }
    }
    //TAX CALCULATION END
    //$data = '{"uom": "' . $result[0]->UOM . '", "cost": "' . $result[0]->COST . '", "qoh": "' . $result[0]->QOH . '", "tax": "' . $tax3 . '"}';
    $data = '{"tax": "' . $tax3 . '"}';
    echo $data;
}
    function exportcsv() {
        $file="exportexcel.csv";
        header("Content-Disposition: attachment; filename=" . urlencode($file));
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header("Content-Description: File Transfer");
        header("Content-type: application/csv");
        header("Pragma: no-cache");
        header("Expires: 0");
        $export= $this->input->post('exportdata');
        $this->load->helper('download');
        force_download($file, $export);
    }
    
    function printsr() {
        $this->load->library('session');
        $this->load->helper('dompdf');
        $this->load->helper('file');
        if (!$this->uri->segment(4) || $this->uri->segment(4) == "")
            redirect(site_url() . 'sales/sales');
        $this->load->model('sales/sales_model');
        $data['receipt'] = $this->sales_model->getreceiptlinesbyparam($this->uri->segment(4));
        $data['ticketlines'] = $this->sales_model->getticketlinesbyparam($this->uri->segment(4));
        $data['paymentlines'] = $this->sales_model->getpaymentlinesbyparam($this->uri->segment(4));
        $data['companyinfo'] = $this->companyinfo_model->getcompanyinfo('0');
        $html = $this->load->view('sales/salesreceipt_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');
        $pdf->SetTitle('Sales Invoice');
        $pdf->SetSubject('Sales Invoice');
        
        if($data['companyinfo']->DISPLAYLOGO!=null){
            $logoWidth=50;
            $complogo = $data['companyinfo']->DISPLAYLOGO;
            $pdf->SetHeaderData($complogo, $logoWidth, $data['companyinfo']->COMPANYNAME."#Sales Invoice", $data['companyinfo']->ADDRESS1."\nPhone: ".$data['companyinfo']->PHONE1."\n".$data['companyinfo']->EMAIL.', '.$data['companyinfo']->WEBSITE."\nTax ID: ".$data['companyinfo']->TAXID);
        }
        else
        {
            $pdf->SetHeaderData(K_BLANK_IMAGE, PDF_HEADER_LOGO_WIDTH, $data['companyinfo']->COMPANYNAME."#Sales Invoice", $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->SetFooterData($data['companyinfo']->COMPANYNAME);
        $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, '');
        
//        $imgdata = file_get_contents($data['companyinfo']->DISPLAYLOGO);
//        $pdf->setXY(0,5);
//        $pdf->Image('@'.$imgdata);
          //var_dump($html); exit;
        
        
        

        $pdf->lastPage();
        $pdf->Output('SALESINVOICE.pdf', 'I');
    }
    
    
}