<?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    class Deposits extends MY_Controller {
        function __construct(){
            parent::__construct();
            if($this->session->user == ""){
                redirect('login');
            }
            $this->load->model('finance/AccountModel');
            $this->load->model('finance/TransactionModel');
            $this->load->library('Formatslist');
            $this->load->library('session');
        }
        public function index(){
            $this->session->unset_userdata('DepId');
            $this->load->view('common/head');
            $this->load->view('common/header');
            $this->load->view('finance/view_deposits');
            $this->load->view('common/footer');
        }
        public function view_deposit() {
            $aColumns = array(
                'sl',
                'TRANSACTION_DATE',
                'account',
                'AMOUNT',
                'created_by',
                'status',
                'ID');
            // 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] . ", ";
                        }
                    }
                }
                $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] == 'account') {
                        $aColumns[$i] = 'b.ACCOUNT_NAME';
//                        $tablename = 'b';
                    } else if ($aColumns[$i] == 'PAYMENTHEAD') {
                        $aColumns[$i] = 'd.PAYMENTHEAD';
                       // $tablename = 'd';
                    } else if ($aColumns[$i] == 'AMOUNT') {
                        $aColumns[$i] = 'a.AMOUNT';
                        //$tablename = 'a';
                    } else if ($aColumns[$i] == 'created_by') {
                        $aColumns[$i] = 'c.NAME';
                        //$tablename = 'c';
                    } else if ($aColumns[$i] == 'TRANSACTION_DATE') {
                        $aColumns[$i] = 'a.TRANSACTION_DATE';
                        //$tablename = 'a';
                    } else if ($aColumns[$i] == 'status') {
                        $aColumns[$i] = 'a.status';
                        //$tablename = '';
                    }
                    $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 = '';
            }
            if($sOrder=='')
                $sOrder= ' ORDER BY a.CREATED DESC';
            
            if(isset($_REQUEST["STATUS"])) {
                if($_REQUEST["STATUS"]!='')
                    $where = ' AND a.STATUS='.$_REQUEST["STATUS"]." ";
            }
            $sql = "Select a.ID, b.ACCOUNT_NAME as account,b.ID as accountid, a.AMOUNT, c.NAME as created_by, a.CREATED as created,a.TRANSACTION_DATE,a.STATUS,CASE a.status 
                WHEN 0 THEN 'Created' 
                WHEN 1 THEN 'Approved'  
                WHEN 2 THEN 'Rejected'
                WHEN 3 THEN 'On Hold'
                WHEN 4 THEN 'Updated'
                ELSE 'Created' 
            END as statustext,".
                " CASE WHEN a.TRANSACTION_TYPE_ID=0 THEN 'Deposit' ELSE 'Payment' END as Transactiontype,d.PAYMENTHEAD".
                " from TRANSACTIONS as a".
                " left join ACCOUNTS as b on a.ACCOUNT_ID=b.ID".
                " left join PEOPLE as c on a.CREATED_BY=c.ID".
                " left join PAYMENTHEADS as d on a.PAYMENTHEAD_ID=d.ID";
            $sql.= " WHERE TRANSACTION_TYPE_ID='0' " . $where . $sOrder . $limit;

            $arr = $this->common->customquery($sql);
            $totalCount_sql = " Select count(*) AS total".
                " from TRANSACTIONS as a".
                " left join ACCOUNTS as b on a.ACCOUNT_ID=b.ID".
                " left join PEOPLE as c on a.CREATED_BY=c.ID".
                " left join PAYMENTHEADS as d on a.PAYMENTHEAD_ID=d.ID";
            $totalCount_sql .= " WHERE TRANSACTION_TYPE_ID='0' ";
            $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] = $j;
                    $row[1] = $this->formatslist->dateFormat($aRow->TRANSACTION_DATE);
                    $row[2] = $aRow->account;
                    $row[3] = $this->formatslist->formatCurrencywithHash($aRow->AMOUNT);
                    $row[4] = $aRow->created_by;
                    $row[5] = $aRow->STATUS;
                    $row[6] = $aRow->ID;
                    $output['aaData'][] = $row;
                    $j++;
                }
            } else {
                //
            }
            echo json_encode($output);
        }
        
        public function add_deposit(){
            $id = $this->session->userdata('DepId');
            if(!empty($_POST)){
                $dataTrans["TRANSACTION_DATE"]      =   date("Y-m-d",strtotime($this->input->post('TRANSACTION_DATE')));
                $dataTrans["TRANSACTION_TYPE_ID"]    =   '0'; // 0 for Deposit
                $dataTrans["PAYMENTHEAD_ID"]    =   'DEPOSIT'; // Defualt Deposit
                $dataTrans["ACCOUNT_ID"]    =   $this->input->post('account');
                $dataTrans["AMOUNT"]    =   $this->input->post('amount');
                $dataTrans["COMMENTS"]    =   $this->input->post('comments');
                $dataTrans["STATUS"]    =   0;
                $dataTrans["CREATED"]    =   date('Y-m-d H:i:s');
                $dataTrans["CREATED_BY"]    =   $this->session->userid;
                $dataTrans["APPROVED_BY"]    =   $this->session->userid;
                if($this->input->post('depId')){
                    $id    =   $this->input->post('depId');
                    $dataTrans["STATUS"]    =   4;
                    if($this->TransactionModel->update_transaction($dataTrans,$id)){
                        redirect('finance/deposits');
                    }else{
                        return false;
                    }
                }else{
                    $dataTrans["ID"]    = uniqid();
                    if($this->TransactionModel->add_transaction($dataTrans)){
                        redirect('finance/deposits');
                    }else{
                        return false;
                    }
                }
            } else {
                if($id){
                    $data['depositdetails'] = $this->TransactionModel->get_transactiondetails($id);
                    $data['depositdetails'] = $data['depositdetails'][0];
                }
                $data['accounts'] = $this->AccountModel->dropdown_acounts();
                $data['template'] = 'finance/add_deposit';
                $this->load->view('template',$data);
            }
        }
        public function editrecord($id=''){
            $this->session->set_userdata(array('DepId'  => $id));
            redirect('finance/Deposits/add_deposit/');
        }
        public function get_account(){
            if(!empty($_POST["account"])){
                $id = $this->input->post('account');
                $account = $this->AccountModel->get_account($id);
                $data['available_balance'] = $account[0]->AVAILABLE_BALANCE;
                echo $this->formatslist->formatCurrency($data['available_balance']);
            }
        }
        public function delete_transaction($id=''){
            if(!empty($id)){
                $where = array('ID' => $id);  
                if($this->common->delete('TRANSACTIONS',$where)){
                    $this->session->set_flashdata('success_msg', 'The record has been deleted successfuly.');
                    redirect('finance/deposits');
                }else{
                    $this->session->set_flashdata('success_msg', 'Cannot Delete');
                    redirect('finance/deposits');
                }
            }
        }
    }
?>
