<?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    class Transactions extends MY_Controller {
        function __construct(){
            parent::__construct();
            if($this->session->user == ""){
                redirect('login');
            }
            $this->load->model('finance/TransactionModel');
            $this->load->model('finance/AccountModel');
            $this->load->model('inventory/purchaseinvoice_model');
            $this->load->library('Formatslist');
        }
        public function index(){
            $this->load->view('common/head');
            $this->load->view('common/header');
            $this->load->view('finance/view_transaction');
            $this->load->view('common/footer');
        }
        public function view_transaction(){
            $ownerid=$this->session->userid;
            $columns = array( 
                0 =>'sl', 
                1=> 'created_by',
                2 =>'account',
                3=> 'Transactiontype',
                4=> 'PAYMENTHEAD',
                5=> 'TRANSACTION_DATE',
                5=> 'AMOUNT',
                7=> 'status',
                8=> 'ID',
            );
            $limit = $this->input->post('length'); 
            $start = $this->input->post('start');

            if($this->input->post('order')[0]['column'])
                $order = $columns[$this->input->post('order')[0]['column']];
            else
                $order= '';
            $dir = $this->input->post('order')[0]['dir'];
            $totalData = $this->TransactionModel->all_transactions_count($ownerid);
            $totalFiltered = $totalData;
            $search_array = array();  
            if($this->input->post('search')['value'] && $this->input->post('search_btn')){
                $search_array['search'] = $this->input->post('search')['value'];
            }
            if($this->input->post('filter_begin')){
                $search_array['filter_begin'] = $this->input->post('filter_begin');
            }
            if($this->input->post('filter_end')) {
                $search_array['filter_end'] = $this->input->post('filter_end');
            }
            
            if(count($search_array)==0) {
                $transactions = $this->TransactionModel->all_transactions($limit,$start,$dir, $ownerid,$order);
                $alltrans = $this->TransactionModel->all_transactions('','',$dir, $ownerid,$order);
                if($alltrans) {
                    $totcount   =   count($alltrans);
                } else {
                    $totcount   =   0;
                }
            } else {
                $alltrans = $this->TransactionModel->all_transactions('','',$dir, $ownerid,$order);
                $transactions =  $this->TransactionModel->transactions_search($limit,$start,$search_array,$order,$dir,$ownerid);
                $totalFiltered = $this->TransactionModel->transactions_search_count($search_array,$ownerid);
//                $totcount   =   count($alltrans);
                if($alltrans) {
                    $totcount   =   count($alltrans);
                } else {
                    $totcount   =   0;
                }
                
            }

            
            $data = array();
            if($transactions) {
                $account_id = 0;
                $j = $start+1;
                foreach ($transactions as $row){
                    $nestedData['sl'] = $j;
                    $nestedData['TRANSACTION_DATE'] = $this->formatslist->dateFormat($row->TRANSACTION_DATE);
                    $nestedData['account'] = $row->account;
                    $nestedData['Transactiontype'] = $row->Transactiontype;
                    if($row->PAYMENTHEAD=='PURCHASE' || $row->PAYMENTHEAD=='PURCHASE RETURN')
                        $nestedData['PAYMENTHEAD'] = $row->PAYMENTHEAD."<br/>[ Supplier : <span style='color:blue;'>".$row->SUPPLIERNAME."</span> ]";
                    else
                        $nestedData['PAYMENTHEAD'] = $row->PAYMENTHEAD;
                    $nestedData['AMOUNT'] = $this->formatslist->formatCurrencywithHash($row->AMOUNT);
                    $nestedData['created_by'] = $row->created_by;
                    //  Transaction Status
                    //  0 created
                    //  1	Approved
                    //  2	Rejected
                    //  3	On Hold
                    //  4	Updated
                    //  5	settle crated
                    //  6	settle updated
                    //  7	settlement on hold
                    //  8	settlement rejected
                    if($row->STATUS==0 || $row->STATUS==5){
                        $statustext='<div class="buttons-preview" id="status_'.$row->ID.'">'
                                . '<span class="label label-primary shiny">'.$this->lang->line("CREATED").'</span></div>';
                    }else if($row->STATUS==1){
                        $statustext='<div class="buttons-preview" id="status_'.$row->ID.'">'
                                . '<span class="label label-success shiny">'.$this->lang->line("APPROVED").'</span></div>';
                    }else if($row->STATUS==2 || $row->STATUS==8){
                        $statustext='<div class="buttons-preview" id="status_'.$row->ID.'">'
                                . '<span class="label label-danger shiny">'.$this->lang->line("REJECTED").'</span></div>';
                    }else if($row->STATUS==3 || $row->STATUS==7){
                        $statustext='<div class="buttons-preview" id="status_'.$row->ID.'">'
                                . '<span class="label label-warning shiny">'.$this->lang->line("ONHOLD").'</span></div>';
                    }else if($row->STATUS==4 || $row->STATUS==6){
                        $statustext='<div class="buttons-preview" id="status_'.$row->ID.'">'
                                . '<span class="label label-info">'.$this->lang->line("UPDATED").'</span></div>';
                    } else {
                        $statustext='<div class="buttons-preview" id="status_'.$row->ID.'">'
                                . '<span class="label label-primary shiny">'.$this->lang->line("CREATED").'</span></div>';
                    }
                    $nestedData['status'] = $statustext;
                    $actionbtn  = "<div class='buttons-preview'><a class='btn btn-info shiny btn-xs' href='javascript:void(0)'"
                            . " onclick='transactionsDetailsView(\"".$row->ID."\")'><i class='fa fa-eye'></i></a></div>";
                    $nestedData['ID'] = $actionbtn;
                    $data[] = $nestedData;
                    $j++;
                }
            }
            
            $json_data = array(
                "draw"            => intval($this->input->post('draw')),  
                "recordsTotal"    => intval($totcount),  
                "recordsFiltered" => intval($totalFiltered),
                "data"            => $data   
            );
            echo json_encode($json_data);
        }
        
        public function getTransactionDetails(){
            $transactionId = $this->input->post('transactionID');
            if($transactionId){
                $editRec    =   $this->TransactionModel->getPurchaseInvoice($transactionId);
                $editRec[0]["AMOUNT"]   =   $this->formatslist->formatCurrency($editRec[0]["AMOUNT"]);
                $editRec[0]["AMOUNTHASH"]   =   $this->formatslist->formatCurrencyWithHash($editRec[0]["AMOUNT"]);
                $editRec[0]["created"]   =   $this->formatslist->datetimeFormat($editRec[0]["created"]);
                echo json_encode($editRec);
            }
        }
        public function updateTransactionDetails(){
            $id     =   $this->input->post('transactionID');
            if($id){
                $getRec    =   $this->TransactionModel->getPurchaseInvoice($id);
                $dataupdate["COMMENTS"] = $this->input->post('txtcomments');
                $dataupdate["STATUS"] = $this->input->post('STATUS');
                $dataupdate["APPROVED"]     = date("Y:m:d H:i");
                $user = $this->session->userdata('user');
                $get_where  = array('NAME' => $user, );
                $user_detail = $this->common->getWhere('PEOPLE',$get_where);
                foreach($user_detail as $userdetail) {
                   $user_id = $userdetail->ID;
                }
                $dataupdate["APPROVED_BY"]  = $user_id;
                if($id){
                    $paymentdetRec  =   $this->TransactionModel->get_transactiondetails($id);
                    if($dataupdate["STATUS"]==1){
                        if($paymentdetRec[0]->STATUS!=9) {
                            $this->AccountModel->update_balance($getRec[0]["accountid"],$this->input->post('amount'));
                        }
                        if($getRec[0]["PAYMENTHEAD_ID"]=='PURCHASE') {
                            $purchaseinvoiceRec =   $this->purchaseinvoice_model->getPurchaseInvoiceDetailsByid($getRec[0]["PURCHASEINVOICE_ID"]);
                            if ($purchaseinvoiceRec) {
                                $totalamount=0;
                                $settlementamount=0;
                                if($paymentdetRec[0]->STATUS!=9) {
                                    // In case of settle ment of purchasse invoice.
                                    if ($paymentdetRec[0]->STATUS==5 || $paymentdetRec[0]->STATUS==6 || $paymentdetRec[0]->STATUS==7 || $paymentdetRec[0]->STATUS==8) {
                                        if((float)$purchaseinvoiceRec->BALANCE<(float)abs($this->input->post('amount'))) {
                                            $remAmount  =   abs((float)$this->input->post('amount'))-(float)$purchaseinvoiceRec->BALANCE;
                                            $form_data["ADJUSTMENT"]  =   abs((float)$purchaseinvoiceRec->ADJUSTMENT+$remAmount);
                                            $this->db->where('ID', $getRec[0]["PURCHASEINVOICE_ID"]);
                                            $this->db->update('PURCHASEINVOICE', $form_data);
                                            $supplierbal            =   $this->input->post('amount');
                                        } else {
                                            if($purchaseinvoiceRec->DISCOUNT)
                                                $discpur =   $purchaseinvoiceRec->DISCOUNT;
                                            else
                                                $discpur =   0;
                                            $settlementamount       =   -1*abs($purchaseinvoiceRec->BALANCE+(-1*abs($this->input->post('amount'))));
                                            $form_data["DISCOUNT"]  =   $discpur+$settlementamount;
                                            $this->db->where('ID', $getRec[0]["PURCHASEINVOICE_ID"]);
                                            $this->db->update('PURCHASEINVOICE', $form_data);
                                            $dicountgiven   =   $form_data["DISCOUNT"];
                                            $supplierbal            =   $this->input->post('amount')+$settlementamount;
                                        }
                                    } else {
                                        if((float)$purchaseinvoiceRec->BALANCE<(float)abs($this->input->post('amount'))) {
                                            $remAmount  =   abs((float)$this->input->post('amount'))-(float)$purchaseinvoiceRec->BALANCE;
                                            $form_data["ADJUSTMENT"]  =   abs((float)$purchaseinvoiceRec->ADJUSTMENT+$remAmount);
                                            $this->db->where('ID', $getRec[0]["PURCHASEINVOICE_ID"]);
                                            $this->db->update('PURCHASEINVOICE', $form_data);
                                        }
                                        $supplierbal    =   $this->input->post('amount');
                                    }
                                }
                            }
//                            if($paymentdetRec[0]->STATUS!=9) {
                                $this->purchaseinvoice_model->updatepisuppliercredit($purchaseinvoiceRec->SUPPLIERID,$supplierbal,$purchaseinvoiceRec->DELIVERYDATE);
//                            }
                        } else if($getRec[0]["PAYMENTHEAD_ID"]=='PURCHASERETURN'){
//                            $paymentdetRec  =   $this->TransactionModel->get_transactiondetails($id);
                            $purchaseinvoiceRec =   $this->purchaseinvoice_model->getPurchaseInvoiceDetailsByid($getRec[0]["PURCHASEINVOICE_ID"]);
                            if($purchaseinvoiceRec){
                                $totalamount=0;
                                $settlementamount=0;
                                if($paymentdetRec[0]->STATUS!=9) {
                                    // In case of settle ment of purchasse invoice.
                                    if($paymentdetRec[0]->STATUS==5 || $paymentdetRec[0]->STATUS==6 || $paymentdetRec[0]->STATUS==7 || $paymentdetRec[0]->STATUS==8){
                                        $balance    =   (float)$purchaseinvoiceRec->BALANCE;
                                        $amount    =   (float)(-1*abs($this->input->post('amount')));
                                        if($balance>$amount) {
                                            $remAmount  =   $amount-$balance;
                                            $form_data["ADJUSTMENT"]  =   -1*abs((float)$purchaseinvoiceRec->ADJUSTMENT+$remAmount);
                                            $this->db->where('ID', $getRec[0]["PURCHASEINVOICE_ID"]);
                                            $this->db->update('PURCHASEINVOICE', $form_data);
                                            $supplierbal            =   $this->input->post('amount');
                                        } else {
                                            if($purchaseinvoiceRec->DISCOUNT)
                                                $discpur =   $purchaseinvoiceRec->DISCOUNT;
                                            else
                                                $discpur =   0;
                                            $settlementamount       =   abs($purchaseinvoiceRec->BALANCE+(abs($this->input->post('amount'))));
                                            $form_data["DISCOUNT"]  =   $discpur+$settlementamount;
                                            $this->db->where('ID', $getRec[0]["PURCHASEINVOICE_ID"]);
                                            $this->db->update('PURCHASEINVOICE', $form_data);
                                            $dicountgiven   =   $form_data["DISCOUNT"];
                                            $supplierbal            =   abs($this->input->post('amount')+$settlementamount);
                                        }
                                    } else {
                                        $balance    =   (float)$purchaseinvoiceRec->BALANCE;
                                        $amount    =   (float)(-1*abs($this->input->post('amount')));
                                        if($balance>$amount) {
                                            $remAmount  =   $amount-$balance;
                                            $form_data["ADJUSTMENT"]  =   -1*abs((float)$purchaseinvoiceRec->ADJUSTMENT+$remAmount);
                                            $this->db->where('ID', $getRec[0]["PURCHASEINVOICE_ID"]);
                                            $this->db->update('PURCHASEINVOICE', $form_data);
                                        }
                                        $supplierbal    =   $this->input->post('amount');
                                    }
                                }
                            }
                            
//                            if($paymentdetRec[0]->STATUS!=9) {
                                $this->purchaseinvoice_model->updatepisuppliercredit($purchaseinvoiceRec->SUPPLIERID,$supplierbal,$purchaseinvoiceRec->DELIVERYDATE);
//                            }
                        }
                    }
                    if($this->TransactionModel->update_transaction($dataupdate,$id)){
                        echo json_encode(array('msgstatus' => 'success','status'=>$dataupdate["STATUS"],'trid'=>$id)); exit;
                    }
                }
            }
        }        
    }
?>