? Fallagassrini

Fallagassrini Bypass Shell

echo"
Fallagassrini
";
Current Path : /home1/savoy/public_html/savoyglobal.net/sibs_draft/system/application/models/

Linux gator3171.hostgator.com 4.19.286-203.ELK.el7.x86_64 #1 SMP Wed Jun 14 04:33:55 CDT 2023 x86_64
Upload File :
Current File : /home1/savoy/public_html/savoyglobal.net/sibs_draft/system/application/models/accountingsmodel.php

<?php

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

class accountingsmodel extends Model
{

    function accountingsmodel()
    {
        parent::Model();
    }

    function addgl_acc_class()
    {

        $class_name = $this->input->post('class_name');
        $class_type = $this->input->post('class_type');
        $inactive = $this->input->post('inactive');
        if ($inactive == 'true')
        {
            $inact = 1;
        }
        else
        {
            $inact = 0;
        }
        $tblValues = array('class_name' => $class_name, 'ctype' => $class_type, 'inactive' => $inact);
        $data = $this->db->insert('gl_class', $tblValues);
        return $data;
    }

    function deletechart_acc($fld, $table, $id)
    {

        $qry = $this->db->query("select count(*) as count from subacc_setting where customer=$id or company=$id or employee=$id or cover=$id");
        $query = $qry->row()->count;
        $acc_cod = $this->customermodel->getSingleFieldValue('chart_master', 'account_code', 'id', $id);
        if (!is_numeric($acc_cod))
        {
            return 0;
        }
        $qry1 = $this->db->query("select count(*) as count1 from gl_trans where account='$acc_cod'");
        $query1 = $qry1->row()->count1;

        if ($query1 == 0 && $query == 0)
        {
            $res = $this->db->delete($table, array($fld => $id));
            if ($res > 0)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
        else
        {
            return 0;
        }
    }

    function deletegl_class($fld, $table, $id)
    {

        $res = $this->db->delete($table, array($fld => $id));
        if ($res > 0)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }

    function updategl_acc_class()
    {

        $class_name = $this->input->post('class_name');
        $class_type = $this->input->post('class_type');
        $inactive = $this->input->post('inactive');
        $id = $this->input->post('id');

        if ($inactive == 'true')
        {
            $inact = 1;
        }
        else
        {
            $inact = 0;
        }

        //$tblValues=array('cid'=>$class_id,'class_name'=>$class_name,'ctype'=>$class_type,'inactive'=>$inact);
        // $data=$this->db->insert('gl_class', $tblValues);
        $res = $this->db->query("update gl_class set class_name='" . $class_name . "',ctype='" . $class_type . "',inactive='" . $inact . "' where cid='" . $id . "'");
        return $res;
    }

    function Getgl_class($table, $pageno, $field, $value = "")
    {

        $limit = (($pageno - 1) * 10);
        $data = array();
        $res = $this->db->query("select * from $table left join chart_account_group on chart_account_group.chart_group_id=char_type.chart_group where " . $table . '.' . $field . " like '" . $value . "%' limit " . $limit . "," . 10);
        foreach ($res->result_array() as $row)
        {
            $data[] = $row;
        }
        return $data;
    }

    function get_bank_accounts($table, $pageno, $field, $value = "")
    {

        $limit = (($pageno - 1) * 10);
        $data = array();
        $res = $this->db->query("select * from $table  where " . $table . '.' . $field . " like '" . $value . "%' limit " . $limit . "," . 10);
        foreach ($res->result_array() as $row)
        {
            $data[] = $row;
        }
        return $data;
    }

    function get_account_type_settings($table)
    {
        $data = array();
        $res = $this->db->query("select * from $table group by account_type_for");
        foreach ($res->result_array() as $row)
        {
            $data[] = $row;
        }
        return $data;
    }

    function showgl_class($pageno, $field, $value = "")
    {
        $limit = (($pageno - 1) * 10);
        $data = array();
        $data1 = array();


        if ($field == 'main_account_code')
        {
            $sql = "select * from chart_master cm join
                char_type ct on ct.id=cm.chart_type  where  parent in (select id from chart_master where account_code like '" . $value . "%')";
            $rescount = $this->db->query($sql);


            $res = $this->db->query("select cm.id,cm.account_code,cm.account_name,cm.chart_type,cm.parent from chart_master cm join
                char_type ct on ct.id=cm.chart_type  where  parent in (select id from chart_master where account_code like '" . $value . "%') order by ct.id,cm.parent,cm.account_code asc,cm.id desc limit " . $limit . "," . 10);
        }
        else if ($field == 'parent')
        {
            $sql = "select * from chart_master cm join
                char_type ct on ct.id=cm.chart_type  where  parent in (select id from chart_master where account_name like '" . $value . "%')";
            $rescount = $this->db->query($sql);


            $res = $this->db->query("select cm.id,cm.account_code,cm.account_name,cm.chart_type,cm.parent from chart_master cm join
                char_type ct on ct.id=cm.chart_type  where  parent in (select id from chart_master where account_name like '" . $value . "%') order by ct.id,cm.parent,cm.account_code asc,cm.id desc limit " . $limit . "," . 10);
        }
        else
        {
            $rescount = $this->db->query("select * from chart_master cm join 
                char_type ct on ct.id=cm.chart_type  where " . $field . " like '" . $value . "%' and parent!=0");


            $res = $this->db->query("select cm.id,cm.account_code,cm.account_name,cm.chart_type,cm.parent from chart_master cm join 
                char_type ct on ct.id=cm.chart_type  where " . $field . " like '" . $value . "%' and parent!=0 order by ct.id,cm.parent,cm.account_code asc,cm.id desc limit " . $limit . "," . 10);
        }
        $data['totcount'] = $rescount->num_rows();

        foreach ($res->result_array() as $row)
        {
            $data1[] = $row;
        }
        $data['result'] = $data1;

        return $data;
    }

    function showsub_classmain($mainacc, $pageno, $field, $value = "")
    {
        $limit = (($pageno - 1) * 10);
        $data = array();
        $data1 = array();
        $rescount = $this->db->query("select * from chart_master cm join
                char_type ct on ct.id=cm.chart_type  where " . $field . " like '" . $value . "%' and parent='$mainacc'");


        $res = $this->db->query("select cm.id,cm.account_code,cm.account_name,cm.chart_type,cm.parent from chart_master cm join
                char_type ct on ct.id=cm.chart_type  where " . $field . " like '" . $value . "%' and parent='$mainacc' order by ct.id,cm.parent,cm.id desc limit " . $limit . "," . 10);
        $data['totcount'] = $rescount->num_rows();

        foreach ($res->result_array() as $row)
        {
            $data1[] = $row;
        }
        $data['result'] = $data1;

        return $data;
    }

    function Getsubacc_settings()
    {


        $data = array();

        $res = $this->db->query("select * from subacc_setting");
        return $res;
    }

    function countacc_settings()
    {


        $data = array();

        $res = $this->db->query("select * from subacc_setting");
        return $res->num_rows();
    }

    function Get_edit_data($fld, $table, $id)
    {

        $res = $this->db->query("select * from $table where " . $fld . "='" . $id . "'");

        $result = $res->row();
        return $res;
    }

    /*     * ************ Functions for GL Account Groups ****************** */

    function addgl_acc_group()
    {

        $group_name = $this->input->post('group_name');

        $class_type = $this->input->post('class_type');
        $inactive = $this->input->post('inactive');
        if ($inactive == 'true')
        {
            $inact = 1;
        }
        else
        {
            $inact = 0;
        }
        $tblValues = array('name' => $group_name, 'class_id' => $class_type, 'inactive' => $inact);
        $data = $this->db->insert('gl_groups', $tblValues);
        return $data;
    }

    function add_acc_settings()
    {

        $customer = $this->input->post('customer');
        $company = $this->input->post('company');
        $employee = $this->input->post('employee');
        $profitloss = $this->input->post('profitloss');
        $agent = $this->input->post('agent');
        $salary = $this->input->post('salary');
        $tblValues = array('customer' => $customer, 'company' => $company, 'employee' => $employee, 'profitloss' => $profitloss, 'agent' => $agent, 'salary' => $salary);
        $data = $this->db->insert('subacc_setting', $tblValues);
        return $data;
    }

    function updateacc_settings()
    {

        $customer = $this->input->post('customer');
        $company = $this->input->post('company');
        $employee = $this->input->post('employee');
        $profitloss = $this->input->post('profitloss');
        $id = $this->input->post('id');
        $agent = $this->input->post('agent');
        $salary = $this->input->post('salary');
        $cover = $this->input->post('cover');
        $settlement = $this->input->post('settlement');
        $allowance = $this->input->post('allowance');
        $deduction = $this->input->post('deduction');

        $tblValues = array('customer' => $customer, 'cover' => $cover, 'company' => $company, 'employee' => $employee, 'profitloss' => $profitloss, 'agent' => $agent, 'salary' => $salary,
            'settlement' => $settlement, 'allowance' => $allowance, 'deduction' => $deduction);

        $this->db->where('id', $id);
        $res = $this->db->update('subacc_setting', $tblValues);
        return $res;
    }

    function updategl_acc_group()
    {

        $group_name = $this->input->post('group_name');
        $class_type = $this->input->post('class_type');

        $inactive = $this->input->post('inactive');
        $id = $this->input->post('id');

        if ($inactive == 'true')
        {
            $inact = 1;
        }
        else
        {
            $inact = 0;
        }

        $Values = array('name' => $group_name, 'class_id' => $class_type, 'inactive' => $inact);
        $this->db->where('id', $id);
        $res = $this->db->update('gl_groups', $Values);
        return $res;
    }

    /*     * **********************End of GL account group functions*************************** */
    /*     * **************************functions of General Ledger accounts********************************** */

    function addgl_acc()/* sub account */
    {
        $acc_name = $this->input->post('acc_name');
        $acc_subexp = $this->input->post('acc_sub');
        $explode = explode("~", $acc_subexp);
        $acc_sub = $explode[0];
        $acc_group = $explode[1];


        $start = $this->customermodel->getSingleFieldValue('chart_master', 'account_code', 'id', $acc_sub);

        $start_ex = str_split($start);

        $code = $this->accountingsmodel->acc_code_increment($acc_sub, $start_ex[0]);
        $max_code = $this->accountingsmodel->acc_code_maxi_limit($start);

        $i = 1;
        if ($code == 0)
        {
            $acc_code = $start + $i;
        }
        else
        {
            $acc_code = $code + $i;
        }



        do
        {
            $i++;
            $num_rows_code = $this->mastermodel->number_rows('chart_master', 'account_code', $acc_code);
            if ($num_rows_code != 0)
            {
                if ($code == 0)
                {
                    $acc_code = $start + $i;
                }
                else
                {
                    $acc_code = $code + $i;
                }
            }
        }
        while ($num_rows_code != 0);

        $tblValues = array('account_code' => $acc_code, 'account_name' => $acc_name, 'chart_type' => $acc_group, 'parent' => $acc_sub);
        $data = $this->db->insert('chart_master', $tblValues);

        return $data;
    }

    function updategl_acc()
    {
        $acc_name = $this->input->post('acc_name');
        $acc_subexp = $this->input->post('acc_sub');
        $explode = explode("~", $acc_subexp);
        $acc_sub = $explode[0];
        $acc_group = $explode[1];

        $inactive = $this->input->post('inactive');
        $id = $this->input->post('id');

        if ($inactive == 'true')
        {
            $inact = 1;
        }
        else
        {
            $inact = 0;
        }

        $Values = array('account_name' => $acc_name, 'chart_type' => $acc_group, 'parent' => $acc_sub, 'inactive' => $inact);

        $this->db->where('id', $id);
        $res = $this->db->update('chart_master', $Values);
        return $res;
    }

    /*     * *************************functions for quick entry********************************* */

    function addquick_entry()
    {

        $description = $this->input->post('description');
        $entry_type = $this->input->post('entry_type');
        $ba_desc = $this->input->post('ba_desc');
        $default_ba = $this->input->post('default_ba');

        $tblValues = array('description' => $description, 'entry_type' => $entry_type, 'base_desc' => $ba_desc, 'base_amount' => $default_ba);
        $data = $this->db->insert('quick_entry', $tblValues);
        return $data;
    }

    function updatequick_entry()
    {
        $description = $this->input->post('description');
        $entry_type = $this->input->post('entry_type');
        $ba_desc = $this->input->post('ba_desc');
        $default_ba = $this->input->post('default_ba');
        $id = $this->input->post('id');

        $Values = array('description' => $description, 'entry_type' => $entry_type, 'base_desc' => $ba_desc, 'base_amount' => $default_ba);
        $this->db->where('id', $id);
        $res = $this->db->update('quick_entry', $Values);
        return $res;
    }

    /*     * ********************functions for bank accounts**************************** */

    function addbank_acc()/* bank account */
    {

        $acc_code = $this->input->post('acc_code');
        $acc_name = $this->input->post('acc_name');
        $acc_type = $this->input->post('acc_type');
        $acc_no = $this->input->post('acc_no');
        //$def_cur_val=$this->input->post('def_cur_val');
        $bank_curr = $this->input->post('bank_curr');
        $bank_name = $this->input->post('bank_name');
        $bank_add = $this->input->post('bank_add');
        $last_rec_date = "";
        $ending_bal = "";


        $tblValues = array('account_code' => $acc_code, 'bank_account_name' => $acc_name, 'acc_type' => $acc_type, 'bank_account_number' => $acc_no, 'bank_name' => $bank_name, 'bank_address' => $bank_add, 'bank_curr_code' => $bank_curr, 'last_reconciled_date' => $last_rec_date, 'ending_reconcile_balance' => $ending_bal);

        $data = $this->db->insert('bank_accounts', $tblValues);
        return $data;
    }

    function updatebank_acc()
    {


        $acc_code = $this->input->post('acc_code');
        $acc_name = $this->input->post('acc_name');
        $acc_type = $this->input->post('acc_type');
        $acc_no = $this->input->post('acc_no');
        //$def_cur_val=$this->input->post('def_cur_val');
        $bank_curr = $this->input->post('bank_curr');
        $bank_name = $this->input->post('bank_name');
        $bank_add = $this->input->post('bank_add');
        $last_rec_date = "";
        $ending_bal = "";

        $id = $this->input->post('id');


        $Values = array('account_code' => $acc_code, 'bank_account_name' => $acc_name, 'acc_type' => $acc_type, 'bank_account_number' => $acc_no, 'bank_name' => $bank_name, 'bank_address' => $bank_add, 'bank_curr_code' => $bank_curr, 'last_reconciled_date' => $last_rec_date, 'ending_reconcile_balance' => $ending_bal);
        $this->db->where('id', $id);
        $res = $this->db->update('bank_accounts', $Values);
        return $res;
    }

    function getSingleFieldValue($table, $field, $condition, $value, $condition2, $value2)
    {


        $data = $this->db->query("select " . $field . " from " . $table . " where " . $condition . "='" . $value . "' and " . $condition2 . "= '" . $value2 . "'");



        $results = $data->row();
        if ($results)
        {

            return $results->$field;
        }
        else
        {
            return "";
        }
    }

    /*     * **************************************functions for bank payment and deposit******************************************* */

    function opt_group()
    {
        $data = array();

        $Q = $this->db->query("select * from chart_master cm join char_type ct on cm.chart_type=ct.id where cm.account_code not in(select account_code from bank_accounts) and cm.parent!=0 ");
        foreach ($Q->result_array() as $row)
        {
            $data[] = $row;
        }
        $Q->free_result();
        return $data;
    }

    function bank_payment($refid)
    {


        $count = $this->db->query("select * from unposted_pay_dep where unpost='0' and type=2 and  reference='" . $refid . "'");

        foreach ($count->result_array() as $row)
        {
            $ref_id = $row['reference'];
            $date = $row['date'];
            $tdate = date('Y-m-d');
            $bank_id = $row['acc_id'];
            $bank_code = $row['bank_acc'];
            $amount = $row['amount'];
            $account = $row['account'];
            $memo = $row['memo'];
            $method = $row['method'];
        }



        $this->db->trans_begin();


        /*         * ******************************************Insert into Audit_trail***************************************************** */
        $fyear = $this->fiscalyear();
        $insValuesA = array(
            'trans_no' => $ref_id,
            'user' => $_SESSION['userid'],
            'date_trans' => $tdate,
            'fiscal_year' => $fyear,
            'gl_date' => $date
        );
        $this->db->insert('audit_trail', $insValuesA);

        /*         * ******************************************Insert into transaction tables*************************** */
        $ref = $this->customermodel->getSingleFieldValue('refs', 'reference', 'id', $ref_id);
        $tblValues = array('type_no' => $ref_id, 'tran_date' => $date, 'account' => $account, 'memo' => $memo, 'amount' => -$amount, 'method' => $method);
        $str1 = $this->db->insert('gl_trans', $tblValues);
        $tblValues1 = array('type_no' => $ref_id, 'tran_date' => $date, 'account' => $bank_code, 'memo' => $memo, 'amount' => $amount, 'method' => $method);
        $str2 = $this->db->insert('gl_trans', $tblValues1);
        $tblValue = array('type_no' => $ref_id, 'tran_date' => $date, 'account' => $account, 'memo' => $memo, 'amount' => -$amount, 'alloc' => '');
        $str = $this->db->insert('customer_trans', $tblValue);
        $bankValue = array('trans_no' => $ref_id, 'bank_act' => $bank_id, 'ref' => $ref, 'trans_date' => $date, 'amount' => $amount, 'reconciled' => '');
        $str = $this->db->insert('bank_trans', $bankValue);
        $posted_val = array('unpost' => 1);
        $this->db->where('reference', $ref_id);
        $str = $this->db->update('unposted_pay_dep', $posted_val);


        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return 0;
        }
        else
        {
            $this->db->trans_commit();
            return $str;
        }
    }

    function unpostcust_payment()
    {
        $cust_id = $_POST['customer_id'];
        $ref = $this->accountingsmodel->get_reference_code(2);
        $memo = $_POST['memo'];
        $method = $_POST['method'];
        $qdate = $_POST['date'];
        $date = $this->mastermodel->convdatformat($qdate);
        $amount = $_POST['amount'];
        $bank_account = $_POST['to_bank'];
        $bank_acc = explode('~', $bank_account);
//        var_dump($_POST);

        $cust_acc = $this->customermodel->getSingleFieldValue('customers', 'code', 'id', $cust_id);

        $this->db->trans_begin();
        $insertvals = array('type' => '2', 'reference' => $ref); // inserting values to refs table
        $this->db->insert('refs', $insertvals);
        $ref_id = $this->db->insert_id();


        $tblValues = array('reference' => $ref_id,
            'acc_id' => $bank_acc[0], 'date' => $date,
            'bank_acc' => $bank_acc[1], 'memo' => $memo, 'amount' => $amount,
            'account' => $cust_acc, 'unpost' => 0, 'type' => 2, 'method' => $method);
        $str = $this->db->insert('unposted_pay_dep', $tblValues);
        if ($method == 'cheque')
        {
            $ch_date = $_POST['ch_date'];
            $ch_date = $this->mastermodel->convdatformat($ch_date);
            $bname = $_POST['bankname'];
            $ch_no = $_POST['ch_no'];
            $chdetails = array('reference' => $ref_id, 'ch_date' => $ch_date, 'bank_name' => $bname, 'cheque_no' => $ch_no);
            $str = $this->db->insert('receipt_cheque', $chdetails);
        }
        if ($method == "bank")
        {
            $bank_details = array('reference' => $ref_id, 'bank_info' => $_POST['bank_info']);
            $this->db->insert('payment_bank_info', $bank_details);
        }


        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return 0;
        }
        else
        {
            $this->db->trans_commit();
            return $str;
        }
    }

    function updatecust_payment()
    {
        $cust_id = $_POST['customer_id'];
        $memo = $_POST['memo'];
        $method = $_POST['method'];
        $qdate = $_POST['date'];
        $date = $this->mastermodel->convdatformat($qdate);
        $amount = $_POST['amount'];
        $bank_account = $_POST['to_bank'];
        $bank_acc = explode('~', $bank_account);



        $cust_acc = $this->customermodel->getSingleFieldValue('customers', 'code', 'id', $cust_id);

        $this->db->trans_begin();

        $ref_id = $_POST['refid'];



        $this->db->delete('receipt_cheque', array('reference' => $ref_id));
        $this->db->delete('payment_bank_info', array('reference' => $ref_id));

        if ($method == 'cheque')
        {
            $delete_ch = $this->db->delete('receipt_cheque', array('reference' => $ref_id));
            $ch_date = $_POST['ch_date'];
            $ch_date = $this->mastermodel->convdatformat($ch_date);
            $bname = $_POST['bankname'];
            $ch_no = $_POST['ch_no'];
            $chdetails = array('reference' => $ref_id, 'ch_date' => $ch_date, 'bank_name' => $bname, 'cheque_no' => $ch_no);
            $str = $this->db->insert('receipt_cheque', $chdetails);
        }
        if ($method == "bank")
        {
            $bank_details = array('reference' => $ref_id, 'bank_info' => $_POST['bank_info']);
            $this->db->insert('payment_bank_info', $bank_details);
        }

        $tblValues = array('acc_id' => $bank_acc[0], 'date' => $date, 'bank_acc' => $bank_acc[1], 'memo' => $memo, 'amount' => $amount, 'account' => $cust_acc, 'unpost' => 0, 'type' => 2, 'method' => $method);
        $this->db->where('reference', $ref_id);
        $str = $this->db->update('unposted_pay_dep', $tblValues);

        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return 0;
        }
        else
        {
            $this->db->trans_commit();
            return $str;
        }
    }

    function data_exist($table, $data)
    {
        $data = str_replace('~', '/', $data);
        $query = $this->db->query("select * from $table where reference='$data'");

        if ($query->num_rows() > 0)
            echo $query->num_rows();
        else
            echo 0;
    }

    function code_exist($table, $field, $data)
    {

        $query = $this->db->query("select * from $table where $field='$data'");
        echo $query->num_rows();
    }

    function deletetrans($type, $refid)
    {

        $res = $this->db->delete('refs', array('type' => $type, 'id' => $refid));
        $res = $this->db->delete('gl_trans', array('type' => $type, 'type_no' => $refid));
        $res = $this->db->delete('bank_trans', array('type' => $type, 'trans_no' => $refid));
        if ($type == 4)
        {
            $res = $this->db->delete('bank_to_bank', array('type' => $type, 'ref' => $refid));
        }
        if ($res > 0)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }

    function single_trans($table, $refid)
    {
        $data = array();

        $res = $this->db->query("select * from $table where  type_no='" . $refid . "' and amount!=0 order by account");
        foreach ($res->result_array() as $row)
        {
            $data[] = $row;
        }
        return $data;
    }

    function single_unpost($table, $refid)
    {


        $data = array();

        $res = $this->db->query("select * from $table where  reference='" . $refid . "'");
        foreach ($res->result_array() as $row)
        {
            $data[] = $row;
        }
        return $data;
    }

    function single_transact($cusid, $date1 = "", $date2 = "")
    {


        $data = array();
        $qry = "SELECT
                                     placing_slip_premiumdetails.premium
                                    ,placing_slip_premiumdetails.policy_fees 
                                    , placing_slip.id as pid
                                    ,'0' as eid
                                    , IFNULL(sum(cust_allocate.amount),0) as amount
                                    , customers.id
                                    , placing_slip_refs.id as typeno
                                    , customer_trans.alloc as calloc
                                    , placing_slip.quotation_ref
                                    , reference    
                                    , '' as policyno
                                    , customer_trans.tran_date as tran_date
                                    ,cover
                                    ,customer_trans.amount as tamount,
                                    refs.type
                                    , placing_slip.remarks as description
                                 

                                FROM
                                    placing_slip_premiumdetails
                                    INNER JOIN placing_slip
                                        ON (placing_slip_premiumdetails.placing_slip_id = placing_slip.id)
                                    LEFT JOIN cust_allocate
                                        ON (placing_slip_premiumdetails.placing_slip_id = cust_allocate.pid and cust_allocate.type='issue')
                                    INNER JOIN placing_slip_refs
                                        ON (placing_slip_premiumdetails.placing_slip_id = placing_slip_refs.pslip_id and placing_slip_refs.type='issue')
                                    INNER JOIN customer_trans
                                        ON (customer_trans.type_no = placing_slip_refs.id)
                                    INNER JOIN refs
                                        ON refs.id=customer_trans.type_no
                                     inner join covers on covers.id=placing_slip.cover_id    
                                    INNER JOIN customers
                                        ON (placing_slip.customer_id = customers.id) where customers.id=$cusid";
        if (!empty($date1) && !empty($date2))
        {
            $qry.=" and customer_trans.tran_date between '$date1' and '$date2' ";
        }
        $qry.=" GROUP BY placing_slip.id";

        $qry.=" UNION SELECT
                                     endorsement.premiumchange as premium
                                    ,endorsement.policyfeeschange as  policy_fees
                                    , '0' as pid
                                    , endorsement.id as eid
                                    , IFNULL(sum(cust_allocate.amount),0) as amount
                                    , customers.id
                                    , placing_slip_refs.id as typeno
                                    , customer_trans.alloc as calloc
                                    , endrefno as quotation_ref
                                    , reference
                                    , endorsement.endpolicyno as policyno
                                    , customer_trans.tran_date as tran_date
                                    ,cover
                                    ,customer_trans.amount as tamount,
                                    refs.type
                                    , endorsement.remarks as description
                                    
                                 

                                FROM
                                    endorsement
                                    join policynote on
                                        policynote.id=endorsement.policyid
                                    join placing_slip on placing_slip.quotation_ref= policynote.quotation_ref   
                                    
                                    LEFT JOIN cust_allocate
                                        ON (endorsement.id = cust_allocate.pid and cust_allocate.type='endorsement')
                                    INNER JOIN placing_slip_refs
                                        ON (endorsement.id = placing_slip_refs.pslip_id and placing_slip_refs.type='endorsement')
                                    INNER JOIN customer_trans
                                        ON (customer_trans.type_no = placing_slip_refs.id)
                                    INNER JOIN refs
                                        ON refs.id=customer_trans.type_no
                                     inner join covers on covers.id=placing_slip.cover_id     
                                    INNER JOIN customers
                                        ON (placing_slip.customer_id = customers.id) where customers.id=$cusid ";
        if (!empty($date1) && !empty($date2))
        {
            $qry.=" and customer_trans.tran_date between '$date1' and '$date2' ";
        }
        $qry.=" GROUP BY endorsement.id";
        $res = $this->db->query($qry);

        return $res;
    }

    function single_allocate($tid)
    {


        $data = array();

        $qry = "SELECT * FROM customer_trans where id=$tid";

        $res = $this->db->query($qry);

        return $res;
    }

    function addtoallocate()
    {
        $totalamount = 0;
        $alloc_amt = $_POST['alloc_fld'];
        $alloc_type = $_POST['alloc_fld_type'];
        $tran_date = $_POST['trans_date'];
        $memo = $_POST['memo'];
        $pre_alloc = $_POST['pre_alloc'];
        $ptype = $_POST['premium_type'];
        $pid = $_POST['pslip_id'];
        $eid = $_POST['endoresement_id'];
        $preval = $_POST['preval'];
        $from = $_POST['tid'];

        $ref = $_POST['ref'];
        $trans_date = date('Y-m-d');
        $this->db->trans_begin();

        for ($p = 0; $p < sizeof($pid); $p++)
        {

            $type = (empty($eid[$p])) ? 'issue' : 'endorsement';
            if ($alloc_amt[$p] != '' || $alloc_amt[$p] != 0)
            {
                if ($type == 'issue')
                {
                    $xpid = $pid[$p];
                }
                else
                    $xpid = $eid[$p];
                $data = array(
                    'from' => $from,
                    'pid' => $xpid,
                    'amount' => $alloc_amt[$p],
                    'type' => $type
                );

                $this->db->insert('cust_allocate', $data);

                if ($type == 'issue')
                {
                    $placing_pay = array(
                        'placing_slip_id' => $xpid,
                        'paydate' => $tran_date,
                        'amount' => $alloc_amt[$p],
                        'paymethod' => $memo
                    );

                    $this->db->insert('placing_slip_payamount', $placing_pay);
                }
                else
                {
                    $endorsement_pay = array(
                        'endorsement_id' => $xpid,
                        'paydate' => $tran_date,
                        'amount' => $alloc_amt[$p],
                        'paymethod' => $memo
                    );

                    $this->db->insert('endorsement_payamount', $endorsement_pay);
                }
                $alloc = $pre_alloc[$p] + $alloc_amt[$p];
                $pretype = $ptype[$p];

                $insdata = array('alloc' => $alloc);

                $this->db->where('type_no', $pretype);
                $this->db->update('customer_trans', $insdata);
                
                $totalamount += $alloc_amt[$p];
            }
        }
        $total = $totalamount + $preval;
        $udata = array('alloc' => $total);

        $this->db->where('id', $from);
        $this->db->update('customer_trans', $udata);
        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
        }
        else
        {
            $this->db->trans_commit();
            return true;
        }
    }

    /*     * **********************Bank transfer functions**************************** */

    function bank_transfer()
    {

        $accfrom1 = $_POST['from'];
        $accfrom = explode('~', $accfrom1);
        $accto1 = $_POST['to'];
        $accto = explode('~', $accto1);
        $ref = $this->accountingsmodel->get_reference_code(4);
        $qdate = $_POST['date'];
        $date = $this->mastermodel->convdatformat($qdate);
        $tdat = date('Y-m-d');

        $amount = $_POST['amount'];

        $memo = $_POST['memo'];

        $total_amt = -($amount);

        $this->db->trans_begin();

        $type = 4;  // to know which type of transaction Refer the trans_type table
        $insertvals = array('type' => $type, 'reference' => $ref); // inserting values to refs table
        $this->db->insert('refs', $insertvals);
        $ref_id = $this->db->insert_id();


        $tblValues5 = array('from_b' => $accfrom[0], 'to_b' => $accto[0], 'amount' => $amount, 'trans_date' => $date, 'ref' => $ref_id, 'memo' => $memo, 'type' => 0);
        $query = $this->db->insert('bank_to_bank', $tblValues5);


        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return 0;
        }
        else
        {
            $this->db->trans_commit();
            return $query;
        }
    }

    function updatebank_transfer()
    {
        $accfrom1 = $_POST['from'];
        $accfrom = explode('~', $accfrom1);
        $accto1 = $_POST['to'];
        $accto = explode('~', $accto1);
        $ref = $_POST['ref'];
        $qdate = $_POST['date'];
        $date = $this->mastermodel->convdatformat($qdate);
        $ref_id = $_POST['refid'];

        $amount = $_POST['amount'];

        $memo = $_POST['memo'];

        $total_amt = -($amount);

        $this->db->trans_begin();

        $tblValues5 = array('from_b' => $accfrom[0], 'to_b' => $accto[0], 'amount' => $amount, 'trans_date' => $date, 'memo' => $memo, 'type' => 0);
        $this->db->where('ref', $ref_id);
        $query = $this->db->update('bank_to_bank', $tblValues5);


        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return 0;
        }
        else
        {
            $this->db->trans_commit();
            return $query;
        }
    }

    function post_banktobank_trans($id)
    {

        $count = $this->db->query("select * from bank_to_bank where type='0' and  id='" . $id . "'");
        foreach ($count->result_array() as $row)
        {

            $date = $row['trans_date'];
            $tdate = date('Y-m-d');
            $amount = $row['amount'];
            $acc_from = $row['from_b'];
            $acc_to = $row['to_b'];
            $memo = $row['memo'];
            $total_amt = 0 - $amount;
            $ref_id = $row['ref'];
        }
        $fromacc_code = $this->customermodel->getSingleFieldValue('bank_accounts', 'account_code', 'id', $acc_from);
        $toacc_code = $this->customermodel->getSingleFieldValue('bank_accounts', 'account_code', 'id', $acc_to);
        $ref = $this->customermodel->getSingleFieldValue('refs', 'reference', 'id', $ref_id);



        $this->db->trans_begin();

        /*         * ******************************************Insert into Audit_trail***************************************************** */
        $fyear = $this->fiscalyear();
        $insValuesA = array(
            'trans_no' => $ref_id,
            'user' => $_SESSION['userid'],
            'date_trans' => $tdate,
            'fiscal_year' => $fyear,
            'gl_date' => $date
        );
        $this->db->insert('audit_trail', $insValuesA);
        /*         * ********************************************************************************** */

        $tblValues = array('type_no' => $ref_id, 'tran_date' => $date, 'account' => $fromacc_code, 'memo' => $memo, 'amount' => $total_amt);
        $str1 = $this->db->insert('gl_trans', $tblValues);
        $tblValues2 = array('type_no' => $ref_id, 'tran_date' => $date, 'account' => $toacc_code, 'memo' => '', 'amount' => $amount);
        $str = $this->db->insert('gl_trans', $tblValues2);


        $tblValues3 = array('trans_no' => $ref_id, 'bank_act' => $acc_from, 'ref' => $ref, 'trans_date' => $date, 'amount' => $total_amt);
        $query = $this->db->insert('bank_trans', $tblValues3);
        $tblValues4 = array('trans_no' => $ref_id, 'bank_act' => $acc_to, 'ref' => $ref, 'trans_date' => $date, 'amount' => $amount);
        $query = $this->db->insert('bank_trans', $tblValues4);

        $tblValues5 = array('type' => 1);
        $this->db->where('id', $id);
        $query = $this->db->update('bank_to_bank', $tblValues5);


        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return 0;
        }
        else
        {
            $this->db->trans_commit();
            return $str;
        }
    }

    function count_val($table, $field, $type)
    {
        $res = $this->db->query("select * from " . $table . " where " . $field . " like '" . $type . "'");
        return $res->num_rows();
    }

    function countcust_tra_val($table, $field, $type)
    {

        $res = $this->db->query("select * from $table c INNER JOIN bank_trans b 
                ON c.type_no=b.trans_no JOIN refs r ON r.id=b.trans_no  where c." . $field . " like'" . $type . "%'");
        return $res->num_rows();
    }

    function bank_trans($pageno, $type, $post)
    {
        if ($type == 'data')
        {

            $limit = (($pageno - 1) * 10);
            $data = array();
//<<<<<<< .mine
//
//            $res=$this->db->query("select * from bank_to_bank where type='$post' order by id  limit " . $limit .",". 10);
//=======

            $sql = "select distinct(bank_to_bank.id),bank_to_bank.ref,amount,trans_date,memo,reference,bank_to_bank.type, ba1.bank_account_name as from_b,ba2.bank_account_name as to_b from bank_to_bank INNER JOIN bank_accounts ba1  ON (bank_to_bank.from_b = ba1.id) INNER JOIN bank_accounts ba2 ON (bank_to_bank.to_b = ba2.id) join refs on refs.id= bank_to_bank.ref  where bank_to_bank.type='$post'   limit " . $limit . "," . 10;
            $res = $this->db->query($sql);
//>>>>>>> .r1039
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
        else if ($type == 'count')
        {
            $sql = "select distinct(bank_to_bank.id),bank_to_bank.ref,amount,trans_date,memo,reference,bank_to_bank.type, ba1.bank_account_name as fromAccount,ba2.bank_account_name as ToAccount from bank_to_bank INNER JOIN bank_accounts ba1  ON (bank_to_bank.from_b = ba1.id) INNER JOIN bank_accounts ba2 ON (bank_to_bank.to_b = ba2.id) join refs on refs.id= bank_to_bank.ref  where bank_to_bank.type='$post'";
            $res = $this->db->query($sql);
            return $res->num_rows();
        }
    }

    function journal_trans($pageno, $type)
    {


        if ($type == 'data')
        {

            $limit = (($pageno - 1) * 10);
            $data = array();
            $res = $this->db->query("select  distinct(r.id) as id,r.type, r.reference,bt.tran_date from gl_trans bt JOIN refs r ON r.id=bt.type_no where r.type='3' order by r.id desc   limit " . $limit . "," . 10);
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
        else if ($type == 'count')
        {
            $res = $this->db->query("select distinct(r.id)  from gl_trans bt JOIN refs r ON r.id=bt.type_no where r.type='3'");
            return $res->num_rows();
        }
    }

    function sumamount_journalpost($rid, $type)
    {
        $res = $this->db->query("select  IFNULL(sum(amount),0) as totalamount from gl_trans t JOIN refs r ON r.id=t.type_no where r.type='$type' and r.id=$rid and t.amount>0  group by t.type_no ");
        $row = $res->row()->totalamount;
        return $row;
    }

    function journal_unpost($pageno, $type)
    {


        if ($type == 'data')
        {

            $limit = (($pageno - 1) * 10);
            $data = array();

            $res = $this->db->query("select  distinct(t.reference) as id,r.type, r.reference,t.date as tran_date from unposted_journal t JOIN refs r ON r.id=t.reference where r.type='3' and t.unpost='0' order by r.id desc   limit " . $limit . "," . 10);

            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
        else if ($type == 'count')
        {
            $res = $this->db->query("select  distinct(t.reference) as id,r.type, r.reference,t.date as tran_date from unposted_journal t JOIN refs r ON r.id=t.reference where r.type='3' and t.unpost='0'");
            return $res->num_rows();
        }
    }

    function sumamount_journal($rid, $type)
    {
        $res = $this->db->query("select  IFNULL(sum(amount),0) as totalamount from unposted_journal t JOIN refs r ON r.id=t.reference where r.type='$type' and r.id=$rid and t.amount>0  group by t.reference ");
        $row = $res->row()->totalamount;
        return $row;
    }

    function banktrans_unpost($pageno, $type, $trans)
    {
        if ($type == 'data')
        {

            $limit = (($pageno - 1) * 10);
            $data = array();

            $res = $this->db->query("select  distinct(t.reference) as id,ch_date, cheque_no, r.type,t.bank_acc,t.acc_id,r.reference,t.date as tran_date 
                    from unposted_pay_dep t 
                    JOIN refs r ON r.id=t.reference left join receipt_cheque on  receipt_cheque.reference = r.id where 
                    r.type='$trans' and t.unpost='0' and r.tr_type='other' order by r.id desc   limit " . $limit . "," . 10);
            
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
        else if ($type == 'count')
        {
            $res = $this->db->query("select  distinct(t.reference) as id,r.type,t.bank_acc,t.acc_id,ch_date, cheque_no,  
                    r.reference,t.date as tran_date from unposted_pay_dep t  
                    JOIN refs r ON r.id=t.reference left join receipt_cheque on  receipt_cheque.reference = r.id  where r.type='$trans' and t.unpost='0'");
           
            return $res->num_rows();
        }
    }

    function pdc_unpost($pageno, $type, $trans)
    {
        if ($type == 'data')
        {

            $limit = (($pageno - 1) * 10);
            $data = array();

            $res = $this->db->query("select  distinct(t.reference) as id,r.type,t.bank_acc,t.acc_id,r.reference,t.date as tran_date 
                    from unposted_pay_dep t 
                    JOIN refs r ON r.id=t.reference 
                    where t.unpost='0'  and r.tr_type='post_dated_cheque' order by r.id desc   limit " . $limit . "," . 10);
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
        else if ($type == 'count')
        {
            $res = $this->db->query("select  distinct(t.reference) as id,r.type,t.bank_acc,t.acc_id, r.reference,t.date as tran_date
                    from unposted_pay_dep t 
                    JOIN refs r ON r.id=t.reference 
                    where  t.unpost='0' and r.tr_type='post_dated_cheque'");
            return $res->num_rows();
        }
    }

    function sumamount_unpost($rid, $type)
    {
        $res = $this->db->query("select  IFNULL(sum(amount),0) as totalamount from unposted_pay_dep t JOIN refs r ON r.id=t.reference where r.type='$type' and r.id=$rid group by t.reference ");
        $row = $res->row()->totalamount;
        return $row;
    }

    function delete_up_journal($table, $id)
    {
        $this->db->where('reference', $id);
        $back = $this->db->delete($table);

        if ($table == 'auto_journal')
        {
            $this->db->where('id', $id);
            $back = $this->db->delete('temp_refs');
        }
        $this->db->where('id', $id);
        $back = $this->db->delete('refs');
        return $back;
    }

    function autojournal_trans($pageno, $type)
    {


        if ($type == 'data')
        {

            $limit = (($pageno - 1) * 10);
            $data = array();

            $res = $this->db->query("select  distinct(aj.reference) as id,r.type, r.reference as ref,aj.title,aj.date from auto_journal aj JOIN temp_refs r ON r.id=aj.reference where r.type='3'    limit " . $limit . "," . 10);
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
        else if ($type == 'count')
        {
            $res = $this->db->query("select  distinct(aj.reference) as id,r.type, r.reference as ref,aj.title,aj.date from auto_journal aj JOIN temp_refs r ON r.id=aj.reference where r.type='3' ");
            return $res->num_rows();
        }
    }

    function sumamount_autojournal($rid, $type)
    {
        $res = $this->db->query("select  IFNULL(sum(amount),0) as totalamount from auto_journal t JOIN temp_refs r ON r.id=t.reference where r.type='$type' and r.id=$rid and t.amount>0  group by t.reference ");
        $row = $res->row()->totalamount;
        return $row;
    }

    function showpaymentvouchertrans($ref)
    {
        $data = array();
        $res = $this->db->query("select bt.type_no,bt.tran_date,bt.amount as amount,cm.account_code,cm.account_name,r.reference FROM  `gl_trans` bt JOIN refs r ON r.id = bt.`type_no`
            join chart_master cm on cm.account_code=bt.account
            WHERE  r.reference='$ref' having amount >0 order by r.id  desc ");

        $data['rvcount'] = $res->num_rows();
        $data['result'] = $res;

        return $data;
    }

    function showunpostedpaymentvouchertrans($ref)
    {
        $data = array();
        $res = $this->db->query("select  t.reference as id,r.type,t.bank_acc,t.acc_id,cm.account_name,cm.account_code,t.amount as amount, r.reference,t.date as tran_date from unposted_pay_dep t JOIN refs r ON r.id=t.reference
                    join chart_master cm on cm.account_code=t.account
                    where t.unpost='0' and r.reference='$ref'  having amount >0  order by r.id desc");

        $data['rvcount'] = $res->num_rows();
        $data['result'] = $res;

        return $data;
    }

    function bankpayment_trans($pageno, $type)
    {

        if ($type == 'data')
        {

            $limit = (($pageno - 1) * 10);
            $data = array();
            $res = $this->db->query("select r.reference as reference, trans_no, trans_date, ch_date,cheque_no from bank_trans bt 
                JOIN refs r ON r.id=bt.trans_no LEFT JOIN receipt_cheque ON receipt_cheque.reference = r.id where  r.type='1' order by r.id desc   limit " . $limit . "," . 10);
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
        else if ($type == 'count')
        {
            $res = $this->db->query("select * from bank_trans bt JOIN refs r ON r.id=bt.trans_no LEFT JOIN receipt_cheque ON receipt_cheque.reference = r.id where r.type='1'  ");
            return $res->num_rows();
        }
    }

//1 amount>0 2 amount<0if(r.type=1,if(amount>0,amount,0) ,if(amount<0,amount,0)) having amount >0
    function showpdctrans($ref)
    {
        $data = array();
        $res = $this->db->query("select r.type ,bt.type_no,bt.tran_date,bt.amount as amount,cm.account_code,cm.account_name,r.reference 
            FROM  `gl_trans` bt 
            JOIN refs r ON r.id = bt.`type_no`
            join chart_master cm on cm.account_code=bt.account
            WHERE r.reference='$ref' and r.tr_type='post_dated_cheque'  order by r.id  desc ");

        $data['rvcount'] = $res->num_rows();
        $data['result'] = $res;

        return $data;
    }

    function showreceiptvouchertrans($ref)
    {
        $data = array();
        $res = $this->db->query("select bt.type_no,bt.tran_date,bt.amount as amount,cm.account_code,cm.account_name,r.reference
                FROM  `gl_trans` bt JOIN refs r ON r.id = bt.`type_no`
            join chart_master cm on cm.account_code=bt.account
            WHERE r.type =  '2' and r.reference='$ref' having amount <0 order by r.id  desc ");

        $data['rvcount'] = $res->num_rows();
        $data['result'] = $res;

        return $data;
    }

    function showunpostedpdctrans($ref)
    {
        $data = array();
        $res = $this->db->query("select  t.reference as id,r.type,t.bank_acc,t.acc_id,
            cm.account_name,cm.account_code,t.amount as amount, r.reference,t.date as tran_date
            from unposted_pay_dep t JOIN refs r ON r.id=t.reference
                    join chart_master cm on cm.account_code=t.account
                    where t.unpost='0' and r.id='$ref'    order by r.id desc");
        $data['rvcount'] = $res->num_rows();
        $data['result'] = $res;

        return $data;
    }

    function showunpostedreceiptvouchertrans($ref)
    {
        $data = array();
        $res = $this->db->query("select  t.reference as id,r.type,t.bank_acc,t.acc_id,cm.account_name,cm.account_code,t.amount as amount, r.reference,t.date as tran_date from unposted_pay_dep t JOIN refs r ON r.id=t.reference
                    join chart_master cm on cm.account_code=t.account
                    where t.unpost='0' and r.reference='$ref'  having amount <0  order by r.id desc");

        $data['rvcount'] = $res->num_rows();
        $data['result'] = $res;

        return $data;
    }

    function bankdep_trans($pageno, $type)
    {

        if ($type == 'data')
        {

            $limit = (($pageno - 1) * 10);
            $data = array();

            $res = $this->db->query("select r.reference as reference, trans_no, trans_date, ch_date,cheque_no  from bank_trans bt JOIN refs r ON r.id=bt.trans_no LEFT JOIN receipt_cheque ON receipt_cheque.reference = r.id where  r.type='2' order by r.id desc   limit " . $limit . "," . 10);
//            

            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
        else if ($type == 'count')
        {
            $res = $this->db->query("select r.reference as reference, trans_no, trans_date, ch_date,cheque_no  from bank_trans bt JOIN refs r ON r.id=bt.trans_no LEFT JOIN receipt_cheque ON receipt_cheque.reference = r.id where  r.type='2'  ");
            return $res->num_rows();
        }
    }

    function get_pdc_report($type, $cid, $cheque_from_date, $cheque_to_date, $tr_type, $value = "")
    {
        $data = array();
        $data['customer'] = array();

        $data['c_id'] = array($cid);
        $where = "";

        if ($cid > 0)
        {
            $where.=" and customers.id='" . $cid . "'";
        }
        if ($tr_type != "all")
        {
            $where.=" and unpost='" . $tr_type . "'";
        }
        if ($value != "")
        {
            $where.=" and account='" . $value . "'";
        }
        if ($cheque_from_date != 0)
        {
            $date1 = $this->mastermodel->convdatformat($cheque_from_date);
            if ($date1 != "")
            {
                $where.=" and rc.ch_date >='" . $date1 . "'";
            }
        }
        if ($cheque_to_date != 0)
        {
            $date2 = $this->mastermodel->convdatformat($cheque_to_date);
            if ($date2 != "")
            {
                $where.=" and rc.ch_date <='" . $date2 . "'";
            }
        }
        $res = $this->db->query(" select * , customers.id as c_id , r.reference as tr_no,r.id as id
                from unposted_pay_dep pd 
                JOIN refs r ON r.id=pd.reference 
                JOIN receipt_cheque rc ON rc.reference=pd.reference
                JOIN transaction_types tt ON tt.id=r.type
                JOIN customers on customers.code=pd.account          
                where  r.tr_type='post_dated_cheque' $where order by rc.ch_date asc");

        $rt = $res->result_array();
        $data['transdet'] = $rt;
        $data['refs_count'] = array();
        foreach ($rt as $row)
        {
            if (isset($data['refs_count'][$row['id']]))
            {
                $data['refs_count'][$row['id']]+=1;
            }
            else
            {
                $data['refs_count'][$row['id']] = 1;
            }
            $data['c_id'][] = $row['c_id'];
        }

        $qry = "select customers.id as cid,customers.code as code,customers.type,customer_contact.address
                    , customer_contact.postbox,country.countryname
                    , city.cityname FROM customers
                    INNER JOIN  customer_contact ON (customer_contact.customer_id = customers.id)
                    INNER JOIN  country
                        ON (country.id = customer_contact.country)
                    INNER JOIN  city
                        ON (city.id = customer_contact.city)  where customers.id in (" . implode(',', $data['c_id']) . ") ";

        $cdet = $this->db->query($qry);
        $rt = $cdet->result_array();
        foreach ($rt as $row)
        {
            $data['customer'][$row['code']] = $row;
        }

        $res = $this->db->query($qry);
        $data['openbalance'] = $res->row();


//        $res = $this->db->query(" select *  , r.reference as tr_no
//                from unposted_pay_dep pd 
//                JOIN refs r ON r.id=pd.reference 
//                JOIN receipt_cheque rc ON rc.reference=pd.reference
//                JOIN transaction_types tt ON tt.id=r.type
//                JOIN customers on customers.code=pd.account
//                LEFT JOIN customer_personal_ind ON customer_personal_ind.customer_id=customers.id
//                where  r.type='2'  and r.tr_type='post_dated_cheque' ");
//        $data['transdet']=$res->result_array();
//        var_dump($data['transdet']);
        return $data;
    }

    function post_dated_cheque($pageno, $type)
    {

        if ($type == 'data')
        {

            $limit = (($pageno - 1) * 10);
            $data = array();

            $res = $this->db->query("select *,bt.trans_no as trans_no,fy.closed as fyclosed ,r.reference as tr_no,r.id as id,r.type                
                from bank_trans bt                 
                JOIN refs r ON r.id=bt.trans_no         
                JOIN gl_trans gl ON gl.type_no=r.id
                join chart_master cm on cm.account_code=gl.account
                JOIN transaction_types tt ON tt.id=r.type
                JOIN audit_trail au ON au.trans_no=r.id 
                JOIN fiscal_year fy ON fy.id=au.fiscal_year                
                where r.tr_type='post_dated_cheque' 
                group by bt.trans_no order by r.id desc   limit " . $limit . "," . 10);
            $k = 1;
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
        else if ($type == 'count')
        {
            $res = $this->db->query("select distinct(r.id) from bank_trans bt 
                JOIN refs r ON r.id=bt.trans_no 
                JOIN gl_trans gl ON gl.type_no=r.id
                JOIN transaction_types tt ON tt.id=r.type
                JOIN audit_trail au ON au.trans_no=r.id 
                JOIN fiscal_year fy ON fy.id=au.fiscal_year                
                where r.tr_type='post_dated_cheque'  ");
            return $res->num_rows();
        }
    }

    function custom_trans($table, $pageno, $field, $type)
    {

        $limit = (($pageno - 1) * 10);
        $data = array();

        $res = $this->db->query("select  distinct(c.id) as id,c.alloc,r.reference, c.tran_date,c.amount,c.account,c.memo,b.bank_act,
                b.trans_no, ch_date,cheque_no from $table c INNER JOIN bank_trans b ON c.type_no=b.trans_no 
                JOIN refs r ON r.id=b.trans_no left join receipt_cheque rc ON rc.reference=r.id
                where c." . $field . " like'" . $type . "%' order by c.id desc limit " . $limit . "," . 10);
        foreach ($res->result_array() as $row)
        {
            $data[] = $row;
        }
        return $data;
    }

    function singlecustom_trans($id)
    {


        $data = array();

        $res = $this->db->query("select c.tran_date,c.amount,c.account,c.memo,b.bank_act,b.ref from customer_trans c INNER JOIN bank_trans b ON c.type_no=b.trans_no where c.id=$id ");
        foreach ($res->result_array() as $row)
        {
            $data[] = $row;
        }
        return $data;
    }

    function bank_bal($id)
    {


        $query = $this->db->query("select sum( amount ) as amount from bank_trans where bank_act='$id'");
        if ($query->num_rows() > 0)
        {
            $row = $query->row();
            $type = $row->amount;
            $type1 = '<font style="color:gray;"><label>Balance:</label>' . $type . '.00</font>';
        }
        if ($type == "")
        {
            $type = 0;
            $type1 = '0.00';
        }
        echo $type1;
    }

    /*     * ***********************function for journal entry******************************** */

    function add_journal($ref_id)
    {

        $count = $this->db->query("select * from unposted_journal where unpost='0' and  reference='" . $ref_id . "'");
        $str = 0;
        $insert_audit = 0;
        $this->db->trans_begin();

        foreach ($count->result_array() as $row)
        {

            $date = $row['date'];
            $tdate = date('Y-m-d');
            $hid = $row['account_code'];
            $bank_id = $row['account_id'];
            $amount = $row['amount'];
            $memo = $row['memo'];

            if ($insert_audit == 0)
            {
                $fyear = $this->fiscalyear();
                $insValuesA = array(
                    'trans_no' => $ref_id,
                    'user' => $_SESSION['userid'],
                    'date_trans' => $tdate,
                    'fiscal_year' => $fyear,
                    'gl_date' => $date
                );
                $this->db->insert('audit_trail', $insValuesA);
                $insert_audit = 1;
            }


            $tblValues = array('type_no' => $ref_id, 'tran_date' => $date, 'account' => $hid, 'memo' => $memo, 'amount' => $amount);

            $str = $this->db->insert('gl_trans', $tblValues);
            $ref = $this->customermodel->getSingleFieldValue('refs', 'reference', 'id', $ref_id);

            $code = $row['account_code'];

            if (strncasecmp("IDL", $code, 3) == 0 || strncasecmp("CRP", $code, 3) == 0)
            {
                $tblValuescu = array('type_no' => $ref_id, 'tran_date' => $date, 'account' => $code, 'memo' => $memo, 'amount' => $amount);
                $str = $this->db->insert('customer_trans', $tblValuescu);
            }
            if (strncasecmp("EMP", $code, 3) == 0 || strncasecmp("AGE", $code, 3) == 0)
            {
                $tblValuescu = array('type_no' => $ref_id, 'tran_date' => $date, 'account' => $code, 'memo' => $memo, 'amount' => $amount);
                $str = $this->db->insert('agent_trans', $tblValuescu);
            }
            if (strncasecmp("INS", $code, 3) == 0)
            {
                $tblValuescu = array('type_no' => $ref_id, 'tran_date' => $date, 'account' => $code, 'memo' => $memo, 'amount' => $amount);
                $str = $this->db->insert('company_trans', $tblValuescu);
            }



            if ($bank_id >= 1)
            {

                $tblValues3 = array('trans_no' => $ref_id, 'bank_act' => $bank_id, 'ref' => $ref, 'trans_date' => $date, 'amount' => $amount);
                $query = $this->db->insert('bank_trans', $tblValues3);
            }
            $posted_val = array('unpost' => 1);
            $this->db->where('reference', $ref_id);
            $str = $this->db->update('unposted_journal', $posted_val);


            if ($row['reverse'] == 'true')
            {

                $date1 = explode('-', $date);
                $newmonth = $date1[1] + 1;
                $year = $date1[0];
                if ($newmonth > 12)
                {
                    $newmonth = 1;
                    $year = $year + 1;
                }
                $newdate = $year . '-' . $newmonth . '-1';


                if ($insert_audit == 1)
                {
                    $trans_type = 3;
                    $tdat = date('Y-m-d');
                    $ref = $this->customermodel->getSingleFieldValue('refs', 'reference', 'id', $ref_id);
                    $insertvals = array('type' => $trans_type, 'reference' => $ref); // inserting values to refs table
                    $this->db->insert('refs', $insertvals);
                    $ref_id1 = $this->db->insert_id();
                    $fyear = $this->fiscalyear();
                    $insValuesA = array(
                        'trans_no' => $ref_id1,
                        'user' => $_SESSION['userid'],
                        'date_trans' => $tdat,
                        'fiscal_year' => $fyear,
                        'gl_date' => $newdate
                    );
                    $this->db->insert('audit_trail', $insValuesA);
                    $insert_audit = 2;
                }
                /*                 * ******************Insert into gl_trans and bank _trans****************** */



                if ($amount >= 1)
                {
                    $amount = -$amount;
                }
                else if ($amount <= -1)
                {
                    $amts = str_replace("-", "", $amount);
                    $amount = $amts;
                }
                else
                {
                    $amount = 0;
                }


                $tblValues = array('type_no' => $ref_id1, 'tran_date' => $newdate, 'account' => $hid, 'memo' => $memo, 'amount' => $amount);
                $str = $this->db->insert('gl_trans', $tblValues);


                $code = $hid;

                if (strncasecmp("IDL", $code, 3) == 0 || strncasecmp("CRP", $code, 3) == 0)
                {
                    $tblValuescu = array('type_no' => $ref_id, 'tran_date' => $date, 'account' => $code, 'memo' => $memo, 'amount' => $amount);
                    $str = $this->db->insert('customer_trans', $tblValuescu);
                }
                if (strncasecmp("EMP", $code, 3) == 0 || strncasecmp("AGE", $code, 3) == 0)
                {
                    $tblValuescu = array('type_no' => $ref_id, 'tran_date' => $date, 'account' => $code, 'memo' => $memo, 'amount' => $amount);
                    $str = $this->db->insert('agent_trans', $tblValuescu);
                }
                if (strncasecmp("INS", $code, 3) == 0)
                {
                    $tblValuescu = array('type_no' => $ref_id, 'tran_date' => $date, 'account' => $code, 'memo' => $memo, 'amount' => $amount);
                    $str = $this->db->insert('company_trans', $tblValuescu);
                }

                if ($bank_id >= 1)
                {

                    $tblValues3 = array('trans_no' => $ref_id1, 'bank_act' => $bank_id, 'ref' => $ref, 'trans_date' => $newdate, 'amount' => $amount);
                    $query = $this->db->insert('bank_trans', $tblValues3);
                }
            }
        }

        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            echo 0;
        }
        else
        {
            $this->db->trans_commit();
            echo $str;
        }
    }

    function add_unposted_journal()
    {

        $reverse = $_POST['reverse'];
        $ref = $this->accountingsmodel->get_reference_code(3);
        $qdate = $_POST['date'];
        $date = $this->mastermodel->convdatformat($qdate);
        $counter = $_POST['counter_check'];
        $trans_type = 3;  // Type is journal entry.Refer table trans_type

        $this->db->trans_begin();
        $update = $_POST['refid'];
        if ($update != 0)
        {
            $delete = $this->db->delete('unposted_journal', array('reference' => $update));
            $ref_id = $update;
        }
        else
        {
            $insertvals = array('type' => $trans_type, 'reference' => $ref); // inserting values to refs table
            $this->db->insert('refs', $insertvals);
            $ref_id = $this->db->insert_id();
        }
        /*         * ******************Insert into temperory table unposted_journal****************** */


        for ($i = 0; $i <= $counter; $i++)
        {
            if (isset($_POST['code_id_' . $i]))
            {

                $memo = $_POST['memo_' . $i];


                $acccode = $_POST['code_id_' . $i];

                $debit = $_POST['debit_' . $i];
                $credit = $_POST['credit_' . $i];
                if ($debit >= 1)
                {
                    $amount = $debit + $credit;
                }
                else if ($credit >= 1)
                {
                    $amount = -($debit + $credit);
                }
                else
                {
                    $amount = 0;
                }

                $bank_id = $this->customermodel->getSingleFieldValue('bank_accounts', 'id', 'account_code', $acccode);
                $tblValues = array('reference' => $ref_id, 'date' => $date, 'reverse' => $reverse, 'account_code' => $acccode, 'account_id' => $bank_id, 'amount' => $amount, 'memo' => $memo, 'unpost' => 0);
                $str = $this->db->insert('unposted_journal', $tblValues);
            }
        }




        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return 0;
        }
        else
        {
            $this->db->trans_commit();
            return $str;
        }
    }

    function add_autojournal($temp_id, $qdate)
    {

        $count = $this->db->query("select * from auto_journal where  reference='" . $temp_id . "'");
        //$ref=$this->customermodel->getSingleFieldValue('temp_refs','reference','id',$temp_id);


        $ref = $this->accountingsmodel->get_reference_code(3);

        $str = 0;
        $insert_audit = 0;
        $date = $this->mastermodel->convdatformat($qdate);
        $tdat = date('Y-m-d');
        $this->db->trans_begin();
        foreach ($count->result_array() as $row)
        {


            $hid = $row['account_code'];
            $bank_id = $row['account_id'];
            $amount = $row['amount'];
            $memo = $row['memo'];

            if ($insert_audit == 0)
            {

                $trans_type = 3;  // Type is journal entry.Refer table trans_type
                $insertvals = array('type' => $trans_type, 'reference' => $ref); // inserting values to refs table
                $this->db->insert('refs', $insertvals);
                $ref_id = $this->db->insert_id();
                $fyear = $this->fiscalyear();
                $insValuesA = array(
                    'trans_no' => $ref_id,
                    'user' => $_SESSION['userid'],
                    'date_trans' => $tdat,
                    'fiscal_year' => $fyear,
                    'gl_date' => $date
                );
                $this->db->insert('audit_trail', $insValuesA);
                $insert_audit = 1;
            }


            $tblValues = array('type_no' => $ref_id, 'tran_date' => $date, 'account' => $hid, 'memo' => $memo, 'amount' => $amount);

            $str = $this->db->insert('gl_trans', $tblValues);
            $ref = $this->customermodel->getSingleFieldValue('refs', 'reference', 'id', $ref_id);

            if ($bank_id >= 1)
            {

                $tblValues3 = array('trans_no' => $ref_id, 'bank_act' => $bank_id, 'ref' => $ref, 'trans_date' => $date, 'amount' => $amount);
                $query = $this->db->insert('bank_trans', $tblValues3);
            }
            $posted_val = array('unpost' => 1);
            $this->db->where('reference', $ref_id);
            $str = $this->db->update('unposted_journal', $posted_val);
        }

        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return 0;
        }
        else
        {
            $this->db->trans_commit();
            echo $str;
        }
    }

    /*     * *********************Get customer account id from cust_id************************** */

    function get_acc_id($table, $tfield, $value)
    {

        $field = 'account_code';
        $data = $this->db->query("select chart_master.account_code from chart_master inner join $table on $table.$tfield=chart_master.account_code where $table.id= " . $value);
        $result = $data->row();
        if ($result)
        {
            return $result->$field;
        }
        else
        {
            return "";
        }
    }

    function getbank_acc($type)
    {

        if ($type == 1)
        {
            $qry = "select employeeid as code,name as name,id as id,'$type' as type from staffpersonaldetails";
            $data = $this->db->query($qry);
        }
        else if ($type == 2)
        {
            $qry = "select id as id, company_code as code,company_name as name,'$type' as type from insurance_company";
            $data = $this->db->query($qry);
        }
        return $data;
    }

    function get_acc_sub($type)
    {


        if ($type == 1)
        {
            $qry = "select employeeid as code,name as name,id as id,'$type' as type from staffpersonaldetails";
            $data = $this->db->query($qry);
        }
        else if ($type == 2)
        {
            $qry = "select id as id, company_code as code,company_name as name,'$type' as type from insurance_company";
            $data = $this->db->query($qry);
        }
        else if ($type == 3)
        {
            $qry = "select c.id as id, c.code as code,IFNULL(cp.insured,cc.insured)  as name,'$type' as type  from customers c LEFT JOIN customer_corp_info cc ON c.id = cc.customer_id LEFT JOIN customer_personal_ind cp ON c.id = cp.customer_id ";
            $data = $this->db->query($qry);
        }
        return $data;
    }

    function getpayment_list($val, $date1 = "", $date2 = "")
    {

        $dat = explode("~", $val);

        if ($dat[0] == 1)
        {
            $acid = $this->customermodel->getSingleFieldValue('staffpersonaldetails', 'id', 'employeeid', $dat[1]);
            $qry = "select 
           ps.quotation_ref
           , '' as eid
           , pspd.placing_slip_id as pid
           , ct.type_no as tno
           , ct.amount as tamount
           ,ct.alloc as calloc,pspd.premium,pspd.policy_fees
          
           ,pspd.brokerage,pspd.ispercentage
           ,pssh.percentage
           ,policynote.policyno,reference
           , ct.tran_date as tran_date
           ,cover, ps.remarks as description
          
           from placing_slip_stakeholders pssh
           join placing_slip_premiumdetails pspd on pspd.placing_slip_id=pssh.placing_slip_id
            INNER JOIN placing_slip ps on pspd.placing_slip_id=ps.id
           INNER JOIN placing_slip_refs psr ON psr.pslip_id= pspd.placing_slip_id and psr.type='issue'
           INNER JOIN agent_trans ct ON (ct.type_no=psr.id and ct.account= '$dat[1]')
           INNER JOIN refs on refs.id=ct.type_no
           inner join covers on covers.id=ps.cover_id
           left join policynote on ps.quotation_ref=policynote.quotation_ref
           where pssh.staffid=$acid";
            if (!empty($date1) && !empty($date2))
            {
                $qry.=" and ct.tran_date between '$date1' and '$date2' ";
            }
            $qry.=" group by ps.id";

            $qry.=" UNION select 
           e.endrefno as quotation_ref
           ,e.id as eid 
           , '' as pid
           , ct.type_no as tno
           , ct.amount as tamount
           ,ct.alloc as calloc,e.premiumchange as premium,e.policyfeeschange as policy_fees
          
           ,e.brokerage,e.ispercentage
           ,pssh.percentage
           ,e.endpolicyno,reference
            ,  ct.tran_date as tran_date
        ,cover, e.remarks as description
        
            from endorsement e
            join policynote on policynote.id=e.policyid
            join placing_slip on placing_slip.quotation_ref= policynote.quotation_ref 
           join placing_slip_stakeholders pssh on pssh.placing_slip_id=placing_slip.id
           join placing_slip_premiumdetails pspd on pspd.placing_slip_id=pssh.placing_slip_id
           INNER JOIN placing_slip_refs psr ON psr.pslip_id= e.id and psr.type='endorsement'
           INNER JOIN agent_trans ct ON (ct.type_no=psr.id and ct.account= '$dat[1]')
           INNER JOIN refs on refs.id=ct.type_no
           inner join covers on covers.id=placing_slip.cover_id 
           
           where pssh.staffid=$acid ";
            if (!empty($date1) && !empty($date2))
            {
                $qry.=" and ct.tran_date between '$date1' and '$date2' ";
            }

            $qry.=" group by e.id";
            $qry .= " ORDER BY tran_date DESC";

            $data = $this->db->query($qry);
        }
        else if ($dat[0] == 2)
        {
            $acid = $this->customermodel->getSingleFieldValue('insurance_company', 'id', 'company_code', $dat[1]);
            $qry = "select ps.quotation_ref
           ,'' as eid
           , pspd.placing_slip_id as pid
           , ct.type_no as tno
           , ct.amount as tamount
           ,ct.alloc as calloc, pspd.premium,pspd.policy_fees
           
           ,pspd.brokerage,pspd.ispercentage
            ,policynote.policyno,'' as endpolicyno,reference
             , ct.tran_date as tran_date
          ,cover,  ps.remarks as description
          
           from  placing_slip_premiumdetails pspd
           INNER JOIN placing_slip ps on pspd.placing_slip_id=ps.id
           INNER JOIN placing_slip_refs psr ON psr.pslip_id= pspd.placing_slip_id and psr.type='issue'
           INNER JOIN company_trans ct ON ct.type_no=psr.id
           INNER JOIN refs on refs.id=ct.type_no
            inner join covers on covers.id=ps.cover_id 
           left join policynote on ps.quotation_ref=policynote.quotation_ref
           where pspd.insurance_company_id=$acid and amount like '-%'";

            if (!empty($date1) && !empty($date2))
            {
                $qry.=" and ct.tran_date between '$date1' and '$date2' ";
            }

            $qry.=" group by ps.id";

            $qry.=" UNION select 
           e.endrefno as quotation_ref
           ,e.id as eid 
           , '' as pid
           , ct.type_no as tno
           , ct.amount as tamount
           ,ct.alloc as calloc,e.premiumchange as premium,e.policyfeeschange as policy_fees
          
           ,e.brokerage,e.ispercentage
          ,policynote.policyno
           ,e.endpolicyno,reference
             , ct.tran_date as tran_date
        ,cover,  e.remarks as description
      
            from endorsement e
            join policynote on policynote.id=e.policyid
            join placing_slip on placing_slip.quotation_ref= policynote.quotation_ref 
            join placing_slip_premiumdetails pspd on pspd.placing_slip_id=placing_slip.id
           INNER JOIN placing_slip_refs psr ON psr.pslip_id= e.id and psr.type='endorsement'
           INNER JOIN company_trans ct ON (ct.type_no=psr.id)
           INNER JOIN refs on refs.id=ct.type_no
             inner join covers on covers.id=placing_slip.cover_id 
            where pspd.insurance_company_id=$acid and amount like '-%'";

            if (!empty($date1) && !empty($date2))
            {
                $qry.=" and ct.tran_date between '$date1' and '$date2' ";
            }

            $qry.=" group by e.id";
            $qry .= " ORDER BY tran_date DESC";
            $data = $this->db->query($qry);
        }
        else if ($dat[0] == 3)
        {
            $acid = $this->customermodel->getSingleFieldValue('insurance_company', 'id', 'company_code', $dat[1]);
            $qry = "select ps.quotation_ref
           ,'' as eid
           , pspd.placing_slip_id as pid
           , ct.type_no as tno
           , ct.amount as tamount
           ,ct.alloc as calloc, pspd.premium,pspd.policy_fees
           
           ,pspd.brokerage,pspd.ispercentage
            ,policynote.policyno,'' as endpolicyno,reference
             , ct.tran_date as tran_date
          ,cover,  ps.remarks as description
          
           from  placing_slip_premiumdetails pspd
           INNER JOIN placing_slip ps on pspd.placing_slip_id=ps.id
           INNER JOIN placing_slip_refs psr ON psr.pslip_id= pspd.placing_slip_id and psr.type='issue'
           INNER JOIN company_trans ct ON ct.type_no=psr.id
           INNER JOIN refs on refs.id=ct.type_no
            inner join covers on covers.id=ps.cover_id 
           left join policynote on ps.quotation_ref=policynote.quotation_ref
           where pspd.insurance_company_id=$acid and ct.amount NOT like '-%' and pspd.payment_method = 'insurance_company'";

            if (!empty($date1) && !empty($date2))
            {
                $qry.=" and ct.tran_date between '$date1' and '$date2' ";
            }

            $qry.=" group by ps.id";

            $qry.=" UNION select 
           e.endrefno as quotation_ref
           ,e.id as eid 
           , '' as pid
           , ct.type_no as tno
           , ct.amount as tamount
           ,ct.alloc as calloc,e.premiumchange as premium,e.policyfeeschange as policy_fees
          
           ,e.brokerage,e.ispercentage
          ,policynote.policyno
           ,e.endpolicyno,reference
             , ct.tran_date as tran_date
        ,cover,  e.remarks as description
      
            from endorsement e
            join policynote on policynote.id=e.policyid
            join placing_slip on placing_slip.quotation_ref= policynote.quotation_ref 
            join placing_slip_premiumdetails pspd on pspd.placing_slip_id=placing_slip.id
           INNER JOIN placing_slip_refs psr ON psr.pslip_id= e.id and psr.type='endorsement'
           INNER JOIN company_trans ct ON (ct.type_no=psr.id)
           INNER JOIN refs on refs.id=ct.type_no
             inner join covers on covers.id=placing_slip.cover_id 
            where pspd.insurance_company_id=$acid and e.paymentoptions = 'insurance_company'";

            if (!empty($date1) && !empty($date2))
            {
                $qry.=" and ct.tran_date between '$date1' and '$date2' ";
            }

            $qry.=" group by e.id";
            $qry .= " ORDER BY tran_date DESC";
            $data = $this->db->query($qry);
        }
        return $data;
    }

    function postdatedcheque_unpostpayment()
    {

        $transact_type = $_POST['bank_trans_type'];
        $acccode1 = "";
        $acccode = "";
        $counter = $_POST['counter_check'];
        $date = date("Y-m-d");
        $ref = "";
//        $ref = $this->accountingsmodel->get_reference_code($_POST['pay_n_dep']);

        $this->db->trans_begin();
        $trans_type = $_POST['pay_n_dep'];
        $str = 0;

        $update = $_POST['refid'];
        $method = 'cheque';

        if ($update != 0)
        {
            $delete = $this->db->delete('unposted_pay_dep', array('reference' => $update));
            $delete_ch = $this->db->delete('receipt_cheque', array('reference' => $update));
            $ref_id = $update;
        }
        else
        {
            $insertvals = array('type' => $trans_type, 'reference' => $ref, 'tr_type' => 'post_dated_cheque'); // inserting values to refs table
            $this->db->insert('refs', $insertvals);
            $ref_id = $this->db->insert_id();
        }

        /*         * ************************************************************************************** */

        for ($i = 0; $i <= $counter; $i++)
        {
            if (isset($_POST['amount_' . $i]))
            {
                $hid = $_POST['hidedesc_' . $i];
                $memo = "By Cheque";
                $code = $_POST['code_' . $i];

                $cre_amo = $_POST['amount_' . $i];
                $amount = $cre_amo;
                if (ISSET($_POST['to_bank']))
                {
                    $pay_to = $_POST['to_bank'];
                }
                else
                {
                    $pay_to = 0;
                }
                if ($trans_type == 1)
                {   // For Bank Payment
                    $sumamount = $_POST['sumamount'];
                    //$pay_to=$_POST['payment_to'];
                }
                else if ($trans_type == 2)
                {   // For Bank Deposit
                    $sumamount = -($_POST['sumamount']);
                    $pay_to = 0;
                }
                $tblValues = array(
                    'reference' => $ref_id,
                    'acc_id' => "",
                    'date' => $date,
                    'bank_acc' => "",
                    'memo' => $memo,
                    'amount' => $amount,
                    'account' => $code,
                    'unpost' => 0,
                    'type' => $trans_type,
                    'pay_to' => $pay_to,
                    'method' => $method);
                $str = $this->db->insert('unposted_pay_dep', $tblValues);
            }
        }


        if ($method == 'cheque')
        {
            $ch_date = $_POST['ch_date'];
            $ch_date = $this->mastermodel->convdatformat($ch_date);
            $bname = $_POST['bankname'];
            $ch_no = $_POST['ch_no'];
            $chdetails = array('reference' => $ref_id, 'ch_date' => $ch_date, 'bank_name' => $bname, 'cheque_no' => $ch_no);
            $str = $this->db->insert('receipt_cheque', $chdetails);
        }
        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return 0;
        }
        else
        {
            $this->db->trans_commit();
            return $str;
        }
    }

    function update_pdc($rid)
    {
        $trans_type = $_POST['pay_n_dep'];
        $ref = $this->accountingsmodel->get_reference_code($trans_type);
        $tblValues = array(
            'reference' => $ref,
            'type' => $_POST['pay_n_dep'],
        );
        $this->db->where('id', $rid);
        $this->db->update('refs', $tblValues);

        $acccode1 = $_POST['bankacc'];
        $acccode = explode('~', $acccode1);


        if ($trans_type == 2)
        {
            $this->db->set('amount', '0-amount', FALSE);
        }
        $tblValues = array(
            'acc_id' => $acccode[0],
            'bank_acc' => $acccode[1],
            'date' => $this->mastermodel->convdatformat($_POST['date'])
        );


        $this->db->where('reference', $rid);

        $str = $this->db->update('unposted_pay_dep', $tblValues);
    }

    function bankaccount_unpostpayment()
    {
        $transact_type = $_POST['bank_trans_type'];
        $acccode1 = $_POST['bankacc'];
        $acccode = explode('~', $acccode1);
        $qdate = $_POST['date'];
        $date = $this->mastermodel->convdatformat($qdate);
        $ref = $this->accountingsmodel->get_reference_code($_POST['pay_n_dep']);
        $this->db->trans_begin();
        $type = explode('~', $acccode1);
        $trans_type = $_POST['pay_n_dep'];
        $str = 0;
        $counter = $_POST['counter_check'];
        $update = $_POST['refid'];
        if (isset($_POST['method']))
        {
            $method = $_POST['method'];
        }
        else
        {
            $method = '';
        }
        if ($update != 0)
        {
            $delete = $this->db->delete('unposted_pay_dep', array('reference' => $update));
            $delete_ch = $this->db->delete('receipt_cheque', array('reference' => $update));
            $delete_bn = $this->db->delete('payment_bank_info', array('reference' => $update));
            $ref_id = $update;
        }
        else
        {
            $insertvals = array('type' => $trans_type, 'reference' => $ref); // inserting values to refs table
            $this->db->insert('refs', $insertvals);
            $ref_id = $this->db->insert_id();
        }
        /*         * ************************************************************************************** */
        for ($i = 0; $i <= $counter; $i++)
        {
            if (isset($_POST['amount_' . $i]))
            {
                $hid = $_POST['hidedesc_' . $i];
                $memo = $_POST['memo_' . $i];
                $code = $_POST['code_' . $i];
                if ($trans_type == 1)
                {   // For Bank Payment
                    $cre_amo = $_POST['amount_' . $i];
                    $amount = $cre_amo;
                    $sumamount = $_POST['sumamount'];
                    //$pay_to=$_POST['payment_to'];

                    if (ISSET($_POST['to_bank']))
                    {
                        $pay_to = $_POST['to_bank'];
                    }
                    else
                    {
                        $pay_to = 0;
                    }
                }
                else if ($trans_type == 2)
                {   // For Bank Deposit
                    $cre_amo = $_POST['amount_' . $i];
                    $amount = 0 - $cre_amo;
                    $sumamount = -($_POST['sumamount']);
                    $pay_to = 0;
                }
                $tblValues = array('reference' => $ref_id,
                    'acc_id' => $acccode[0],
                    'date' => $date,
                    'bank_acc' => $acccode[1],
                    'memo' => $memo,
                    'amount' => $amount,
                    'account' => $code,
                    'unpost' => 0,
                    'type' => $trans_type,
                    'pay_to' => $pay_to,
                    'method' => $method);
                $str = $this->db->insert('unposted_pay_dep', $tblValues);
            }
        }
        if ($method == 'cheque')
        {
            $ch_date = $_POST['ch_date'];
            $ch_date = $this->mastermodel->convdatformat($ch_date);
            $bname = $_POST['bankname'];
            $ch_no = $_POST['ch_no'];
            $chdetails = array('reference' => $ref_id, 'ch_date' => $ch_date, 'bank_name' => $bname, 'cheque_no' => $ch_no);
            $str = $this->db->insert('receipt_cheque', $chdetails);
        }
        if ($method == 'bank')
        {
            $bank_details = array('reference' => $ref_id, 'bank_info' => $_POST['bank_info']);
            $this->db->insert('payment_bank_info', $bank_details);
        }
        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return 0;
        }
        else
        {
            $this->db->trans_commit();
            return $str;
        }
    }

    function bankaccount_payment($ref_id)
    {

        $count = $this->db->query("select * from unposted_pay_dep where unpost='0' and  reference='" . $ref_id . "'");
        $str = 0;
        $insert_audit = 0;
        $this->db->trans_begin();

        $transact_type = 'other';
        if ($transact_type == 'other')
        {

            $str = 0;
            $sumamount = 0;
            foreach ($count->result_array() as $row)
            {
                $date = $row['date'];
                $tdate = date('Y-m-d');
                $acccode = $row['bank_acc'];
                $accid = $row['acc_id'];
                $amount = $row['amount'];
                $code = $row['account'];
                $memo = $row['memo'];
                $type = $row['type'];
                $method = $row['method'];
                $this->db->trans_begin();

                /*                 * ******************************************Insert into Audit_trail***************************************************** */

                if ($insert_audit == 0)
                {
                    $fyear = $this->fiscalyear();
                    $insValuesA = array(
                        'trans_no' => $ref_id,
                        'user' => $_SESSION['userid'],
                        'date_trans' => $tdate,
                        'fiscal_year' => $fyear,
                        'gl_date' => $date
                    );
                    $this->db->insert('audit_trail', $insValuesA);
                    $insert_audit = 1;
                }

                /*                 * ************************************************************************************** */



                $tblValues = array('type_no' => $ref_id, 'tran_date' => $date, 'account' => $code, 'memo' => $memo, 'amount' => $amount, 'method' => $method);
                $str = $this->db->insert('gl_trans', $tblValues);


                if (strncasecmp("IDL", $code, 3) == 0 || strncasecmp("CRP", $code, 3) == 0)
                {
                    $tblValuescu = array('type_no' => $ref_id, 'tran_date' => $date, 'account' => $code, 'memo' => $memo, 'amount' => $amount);
                    $str = $this->db->insert('customer_trans', $tblValuescu);
                }
                if (strncasecmp("EMP", $code, 3) == 0 || strncasecmp("AGE", $code, 3) == 0)
                {
                    $tblValuescu = array('type_no' => $ref_id, 'tran_date' => $date, 'account' => $code, 'memo' => $memo, 'amount' => $amount);
                    $str = $this->db->insert('agent_trans', $tblValuescu);
                }
                if (strncasecmp("INS", $code, 3) == 0)
                {
                    $tblValuescu = array('type_no' => $ref_id, 'tran_date' => $date, 'account' => $code, 'memo' => $memo, 'amount' => $amount);
                    $str = $this->db->insert('company_trans', $tblValuescu);
                }

                $sumamount+=$amount;
            }
            $insamount = 0 - $sumamount;
            $ref = $this->customermodel->getSingleFieldValue('refs', 'reference', 'id', $ref_id);
            $tblValues1 = array('type_no' => $ref_id, 'tran_date' => $date, 'account' => $acccode, 'memo' => $memo, 'amount' => $insamount, 'method' => $method);
            $str = $this->db->insert('gl_trans', $tblValues1);
            $tblValues3 = array('trans_no' => $ref_id, 'bank_act' => $accid, 'ref' => $ref, 'trans_date' => $date, 'amount' => $insamount, 'reconciled' => '');
            $query = $this->db->insert('bank_trans', $tblValues3);



            $posted_val = array('unpost' => 1);
            $this->db->where('reference', $ref_id);
            $str = $this->db->update('unposted_pay_dep', $posted_val);
            if ($this->db->trans_status() === FALSE)
            {
                $this->db->trans_rollback();
                return 0;
            }
            else
            {
                $this->db->trans_commit();
                return $query;
            }
        }
        else
        {

            $pay_amt = $_POST['pay_amt'];
            $memo1 = $_POST['memo1'];
            $type_no = $_POST['t_no'];
            $pid = $_POST['p_id'];
            $to_acc = $_POST['to_bank'];
            $prev_amt = $_POST['prev_amt'];
            $bank_details = explode('~', $to_acc);
            $acc_code = $bank_details[2];
            $sum_amount = 0;
            if ($bank_details[0] == 1)
            {
                $table = 'agent_allocate';
                $table1 = 'agent_trans';
            }
            else if ($bank_details[0] == 2)
            {
                $table = 'company_allocate';
                $table1 = 'company_trans';
            }

            $insertvals = array('type' => '2', 'reference' => $_POST['ref']); // inserting values to refs table
            $this->db->insert('refs', $insertvals);
            $ref_id = $this->db->insert_id();





            /*             * ******************************************Insert into Audit_trail***************************************************** */
            $fyear = $this->fiscalyear();
            $insValuesA = array(
                'trans_no' => $ref_id,
                'user' => $_SESSION['userid'],
                'date_trans' => $tdat,
                'fiscal_year' => $fyear,
                'gl_date' => $date
            );
            $this->db->insert('audit_trail', $insValuesA);
            /*             * ************************************************************************************** */


            for ($p = 0; $p < sizeof($type_no); $p++)
            {
                if ($pay_amt[$p] != '' || $pay_amt[$p] != 0)
                {


                    $insertdata = array('type_no' => $ref_id,
                        'tran_date' => $date,
                        'account' => $acc_code,
                        'memo' => $memo1[$p],
                        'amount' => $pay_amt[$p],
                        'alloc' => $pay_amt[$p]
                    );

                    $this->db->insert($table1, $insertdata);
                    $fromac = $this->db->insert_id();

                    $data = array(
                        'from' => $fromac,
                        'pid' => $pid[$p],
                        'amount' => $pay_amt[$p]
                    );

                    $this->db->insert($table, $data);



                    $alloc = $prev_amt[$p] + $pay_amt[$p];

//
//                             
                    $this->db->query("update $table1 set alloc=$alloc where type_no='$type_no[$p]' and account='$acc_code'");
                    $sum_amount+=$pay_amt[$p];
                }
            }

            $Tabledata = array('type_no' => $ref_id,
                'tran_date' => $date,
                'account' => $acc_code,
                'memo' => '',
                'amount' => $sum_amount
            );
            $this->db->insert('gl_trans', $Tabledata);

            $Tabledata1 = array('type_no' => $ref_id,
                'tran_date' => $date,
                'account' => $acccode[1],
                'memo' => '',
                'amount' => -$sum_amount
            );
            $this->db->insert('gl_trans', $Tabledata1);
            $bankdata = array('trans_no' => $ref_id,
                'bank_act' => $acccode[0],
                'ref' => $ref,
                'trans_date' => $date,
                'amount' => -$sum_amount,
                'reconciled' => ''
            );
            $data = $this->db->insert('bank_trans', $bankdata);


            if ($this->db->trans_status() === FALSE)
            {
                $this->db->trans_rollback();
                return 0;
            }
            else
            {
                $this->db->trans_commit();
                return $data;
            }
        }
    }

    function fiscalyear()
    {


        $data = $this->db->query("select fyear from mycompany ");
        $result = $data->row();
        if ($result)
        {
            return $result->fyear;
        }
        else
        {
            return "";
        }
    }

    /*     * *****************function to add auto journal******************* */

    function add_auto_journal()
    {

        // $reverse=$_POST['reverse'];
        // $ref=$_POST['ref'];
        $title = $_POST['title'];
        $date = date('Y-m-d');
        $counter = $_POST['counter_check'];
        $trans_type = 3;  // Type is journal entry.Refer table trans_type

        $this->db->trans_begin();
        $update = $_POST['refid'];
        if ($update != 0)
        {
            $delete = $this->db->delete('auto_journal', array('reference' => $update));
            $ref_id = $update;
        }
        else
        {
            $insertvals = array('type' => $trans_type, 'reference' => $title); // inserting values to refs table
            $this->db->insert('temp_refs', $insertvals);
            $ref_id = $this->db->insert_id();
        }
        /*         * ******************Insert into temperory table unposted_journal****************** */


        for ($i = 0; $i <= $counter; $i++)
        {
            if (isset($_POST['desc_' . $i]))
            {
                $hid = $_POST['hidedesc_' . $i];
                $memo = $_POST['memo_' . $i];
                $desc = $_POST['desc_' . $i];



                $debit = $_POST['debit_' . $i];
                $credit = $_POST['credit_' . $i];
                if ($debit >= 1)
                {
                    $amount = $debit + $credit;
                }
                else if ($credit >= 1)
                {
                    $amount = -($debit + $credit);
                }
                else
                {
                    $amount = 0;
                }

                $bank_id = $this->customermodel->getSingleFieldValue('bank_accounts', 'id', 'account_code', $hid);
                $tblValues = array('reference' => $ref_id, 'date' => $date, 'title' => $title, 'account_code' => $hid, 'account_id' => $bank_id, 'amount' => $amount, 'memo' => $memo);
                $str = $this->db->insert('auto_journal', $tblValues);
            }
        }

        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return 0;
        }
        else
        {
            $this->db->trans_commit();
            return $str;
        }
    }

    function get_transtype_count($type, $refid)
    {
        $res = $this->db->query("select count(*) as count from refs where refs.type= $type and refs.id <= $refid ");

        $cnt = ($res->row()->count);
        return $cnt;
    }

    function checkaccountisset($account, $table)
    {

        $query = $this->db->query('select * from ' . $table . ' t join fiscal_year fy ON t.fyear=fy.id where fy.closed=0');
        $res = $query->row();
        if (!isset($res->$account))
            $baccount = 0;
        else
            $baccount = $res->$account;
        return $baccount;
    }

    function checkaccountsetting()
    {

        $query = $this->db->query('select * from subacc_setting');

        $res = $query->num_rows();
        return $res;
    }

    function get_subaccount_setting($field)
    {


        $query = $this->db->query("select $field from subacc_setting ");
        $res = $query->row()->$field;
        return $res;
    }

    function get_mainaccount_setting($field)
    {


        $query = $this->db->query("select $field from mainacc_setting ");
        $res = $query->row()->$field;
        return $res;
    }

    /*     * ***********Report Functions****************** */

    function get_chart_report()
    {

        $sql = "select IFNULL(sum(g.amount),0) as amount,cg.chart_group,cg.chart_type as ctype,ct.id as cid,c.account_name,c.account_code,ct.chart_types as chart_type from chart_master c INNER JOIN char_type ct ON ct.id=c.chart_type LEFT JOIN gl_trans
          g ON g.account=c.account_code join chart_group cg ON cg.chart_type=ct.id group by c.account_code,cg.chart_type order by ct.id";
        $Q = $this->db->query($sql);

        if ($Q->num_rows() > 0)
        {
            foreach ($Q->result_array() as $row)
            {
                $data[] = $row;
            }
        }
        $Q->free_result();
        return $data;
    }

    function get_journal_report($date1 = '', $date2 = '')
    {

        $data = array();
        $date1 = $this->mastermodel->convdatformat($date1);
        $date2 = $this->mastermodel->convdatformat($date2);
        $sql = "select * from gl_trans g INNER JOIN refs r ON r.id=g.type_no where r.type=3 and g.tran_date between '$date1' and '$date2' order by g.type_no";
        $Q = $this->db->query($sql);

        if ($Q->num_rows() > 0)
        {
            foreach ($Q->result_array() as $row)
            {
                $data[] = $row;
            }
        }
        $Q->free_result();
        return $data;
    }

    function get_customer_balance($cus_id, $date1, $date2)
    {

        $data = array();
        $date1 = $this->mastermodel->convdatformat($date1);
        $date2 = $this->mastermodel->convdatformat($date2);
        if ($cus_id == 'all')
            $condition = "where";
        else
            $condition = " where customers.id=$cus_id and ";



        $sql = "SELECT
                             placing_slip_premiumdetails.premium
                            , placing_slip.id as pid
                            , IFNULL(sum(cust_allocate.amount),0) as amount
                            , customers.id
                            , placing_slip_refs.id as typeno
                            , customer_trans.alloc as calloc
                            , placing_slip.quotation_ref
                            , refs.reference
                            , customer_trans.tran_date
                            , customer_trans.account


                        FROM
                            placing_slip_premiumdetails
                            INNER JOIN placing_slip
                                ON (placing_slip_premiumdetails.placing_slip_id = placing_slip.id)
                            LEFT JOIN cust_allocate
                                ON (placing_slip_premiumdetails.placing_slip_id = cust_allocate.pid)
                            INNER JOIN placing_slip_refs
                                ON (placing_slip_premiumdetails.placing_slip_id = placing_slip_refs.pslip_id)
                            INNER JOIN refs
                                ON (placing_slip_refs.id = refs.id)
                            INNER JOIN customer_trans
                                ON (customer_trans.type_no = placing_slip_refs.id)
                            INNER JOIN customers
                                ON (placing_slip.customer_id = customers.id)  $condition customer_trans.tran_date between '$date1' and '$date2' GROUP BY placing_slip.id ORDER by customer_trans.account";



        $Q = $this->db->query($sql);

        if ($Q->num_rows() > 0)
        {
            foreach ($Q->result_array() as $row)
            {
                $data[] = $row;
            }
        }
        $Q->free_result();
        return $data;
    }

    function get_cust_allocate_bal($cus_code, $date1, $date2)
    {

        $data = array();
        $date1 = $this->mastermodel->convdatformat($date1);
        $date2 = $this->mastermodel->convdatformat($date2);
        if ($cus_code == 'all')
            $condition = "where";
        else
            $condition = " where account='$cus_code' and ";

        $qry = "SELECT sum(amount) as all_amount,sum(alloc) as bal_amount, account FROM customer_trans $condition amount <0 and customer_trans.tran_date between '$date1' and '$date2' GROUP by customer_trans.account ORDER by customer_trans.account";

        $res = $this->db->query($qry);

        if ($res->num_rows() > 0)
        {
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
        }
        $res->free_result();
        return $data;
    }

    function customer_list_rep()
    {


        $qry = "SELECT IFNULL(cp.insured,cc.insured) as name , c.id,c.code FROM customers c LEFT JOIN customer_personal_ind cp ON c.id=cp.customer_id  LEFT JOIN customer_corp_info cc ON c.id=cc.customer_id  ";

        $res = $this->db->query($qry);

        if ($res->num_rows() > 0)
        {
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
        }
        $res->free_result();
        return $data;
    }

    function get_customer_name($cus_code)
    {

        $data = "SELECT IFNULL(cp.insured,cc.insured) as name , c.id,c.code FROM customers c LEFT JOIN customer_personal_ind cp ON c.id=cp.customer_id  LEFT JOIN customer_corp_info cc ON c.id=cc.customer_id where c.code='$cus_code' ";
        $res = $this->db->query($data);

        $result = $res->row();
        if ($result)
        {
            return $result->name;
        }
        else
        {
            return "";
        }
    }

    function bankname_list()
    {


        $qry = "SELECT * from bank_accounts ";

        $res = $this->db->query($qry);

        if ($res->num_rows() > 0)
        {
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
        }
        $res->free_result();
        return $data;
    }

    function get_bank_statement($bankid, $date1, $date2)
    {

        $data = array();
        $date1 = $this->mastermodel->convdatformat($date1);
        $date2 = $this->mastermodel->convdatformat($date2);

        $qry = "SELECT bt.trans_no, bt.trans_date,bt.amount,r.reference,tt.transaction FROM bank_trans bt LEFT JOIN refs r ON r.id=bt.trans_no LEFT JOIN transaction_types tt ON tt.id=r.type where bank_act=$bankid and  trans_date between '$date1' and '$date2' ORDER BY bt.trans_no ";

        $res = $this->db->query($qry);

        if ($res->num_rows() > 0)
        {
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
        }
        $res->free_result();
        return $data;
    }

    function get_chart_trans_report($acc, $date1 = '', $date2 = '')
    {

        $data = array();
        $date1 = $this->mastermodel->convdatformat($date1);
        $date2 = $this->mastermodel->convdatformat($date2);
        $sql = "SELECT gt.type_no, gt.tran_date,gt.amount,r.reference,tt.transaction_type FROM gl_trans gt LEFT JOIN refs r ON r.id=gt.type_no LEFT JOIN transaction_types tt ON tt.id=r.type where gt.account='$acc' and  gt.tran_date between '$date1' and '$date2' ORDER BY gt.type_no ";

        $Q = $this->db->query($sql);

        if ($Q->num_rows() > 0)
        {
            foreach ($Q->result_array() as $row)
            {
                $data[] = $row;
            }
        }
        $Q->free_result();
        return $data;
    }

    /*     * *****************Report end****************** */

    function acc_code_increment($where, $like)
    {

        $data = "SELECT IFNULL(max(account_code),0) as code FROM chart_master where parent=$where and account_code like '" . $like . "%'";

        $res = $this->db->query($data);
        return $res->row()->code;
    }

    function acc_code_maxi_limit($value)
    {

        $data = "SELECT account_code FROM chart_master where account_code > '$value' and parent=0 order by account_code ASC limit 0,1";

        $res = $this->db->query($data);
        if ($res->num_rows() > 0)
        {
            return $res->row()->account_code;
        }
        else
        {
            return 99999999999999999999;
        }
    }

    function Getchart_group($table, $pageno, $field, $value = "")
    {

        $limit = (($pageno - 1) * 10);
        $data = array();
        if ($field == 'chart_type')
        {

            $res = $this->db->query("select * from $table t join char_type ct on ct.id=t.chart_type where ct.chart_types like '" . $value . "%' order by t.id limit " . $limit . "," . 10);
        }
        else
        {
            $res = $this->db->query("select * from $table where " . $field . " like '" . $value . "%' order by id limit " . $limit . "," . 10);
        }
        foreach ($res->result_array() as $row)
        {
            $data[] = $row;
        }
        return $data;
    }

    function showchart_group($pageno, $field, $value = "")
    {
        $limit = (($pageno - 1) * 10);
        $data = array();
        $data1 = array();
        $rescount = $this->db->query("select * from chart_master  where " . $field . " like '" . $value . "%' and parent=0");

        if ($field == 'chart_type')
        {

            $res = $this->db->query("select * from chart_master t join char_type ct on ct.id=t.chart_type where ct.chart_types like '" . $value . "%' and parent=0 order by t.id limit " . $limit . "," . 10);
        }
        else
        {

            $res = $this->db->query("select cg.account_code,cg.account_name,cg.id,cg.chart_type from  chart_master cg join char_type ct on ct.id=cg.chart_type
                where " . $field . " like '" . $value . "%' and parent=0 order by ct.id,cg.account_code asc,cg.id desc limit " . $limit . "," . 10);
        }

        $data['totcount'] = $rescount->num_rows();

        foreach ($res->result_array() as $row)
        {
            $data1[] = $row;
        }
        $data['result'] = $data1;

        return $data;
    }

    function addchart_group()
    {


        $acc_name = $this->input->post('acc_name');
        $parent = $this->input->post('parent');
        $acc_group = $this->input->post('acc_group');
        $account_code = $this->input->post('account_code');

        $tblValues = array('account_code' => $account_code, 'chart_type' => $acc_group, 'parent' => $parent, 'account_name' => $acc_name);

        $data = $this->db->insert('chart_master', $tblValues);


        return $data;
    }

    function addtransaction_code()
    {


        $code = $this->input->post('code');
        $codefor = $this->input->post('codefor');
        $type = $this->input->post('type');

        $tblValues = array('code' => $code, 'type' => $type, 'trans' => $codefor);
        $data = $this->db->insert('transaction_code', $tblValues);
        return $data;
    }

    function addaccount_type()
    {

        $this->db->trans_begin();

        $chart_code = $this->input->post('chart_code');
        $group = $this->input->post('chart_account_group');

        $tblValues = array('chart_types' => $chart_code, 'chart_group' => $group);
        $data = $this->db->insert('char_type', $tblValues);

        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return $data;
        }
        else
        {
            $this->db->trans_commit();
            return $data;
        }
    }

    function countchart_group($table, $field, $value = "")
    {

        if ($field == 'chart_type')
        {

            $res = $this->db->query("select * from $table t join char_type ct on ct.id=t.chart_type where ct.chart_types like '" . $value . "%'  ");
        }
        else
        {

            $res = $this->db->query("select * from " . $table . " where " . $field . " like '" . $value . "%'");
        }
        return $res->num_rows();
    }

    function updatechart_group()
    {

        $acc_name = $this->input->post('acc_name');
        $parent = $this->input->post('parent');
        $acc_group = $this->input->post('acc_group');
        $account_code = $this->input->post('account_code');
        $id = $this->input->post('id');

        $tblValues = array('account_code' => $account_code, 'chart_type' => $acc_group, 'parent' => $parent, 'account_name' => $acc_name);
        $this->db->where('id', $id);
        $res = $this->db->update('chart_master', $tblValues);

        $tblValues = array('chart_type' => $acc_group);
        $this->db->where('parent', $id);
        $this->db->update('chart_master', $tblValues);
        return $res;
    }

    function updatetrans_code()
    {

        $id = $this->input->post('id');
        $code = $this->input->post('code');
        $codefor = $this->input->post('codefor');
        $type = $this->input->post('type');

        $this->db->where('id', $id);
        $tblValues = array('code' => $code, 'type' => $type, 'trans' => $codefor);
        $res = $this->db->update('transaction_code', $tblValues);
        return $res;
    }

    function updateaccount_type()
    {

        $id = $this->input->post('id');
        $chart_types = $this->input->post('chart_types');
        $group = $this->input->post('chart_account_group');

        $this->db->where('id', $id);
        $tblValues = array('chart_types' => $chart_types, 'chart_group' => $group);
        $res = $this->db->update('char_type', $tblValues);
        return $res;
    }

    function deletechart_group($fld, $table, $id)
    {

        $qry = $this->db->query("select count(*) as count from chart_master where parent='$id'");
        $query = $qry->row()->count;

        if ($query == 0)
        {
            $res = $this->db->delete($table, array($fld => $id));
            if ($res > 0)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
        else
        {
            return 0;
        }
    }

    function unpost_customerpayment($pageno, $type, $post)
    {



        if ($type == 'data')
        {

            $limit = (($pageno - 1) * 10);
            $data = array();

            $res = $this->db->query("select * from bank_to_bank where type='$post'   limit " . $limit . "," . 10);
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
        else if ($type == 'count')
        {

            $res = $this->db->query("select * from bank_to_bank ");
            return $res->num_rows();
        }
    }

    function checktrans_codeset($val)
    {

        $query = $this->db->query("select * from transaction_code  where trans=$val");

        $res = $query->num_rows();
        return $res;
    }

    function get_reference($transaction_code)
    {

        $length = strlen($transaction_code) + 1;
        $data = "SELECT MAX(CONVERT(SUBSTRING(reference," . $length . "),UNSIGNED INTEGER) ) as code FROM 
        refs where reference like '" . $transaction_code . "%' ";
        $res = $this->db->query($data);
        if ($res->num_rows() > 0)
        {
            $code = $res->row()->code;
            $ref = $code + 1;
        }
        else
        {
            $ref = 1;
        }

        return $transaction_code . $ref;
    }

    function get_reference_code($val)
    {
        $transaction_code = $this->customermodel->getSingleFieldValue('transaction_code', 'code', 'trans', $val) . '/';
        $year = date("Y");
        $transaction_code.= $year . '/';
        $reference = $this->get_reference($transaction_code);
        return $reference;
    }

    function add_reverse_posted_journal()
    {
        $str = 0;
        $reverse = $_POST['reverse'];
        $ref = $this->accountingsmodel->get_reference_code(3);
        $qdate = $_POST['date'];
        $date = $this->mastermodel->convdatformat($qdate);
        $counter = $_POST['counter_check'];
        $trans_type = 3;  // Type is journal entry.Refer table trans_type

        $this->db->trans_begin();
        if ($reverse == 'true')
        {

            $insertvals = array('type' => $trans_type, 'reference' => $ref); // inserting values to refs table
            $this->db->insert('refs', $insertvals);
            $ref_id = $this->db->insert_id();
            /*             * ******************Insert into temperory table unposted_journal****************** */


            for ($i = 0; $i <= $counter; $i++)
            {
                if (isset($_POST['desc_' . $i]))
                {
                    $hid = $_POST['hidedesc_' . $i];
                    $memo = $_POST['memo_' . $i];
                    $desc = $_POST['desc_' . $i];



                    $debit = $_POST['debit_' . $i];
                    $credit = $_POST['credit_' . $i];
                    if ($debit >= 1)
                    {
                        $amount = 0 - ($debit + $credit);
                    }
                    else if ($credit >= 1)
                    {
                        $amount = $debit + $credit;
                    }
                    else
                    {
                        $amount = 0;
                    }

                    $bank_id = $this->customermodel->getSingleFieldValue('bank_accounts', 'id', 'account_code', $hid);
                    $tblValues = array('reference' => $ref_id, 'date' => $date, 'reverse' => 'false', 'account_code' => $hid, 'account_id' => $bank_id, 'amount' => $amount, 'memo' => $memo, 'unpost' => 0);
                    $str = $this->db->insert('unposted_journal', $tblValues);
                }
            }
        }

        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return 0;
        }
        else
        {
            $this->db->trans_commit();
            return 1;
        }
    }

    function get_emp_paid_amount($val, $table)
    {
        $query = $this->db->query("select  amount from $table  where id='$val'");

        $res = $query->row()->amount;
        return $res;
    }

    function get_emp_alloc_amount($val, $table)
    {
        $query = $this->db->query("select  alloc from $table  where id='$val'");
        $res = $query->row()->alloc;
        return $res;
    }

    function addemployeeallocate()
    {

        $ptype = $_POST['t_no'];
        $pid = $_POST['p_id'];
        $eid = $_POST['e_id'];
        $alloc_amt = $_POST['pay_amt'];
        $pre_alloc = $_POST['prev_amt'];
        $account_code = $_POST['account_code'];
        $from = $_POST['fromid'];
        $allocate = $_POST['alloc_table'];
        $trans = $_POST['trans_table'];
        $bal_allocate = $_POST['bal_allocate'];
        $this->db->trans_begin();
        for ($p = 0; $p < sizeof($pid); $p++)
        {

            $type = (empty($eid[$p])) ? 'issue' : 'endorsement';
            if ($type == 'issue')
            {
                $xpid = $pid[$p];
            }
            else
                $xpid = $eid[$p];
            if ($alloc_amt[$p] != '' || $alloc_amt[$p] != 0)
            {
                $data = array(
                    'from' => $from,
                    'pid' => $xpid,
                    'amount' => $alloc_amt[$p],
                    'type' => $type
                );

                $this->db->insert($allocate, $data);


                $bal_allocate+=$alloc_amt[$p];



                $alloc = $pre_alloc[$p] + $alloc_amt[$p];
                $pretype = $ptype[$p];

                $insdata = array('alloc' => $alloc);

                $this->db->where('type_no', $pretype);
                $this->db->where('account', $account_code);
                $this->db->update($trans, $insdata);

                //   $this->db->query("update $trans set alloc=$alloc where type_no=$pretype and account='$account_code'");
            }
        }


        $insalloc = array('alloc' => $bal_allocate);

        $this->db->where('id', $from);
        $this->db->update($trans, $insalloc);


        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
        }
        else
        {
            $this->db->trans_commit();
            return true;
        }
    }
    
    function addcommissionallocate()
    {

        $ptype = $_POST['t_no'];
        $pid = $_POST['p_id'];
        $eid = $_POST['e_id'];
        $alloc_amt = $_POST['pay_amt'];
        $pre_alloc = $_POST['prev_amt'];
        $account_code = $_POST['account_code'];
        $from = $_POST['fromid'];
        $allocate = $_POST['alloc_table'];
        $trans = $_POST['trans_table'];
        $bal_allocate = $_POST['bal_allocate'];
        $this->db->trans_begin();
        for ($p = 0; $p < sizeof($pid); $p++)
        {

            $type = (empty($eid[$p])) ? 'issue' : 'endorsement';
            if ($type == 'issue')
            {
                $xpid = $pid[$p];
            }
            else {
                $xpid = $eid[$p];
                $endmode = $this->customermodel->getSingleFieldValue('endorsement', 'mode', 'id', $xpid);
            }
            if ($alloc_amt[$p] != '' || $alloc_amt[$p] != 0)
            {
                $data = array(
                    'from' => $from,
                    'pid' => $xpid,
                    'amount' => $alloc_amt[$p],
                    'type' => $type
                );

                $this->db->insert($allocate, $data);


                
                $alloc = $pre_alloc[$p] + $alloc_amt[$p];
                $pretype = $ptype[$p];

                $insdata = array('alloc' => $alloc);

                $this->db->where('type_no', $pretype);
                $this->db->where('account', $account_code);
                $this->db->update($trans, $insdata);

                if ($endmode == 'Deduction')
                    $alloc_amt[$p] = 0 - $alloc_amt[$p];
                $bal_allocate+=$alloc_amt[$p];

                //   $this->db->query("update $trans set alloc=$alloc where type_no=$pretype and account='$account_code'");
            }
        }


        $insalloc = array('alloc' => $bal_allocate);

        $this->db->where('id', $from);
        $this->db->update($trans, $insalloc);


        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
        }
        else
        {
            $this->db->trans_commit();
            return true;
        }
    }

    function search_autojournal($searchopt, $searchtext = "", $page = "", $per_page = "", $count)
    {
        $data = array();
        if ($page)
            $start = ($page - 1) * $per_page;
        else
            $start = 0;
        if ($count == 'true')
        {
            $sql = "select  distinct(aj.reference) as id, r.reference as ref,aj.title,aj.date from auto_journal aj JOIN temp_refs r ON r.id=aj.reference  where r.type='7' and  $searchopt like '$searchtext%'";
            $data['results'] = $this->db->query($sql);
            return $data['results']->num_rows();
        }
        else
        {
            $sql = "select distinct(aj.reference) as id, r.reference as ref,aj.title,aj.date from auto_journal aj JOIN temp_refs r ON r.id=aj.reference  where r.type='7' and  $searchopt like '$searchtext%'  limit $start,$per_page";
            $res = $this->db->query($sql);
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
    }

    function search_unposted_journal($searchopt, $searchtext = "", $page = "", $per_page = "", $count)
    {
        $data = array();
        if ($page)
            $start = ($page - 1) * $per_page;
        else
            $start = 0;
        if ($count == 'true')
        {
            $sql = "select  distinct(t.reference) as id, r.reference,t.date as tran_date from unposted_journal t JOIN refs r ON r.id=t.reference where r.type='7' and t.unpost='0' and $searchopt like '$searchtext%'";
            $data['results'] = $this->db->query($sql);
            return $data['results']->num_rows();
        }
        else
        {
            $sql = "select  distinct(t.reference) as id, r.reference,t.date as tran_date from unposted_journal t JOIN refs r ON r.id=t.reference where r.type='7' and t.unpost='0' and $searchopt like '$searchtext%'  limit $start,$per_page";
            $res = $this->db->query($sql);
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
    }

    function search_posted_journal($searchopt, $searchtext = "", $page = "", $per_page = "", $count)
    {
        $data = array();
        if ($page)
            $start = ($page - 1) * $per_page;
        else
            $start = 0;
        if ($count == 'true')
        {
            $sql = "select distinct(r.id)  from gl_trans bt JOIN refs r ON r.id=bt.type_no where r.type='7' and $searchopt like '$searchtext%'";
            $data['results'] = $this->db->query($sql);
            return $data['results']->num_rows();
        }
        else
        {
            $sql = "select  distinct(r.id) as id, r.reference,bt.tran_date from gl_trans bt JOIN refs r ON r.id=bt.type_no where r.type='7' and $searchopt like '$searchtext%'  limit $start,$per_page";
            $res = $this->db->query($sql);
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
    }

    function search_bank_transfer($searchopt, $searchtext = "", $page = "", $per_page = "", $count = "", $post = "")
    {
        $data = array();
        if ($page)
            $start = ($page - 1) * $per_page;
        else
            $start = 0;
        if ($count == 'true')
        {
            $sql = "select distinct(bank_to_bank.id),bank_to_bank.ref,amount,trans_date,memo,reference,bank_to_bank.type, ba1.bank_account_name as from_b,ba2.bank_account_name as to_b from bank_to_bank INNER JOIN bank_accounts ba1  ON (bank_to_bank.from_b = ba1.id) INNER JOIN bank_accounts ba2 ON (bank_to_bank.to_b = ba2.id) join refs on refs.id= bank_to_bank.ref  where bank_to_bank.type='$post' and $searchopt like '$searchtext%'";
            $data['results'] = $this->db->query($sql);
            return $data['results']->num_rows();
        }
        else
        {
            $sql = "select distinct(bank_to_bank.id),bank_to_bank.ref,amount,trans_date,memo,reference,bank_to_bank.type, ba1.bank_account_name as from_b,ba2.bank_account_name as to_b from bank_to_bank INNER JOIN bank_accounts ba1  ON (bank_to_bank.from_b = ba1.id) INNER JOIN bank_accounts ba2 ON (bank_to_bank.to_b = ba2.id) join refs on refs.id= bank_to_bank.ref  where bank_to_bank.type='$post' and $searchopt like '$searchtext%'  limit $start,$per_page";
            $res = $this->db->query($sql);
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
    }

    function search_posted_bank_deposit($searchopt, $searchtext = "", $page = "", $per_page = "", $count = "")
    {
        $data = array();
        if ($page)
            $start = ($page - 1) * $per_page;
        else
            $start = 0;


        if ($searchopt == 'tran_date')
        {
            $searchtext = $this->mastermodel->convdatformat($searchtext);
        }
        else if ($searchopt == 'reference')
        {
            $searchopt = 'r.reference';
        }
        else if ($searchopt == 'amount')
        {
            $searchtext = 0 - $searchtext;
        }

        if ($count == 'true')
        {
            $sql = "select r.reference, bt.type_no as trans_no,bt.tran_date as trans_date,bt.amount as amount,cm.account_code,cm.account_name, ch_date,cheque_no FROM  `gl_trans` bt JOIN refs r ON r.id = bt.`type_no`
             join chart_master cm on cm.account_code=bt.account
            LEFT JOIN receipt_cheque ON receipt_cheque.reference = r.id
             WHERE r.type =  '2' and $searchopt like '$searchtext%' group by r.reference having amount <0 ";

            $data['results'] = $this->db->query($sql);
            return $data['results']->num_rows();
        }
        else
        {
            $sql = "select r.reference, bt.type_no as trans_no,bt.tran_date as trans_date,bt.amount as amount,cm.account_code,cm.account_name, ch_date,cheque_no FROM  `gl_trans` bt JOIN refs r ON r.id = bt.`type_no`
             join chart_master cm on cm.account_code=bt.account
            LEFT JOIN receipt_cheque ON receipt_cheque.reference = r.id
             WHERE r.type =  '2' and $searchopt like '$searchtext%' group by r.reference having amount <0 order by r.id  desc limit $start,$per_page";




            $res = $this->db->query($sql);
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
    }

    function search_unposted_pdc($searchopt, $searchtext = "", $page = "", $per_page = "", $count = "", $tr_type = "other")
    {
        $data = array();
        if ($page)
            $start = ($page - 1) * $per_page;
        else
            $start = 0;

        if ($searchopt == 'date')
        {
            $searchtext = $this->mastermodel->convdatformat($searchtext);
        }
        else if ($searchopt == 'amount')
        {
            $searchtext = 0 - $searchtext;
        }

        if ($count == 'true')
        {
            $sql = "select  t.reference as id,r.type,t.bank_acc,t.acc_id,cm.account_name,cm.account_code,t.amount as amount, r.reference,t.date as tran_date from unposted_pay_dep t JOIN refs r ON r.id=t.reference
                    join chart_master cm on cm.account_code=t.account
                    where t.unpost='0' and r.tr_type='$tr_type' and $searchopt like '$searchtext%'  ";


            $data['results'] = $this->db->query($sql);
            return $data['results']->num_rows();
        }
        else
        {

            $sql = "select  t.reference as id,r.type,t.bank_acc,t.acc_id,cm.account_name,cm.account_code,t.amount as amount, r.reference,t.date as tran_date from unposted_pay_dep t JOIN refs r ON r.id=t.reference
                    join chart_master cm on cm.account_code=t.account
                    where t.unpost='0' and r.tr_type='$tr_type'  and $searchopt like '$searchtext%'  order by r.id desc limit $start,$per_page";

             $res = $this->db->query($sql);
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
    }

    function search_posted_pdc($searchopt, $searchtext = "", $page = "", $per_page = "", $count = "", $tr_type = "other")
    {
        $data = array();
        if ($page)
            $start = ($page - 1) * $per_page;
        else
            $start = 0;

        if ($searchopt == 'date')
        {
            $searchtext = $this->mastermodel->convdatformat($searchtext);
        }
        else if ($searchopt == 'amount')
        {
            $searchtext = 0 - $searchtext;
        }

        if ($count == 'true')
        {
            $sql = "select * ,fy.closed as fyclosed ,r.id as id,r.type 
            from bank_trans bt 
                JOIN refs r ON r.id=bt.trans_no                
                JOIN transaction_types tt ON tt.id=r.type
                JOIN audit_trail au ON au.trans_no=r.id 
                JOIN fiscal_year fy ON fy.id=au.fiscal_year
                where   r.tr_type='post_dated_cheque' and $searchopt like '$searchtext%'  ";


            $data['results'] = $this->db->query($sql);
            return $data['results']->num_rows();
        }
        else
        {

            $sql = "select * ,fy.closed as fyclosed ,r.id as id,r.type 
            from bank_trans bt 
                JOIN refs r ON r.id=bt.trans_no                
                JOIN transaction_types tt ON tt.id=r.type
                JOIN audit_trail au ON au.trans_no=r.id 
                JOIN fiscal_year fy ON fy.id=au.fiscal_year
                where   r.tr_type='post_dated_cheque' and $searchopt like '$searchtext%'  order by r.id desc limit $start,$per_page";


            $res = $this->db->query($sql);
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
    }

    function search_unposted_bank_deposit($searchopt, $searchtext = "", $page = "", $per_page = "", $count = "", $tr_type = "other")
    {
        $data = array();
        if ($page)
            $start = ($page - 1) * $per_page;
        else
            $start = 0;

        if ($searchopt == 'date')
        {
            $searchtext = $this->mastermodel->convdatformat($searchtext);
        }
        else if ($searchopt == 'amount')
        {
            $searchtext = 0 - $searchtext;
        }

        if ($count == 'true')
        {
            $sql = "select  t.reference as id,ch_date,cheque_no, r.type,t.bank_acc,t.acc_id,cm.account_name,cm.account_code,t.amount as amount, r.reference,t.date as tran_date from unposted_pay_dep t JOIN refs r ON r.id=t.reference
                    join chart_master cm on cm.account_code=t.account
                    LEFT JOIN receipt_cheque ON receipt_cheque.reference = r.id
                    where r.type='2' and t.unpost='0' and r.tr_type='$tr_type' and $searchopt like '$searchtext%' group by r.reference   having amount <0  ";


            $data['results'] = $this->db->query($sql);
            return $data['results']->num_rows();
        }
        else
        {

            $sql = "select  t.reference as id,ch_date,cheque_no, r.type,t.bank_acc,t.acc_id,cm.account_name,cm.account_code,t.amount as amount, r.reference,t.date as tran_date from unposted_pay_dep t JOIN refs r ON r.id=t.reference
                    join chart_master cm on cm.account_code=t.account
                    LEFT JOIN receipt_cheque ON receipt_cheque.reference = r.id
                    where r.type='2' and t.unpost='0' and r.tr_type='$tr_type'  and $searchopt like '$searchtext%' group by r.reference  having amount <0  order by r.id desc limit $start,$per_page";


            $res = $this->db->query($sql);
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
    }

    function search_posted_bank_payment($searchopt, $searchtext = "", $page = "", $per_page = "", $count = "")
    {

        $data = array();
        if ($page)
            $start = ($page - 1) * $per_page;
        else
            $start = 0;


        if ($searchopt == 'tran_date')
        {
            $searchtext = $this->mastermodel->convdatformat($searchtext);
        }


        if ($count == 'true')
        {
              $sql = "select r.reference,ch_date,cheque_no, bt.type_no as trans_no,bt.tran_date as trans_date,bt.amount as amount,cm.account_code,cm.account_name FROM  `gl_trans` bt JOIN refs r ON r.id = bt.`type_no` 
            LEFT JOIN receipt_cheque ON receipt_cheque.reference = r.id
             join chart_master cm on cm.account_code=bt.account
             WHERE r.type =  '1' and $searchopt like '$searchtext%' group by r.reference having amount >0 ";
            $data['results'] = $this->db->query($sql);
            return $data['results']->num_rows();
        }
        else
        {
            $sql = "select r.reference,ch_date,cheque_no, bt.type_no as trans_no,bt.tran_date as trans_date,bt.amount as amount,cm.account_code,cm.account_name FROM  `gl_trans` bt JOIN refs r ON r.id = bt.`type_no`
            LEFT JOIN receipt_cheque ON receipt_cheque.reference = r.id
             join chart_master cm on cm.account_code=bt.account
             WHERE r.type =  '1' and $searchopt like '$searchtext%' group by r.reference having amount >0 order by r.id  desc limit $start,$per_page";




            $res = $this->db->query($sql);
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
    }

    function search_unposted_bank_payment($searchopt, $searchtext = "", $page = "", $per_page = "", $count = "", $tr_type = "other")
    {
        $data = array();
        if ($page)
            $start = ($page - 1) * $per_page;
        else
            $start = 0;

        if ($searchopt == 'date')
        {
            $searchtext = $this->mastermodel->convdatformat($searchtext);
        }

        if ($count == 'true')
        {
           $sql = "select  t.reference as id,r.type, ch_date,cheque_no, t.bank_acc,t.acc_id,cm.account_name,cm.account_code,t.amount as amount, r.reference,t.date as tran_date from unposted_pay_dep t JOIN refs r ON r.id=t.reference
                    join chart_master cm on cm.account_code=t.account left join receipt_cheque on receipt_cheque.reference=r.id
                    where r.type='1' and r.tr_type='$tr_type'  and t.unpost='0' and $searchopt like '$searchtext%' group by r.reference   having amount >0  ";


            $data['results'] = $this->db->query($sql);
            return $data['results']->num_rows();
        }
        else
        {

            $sql = "select  t.reference as id,r.type, ch_date,cheque_no ,t.bank_acc,t.acc_id,cm.account_name,cm.account_code,t.amount as amount, r.reference,t.date as tran_date from unposted_pay_dep t JOIN refs r ON r.id=t.reference
                    join chart_master cm on cm.account_code=t.account join receipt_cheque on receipt_cheque.reference=r.id
                    where r.type='1' and r.tr_type='$tr_type'  and t.unpost='0' and $searchopt like '$searchtext%' group by r.reference  having amount >0  order by r.id desc limit $start,$per_page";


            $res = $this->db->query($sql);
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
    }

    function search_unposted_customer_payment($searchopt, $searchtext = "", $page = "", $per_page = "", $count = "")
    {
        $data = array();
        if ($page)
            $start = ($page - 1) * $per_page;
        else
            $start = 0;
        if ($count == 'true')
        {
           $sql = "select  distinct(t.reference) as id,t.bank_acc,t.acc_id,ch_date, cheque_no, r.reference,t.date as tran_date from 
            unposted_pay_dep t JOIN refs r ON r.id=t.reference left join receipt_cheque on  receipt_cheque.reference = r.id
            where r.type='2' and t.unpost='0' and $searchopt like '$searchtext%'";
            $data['results'] = $this->db->query($sql);
            return $data['results']->num_rows();
        }
        else
        {
            $sql = "select  distinct(t.reference) as id,t.bank_acc,t.acc_id,ch_date, cheque_no, r.reference,t.date as tran_date from unposted_pay_dep t JOIN refs r ON r.id=t.reference 
            left join receipt_cheque on  receipt_cheque.reference = r.id where r.type='2' and t.unpost='0' and $searchopt like '$searchtext%'  limit $start,$per_page";
            $res = $this->db->query($sql);
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
    }

    function search_posted_customer_payment($searchopt, $searchtext = "", $page = "", $per_page = "", $count = "")
    {
        $data = array();
        if ($page)
            $start = ($page - 1) * $per_page;
        else
            $start = 0;
        if ($count == 'true')
        {
            $sql = "select * from customer_trans c INNER JOIN bank_trans b ON c.type_no=b.trans_no
            left join receipt_cheque on  receipt_cheque.reference = b.trans_no where c.amount like'-%' and $searchopt like '$searchtext%'";
            $data['results'] = $this->db->query($sql);
            return $data['results']->num_rows();
        }
        else
        {
           $sql = "select distinct(c.id) as id,c.tran_date,c.amount,c.account,c.memo, ch_date,cheque_no, c.alloc, b.ref as reference, b.trans_no  from customer_trans c INNER JOIN bank_trans b ON c.type_no=b.trans_no 
            left join receipt_cheque on  receipt_cheque.reference = b.trans_no where c.amount like'-%' and $searchopt like '$searchtext%'  limit $start,$per_page";
            $res = $this->db->query($sql);
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
    }

    function custom_allocat($table, $pageno, $field, $type)
    {

        $limit = (($pageno - 1) * 10);
        $data = array();
       $res = $this->db->query("select distinct(c.id) as id,c.alloc,c.tran_date,c.amount,c.account,account_name,c.memo,b.bank_act,refs.reference from $table c 
                    INNER JOIN bank_trans b ON c.type_no=b.trans_no 
                    INNER JOIN refs  ON c.type_no=refs.id
                    INNER JOIN chart_master ON chart_master.account_code=c.account
                    where c.alloc<>-c.amount and c.amount like '-%' and " . $field . " like'" . $type . "%' order by c.id desc limit " . $limit . "," . 10);
        foreach ($res->result_array() as $row)
        {
            $data[] = $row;
        }
        return $data;
    }

    function countcust_alloc_val($table, $field, $type)
    {

        $res = $this->db->query("select * from $table c INNER JOIN bank_trans b ON c.type_no=b.trans_no
                     INNER JOIN chart_master ON chart_master.account_code=c.account
                    where c.alloc<>-c.amount and " . $field . " like'" . $type . "%'");

        return $res->num_rows();
    }

    function emplo_allocat($table, $pageno, $field, $type)
    {

        $limit = (($pageno - 1) * 10);
        $data = array();

        $res = $this->db->query("select  a.id,a.alloc,a.tran_date,a.amount,a.account,a.memo,account_name,refs.reference from $table a  
                    INNER JOIN chart_master ON chart_master.account_code=a.account
                    INNER JOIN refs  ON a.type_no=refs.id
                    where a.alloc<>a.amount and a.amount>0 and " . $field . " like'" . $type . "%' order by a.id desc limit " . $limit . "," . 10);
        foreach ($res->result_array() as $row)
        {
            $data[] = $row;
        }
        return $data;
    }

    function countemp_alloc_val($table, $field, $type)
    {
         $res = $this->db->query("select * from $table a 
                     INNER JOIN chart_master ON chart_master.account_code=a.account
                    where a.alloc<>a.amount and a.amount>0 and " . $field . " like'" . $type . "%'");
        return $res->num_rows();
    }

    function commission_allocat($table, $pageno, $field, $type)
    {

        $limit = (($pageno - 1) * 10);
        $data = array();
        
        
       
        $res = $this->db->query("select distinct(c.id) as id,c.alloc,c.tran_date,c.amount,c.account,account_name,c.memo,b.bank_act,refs.reference from $table c 
                    INNER JOIN bank_trans b ON c.type_no=b.trans_no 
                    INNER JOIN refs  ON c.type_no=refs.id
                    INNER JOIN chart_master ON chart_master.account_code=c.account
                    where c.alloc<>-c.amount and c.amount like '-%' and " . $field . " like'" . $type . "%' order by c.id desc limit " . $limit . "," . 10);
        foreach ($res->result_array() as $row)
        {
            $data[] = $row;
        }
        return $data;
    }

    function countcommission_alloc_val($table, $field, $type)
    {

        $res = $this->db->query("select distinct(c.id) as id,c.alloc,c.tran_date,c.amount,c.account,account_name,c.memo,b.bank_act,refs.reference from $table c 
                    INNER JOIN bank_trans b ON c.type_no=b.trans_no 
                    INNER JOIN refs  ON c.type_no=refs.id
                    INNER JOIN chart_master ON chart_master.account_code=c.account
                    where c.alloc<>-c.amount and c.amount like '-%' and " . $field . " like'" . $type . "%'");

        return $res->num_rows();
    }
    
    function get_receipt_voucher($id)
    {

        $data = array();
        $sql = "
     SELECT  cv.cover
    , cc.address
    , cc.postbox
    , c.type
    , ca.amount as alloc_amt
    , c.id as cid
    , cty.cityname
    , ctry.countryname
    , ctry.currencyname
    , ctry.currencycode
    , pspd.fromdate
    , pspd.todate
    , ic.company_name
    , gt.method
    , ct.type_no

FROM
    customer_trans ct
        JOIN cust_allocate ca ON ct.id=ca.from
        JOIN gl_trans gt ON gt.type_no=ct.type_no
        INNER JOIN placing_slip ps ON ps.id=ca.pid
        JOIN placing_slip_premiumdetails  pspd ON pspd.placing_slip_id=ps.id
        JOIN insurance_company ic ON ic.id=pspd.insurance_company_id
        LEFT JOIN covers cv ON cv.id=ps.cover_id
        JOIN customers c ON c.id=ps.customer_id
        JOIN customer_contact cc ON cc.customer_id=c.id
        JOIN city cty ON cty.id=cc.city
        JOIN country ctry ON ctry.id=cc.country

        where ct.id='$id' and ct.account=gt.account";

      
         $Q = $this->db->query($sql);

        if ($Q->num_rows() > 0)
        {
            foreach ($Q->result_array() as $row)
            {
                $data[] = $row;
            }
        }
        $Q->free_result();
        return $data;
    }

    function generate_rv($rid)
    {
        $res = $this->db->query("SELECT * FROM gl_trans gt JOIN refs r   ON r.id=gt.type_no WHERE amount<0 and  gt.type_no=$rid");
        return $res->result_array();
    }

    function generate_pv($rid)
    {
        $res = $this->db->query("SELECT * FROM gl_trans gt JOIN refs r   ON r.id=gt.type_no WHERE amount>0 and  gt.type_no=$rid");
        return $res->result_array();
    }

    function show_trans_pslip($refid)
    {


        $res = $this->db->query("SELECT * FROM placing_slip_refs p JOIN gl_trans  gt ON p.id=gt.type_no JOIN refs r ON p.id=r.id WHERE r.id='$refid' group by gt.id");
        return $res->result_array();
    }

    function get_ref_pslip($pid, $type)
    {
        $res = $this->db->query("SELECT r.id FROM placing_slip_refs p JOIN refs r ON p.id=r.id  WHERE r.type='$type' and p.pslip_id='$pid' ");
        return $res->row()->id;
    }

    function search_trans($pageno, $type, $ref, $rtype, $from = '', $to = '')
    {

        if ($rtype != 'all')
        {
            $where = "r.type=$rtype ";
        }
        else
        {
            $where = "gt.type_no != '' ";
        }
        if ($from != '')
            $from = $this->mastermodel->convdatformat($from);
        if ($to != '')
            $to = $this->mastermodel->convdatformat($to);

        if ($type == 'data')
        {

            $limit = (($pageno - 1) * 10);
            $data = array();
            $sql = "
                                  select fy.closed, sum(gt.amount) as amount,gt.memo,tt.transaction,  
                                  gt.type_no as id,r.type, r.reference as ref,gt.tran_date
                                  from gl_trans gt JOIN refs r ON r.id=gt.type_no 
                                  JOIN transaction_types tt ON tt.id=r.type
                                  JOIN audit_trail au ON au.trans_no=gt.type_no 
                                  JOIN fiscal_year fy ON fy.id=au.fiscal_year
                                  where $where ";
            if ($ref != '' && $ref != ' ')
                $sql .= "and r.reference like '$ref%' ";
            if ($from != '')
                $sql.=" and gt.tran_date >= '$from '";
            if ($to != '')
                $sql.=" and gt.tran_date <= '$to'";
            $sql.="and gt.amount>0  group by gt.type_no order by gt.type_no desc   limit " . $limit . "," . 10;
            $res = $this->db->query($sql);
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
            return $data;
        }
        else if ($type == 'count')
        {

            $sql = "select fy.closed, sum(gt.amount) as amount,gt.memo,tt.transaction , gt.type_no as id,r.type,
                                    r.reference as ref,gt.tran_date from gl_trans gt JOIN refs r ON r.id=gt.type_no
                                    JOIN transaction_types tt ON tt.id=r.type JOIN audit_trail au ON au.trans_no=gt.type_no JOIN fiscal_year fy ON fy.id=au.fiscal_year
                     where $where ";

            if ($ref != '' && $ref != ' ')
                $sql .= "and r.reference like '$ref%' ";
            if ($from != '')
                $sql.=" and gt.tran_date >= '$from'";
            if ($to != '')
                $sql.=" and gt.tran_date <= '$to'";
            $sql.="and gt.amount>0 group by gt.type_no";
            $res = $this->db->query($sql);
            return $res->num_rows();
        }
    }

    function get_main_trail_balance($date1, $date2)
    {

        $data = array();


        $date1 = $this->mastermodel->convdatformat($date1);
        $date2 = $this->mastermodel->convdatformat($date2);
      
        $qry = "SELECT
                `chart_master`.`account_name` as main_head,
                `cm2`.`account_name` as sub_head,
                SUM(If(`gl_trans`.tran_date> '$date1' AND `gl_trans`.tran_date < '$date2',IF(`gl_trans`.`amount` < 0 , `gl_trans`.`amount` , 0),0)) AS credit,
                SUM(if(`gl_trans`.tran_date> '$date1' AND `gl_trans`.tran_date < '$date2',IF(`gl_trans`.`amount` > 0 , `gl_trans`.`amount` , 0),0)) AS debit,
                sum(if(`gl_trans`.tran_date< '$date1',if(`gl_trans`.amount<0,`gl_trans`.amount,0),0)) as opencredit,
                sum(if(`gl_trans`.tran_date< '$date1',if(`gl_trans`.amount>0,`gl_trans`.amount,0),0)) as opendebit,
                IF(chart_master.parent=0,chart_master.account_name,cm2.account_name) as account_name ,
                IF(chart_master.parent=0,chart_master.account_code,cm2.account_code) as account,
                IF(chart_master.parent=0,chart_master.id,cm2.id) as cgid
            FROM `gl_trans`
            INNER JOIN `chart_master` ON (`gl_trans`.`account` = `chart_master`.`account_code`)
            LEFT JOIN `chart_master` AS `cm2`  ON (`chart_master`.`parent` = `cm2`.`id`)
            GROUP BY cgid
            order by cgid";
        $res = $this->db->query($qry);
        if ($res->num_rows() > 0)
        {
            foreach ($res->result_array() as $row)
            {
                $data[$row['cgid']][] = $row;
            }
        }
        $res->free_result();
        return $data;
    }

    function get_trail_balance($date1, $date2, $mainacc = "", $rangefrom = "", $rangeto = "")
    {

        $data = array();


        $date1 = $this->mastermodel->convdatformat($date1);
        $date2 = $this->mastermodel->convdatformat($date2);

        $cust = "";

        if (!empty($mainacc) && !empty($rangefrom) && !empty($rangeto))
        {
            $cust = "where cm.parent='$mainacc' and cm.account_code between '$rangefrom' and '$rangeto'";
        }
        if (!empty($mainacc) && empty($rangefrom) && empty($rangeto))
        {
            $cust = "where cm.parent='$mainacc'";
        }

        if (!empty($rangefrom) && !empty($rangeto))
        {
            $cust = "where cm.account_code between '$rangefrom' and '$rangeto'";
        }

        $qry = "SELECT sum(if(gt.tran_date>='$date1' and gt.tran_date <='$date2',if(gt.amount<0,amount,0),0))as credit,

                sum(if(gt.tran_date>='$date1' and gt.tran_date <='$date2',if(gt.amount>0,amount,0),0))as debit,
                sum(if(gt.tran_date< '$date1',if(gt.amount<0,gt.amount,0),0)) as opencredit, sum(if(gt.tran_date< '$date1',if(gt.amount>0,gt.amount,0),0)) as opendebit,
                cm.account_code as account,cm.account_name FROM chart_master cm left join gl_trans gt ON gt.account=cm.account_code 
                $cust group by cm.account_code";


        $res = $this->db->query($qry);

        if ($res->num_rows() > 0)
        {
            foreach ($res->result_array() as $row)
            {
                $data[] = $row;
            }
        }
        $res->free_result();
        return $data;
    }

    function get_sub_gl($from, $to, $mainacc, $rangefrom, $rangeto)
    {
        $data = array();


        $date1 = $this->mastermodel->convdatformat($from);
        $date2 = $this->mastermodel->convdatformat($to);




        $cust = "";

        if (!empty($mainacc) && !empty($rangefrom) && !empty($rangeto))
        {
            $cust = "where cm.parent='$mainacc' and cm.account_code between '$rangefrom' and '$rangeto'";
        }
        if (!empty($mainacc) && empty($rangefrom) && empty($rangeto))
        {
            $cust = "where cm.parent='$mainacc'";
        }

        if (!empty($rangefrom) && !empty($rangeto))
        {
            $cust = "where cm.account_code between '$rangefrom' and '$rangeto'";
        }

        $qry1 = "SELECT if(gt.tran_date>='$date1' and gt.tran_date <='$date2',if(gt.amount<0,gt.amount,0),if(glt.tran_date>='$date1' and glt.tran_date <='$date2',if(glt.amount<0,glt.amount,0),0))as credit,
                if(gt.tran_date>='$date1' and gt.tran_date <='$date2',if(gt.amount>0,gt.amount,0),if(glt.tran_date>='$date1' and glt.tran_date <='$date2',if(glt.amount>0,glt.amount,0),0))as debit,
                ifnull(gt.tran_date,glt.tran_date) as tran_date,
                ifnull(gt.memo,glt.memo) as memo,
                ifnull(r1.reference,r2.reference) as reference,
                cm.account_name ,cm.account_code as account,cm.id as cgid FROM chart_master cm
                left join chart_master cp on cp.parent=cm.id
                left join gl_trans gt ON gt.account=cp.account_code
                left join gl_trans glt ON glt.account=cm.account_code
                left join refs r1 on  r1.id= gt.type_no
                left join refs r2 on  r2.id= glt.type_no
                join char_type ct on ct.id=cm.chart_type
                $cust  having reference!=''   order by ct.id,cm.account_code,tran_date,LEFT(r1.reference,2),LEFT(r2.reference,2),RIGHT(r1.reference ,2),RIGHT(r2.reference,2),reference asc";

        $res = $this->db->query($qry1);

        $data['transdet'] = $res->result_array();

        return $data;
    }

    /* get balance sheet */

    function get_balance_sheet($fromdate, $todate)
    {
        $fromdate = $this->mastermodel->convertdateformat($fromdate);
        $todate = $this->mastermodel->convertdateformat($todate);
        $data = array();
        $this->db->select('*,SUM(amount) as account_amount,refs.type as type,
            chart_types as chart_type,chart_master.chart_type as chart_id', false);
        $this->db->from('refs');
        $this->db->join('gl_trans', 'gl_trans.type_no=refs.id');
        $this->db->join('chart_master', 'chart_master.account_code=gl_trans.account');
        $this->db->join('char_type', 'chart_master.chart_type=char_type.id');
        if ($fromdate != 0)
            $this->db->where('tran_date >=', $fromdate);
        if ($todate != 0)
            $this->db->where('tran_date <=', $todate);

        $this->db->group_by('account');
        $this->db->order_by('account');
        $Q = $this->db->get();
        if ($Q->num_rows() > 0)
        {
            foreach ($Q->result_array() as $row)
            {
                $data[$row['account']] = $row;

            }
        }
        $Q->free_result();
        return $data;
    }

    function get_main_gl($rangefrom, $rangeto, $fromdate, $todate)
    {
        $data = array();


        $date1 = $this->mastermodel->convdatformat($fromdate);
        $date2 = $this->mastermodel->convdatformat($todate);




        $qry1 = "SELECT if(gt.tran_date>='$date1' and gt.tran_date <='$date2',if(gt.amount<0,sum(gt.amount),0),if(glt.tran_date>='$date1' and glt.tran_date <='$date2',if(glt.amount<0,sum(glt.amount),0),0))as credit,
                if(gt.tran_date>='$date1' and gt.tran_date <='$date2',if(gt.amount>0,sum(gt.amount),0),if(glt.tran_date>='$date1' and glt.tran_date <='$date2',if(glt.amount>0,sum(glt.amount),0),0))as debit,
                ifnull(gt.tran_date,glt.tran_date) as tran_date,
                ifnull(gt.memo,glt.memo) as memo,
                ifnull(r1.reference,r2.reference) as reference,
                cm.account_name ,cm.account_code as account,cm.id as cgid FROM chart_master cm
                left join chart_master cp on cp.parent=cm.id
                left join gl_trans gt ON gt.account=cp.account_code
                left join gl_trans glt ON glt.account=cm.account_code
                left join refs r1 on  r1.id= gt.type_no
                left join refs r2 on  r2.id= glt.type_no
                join char_type ct on ct.id=cm.chart_type
                where cm.parent=0 and 
                cm.account_code between '$rangefrom' and '$rangeto' 
        group by reference order by ct.id,cm.account_code,tran_date,LEFT(r1.reference,2),LEFT(r2.reference,2),RIGHT(r1.reference ,2),RIGHT(r2.reference,2),reference asc";

        $res = $this->db->query($qry1);

        $data['transdet'] = $res->result_array();

        return $data;
    }

    function get_ageing_report($date, $accval, $type, $cid)
    {
        $data = array();

        $acccode = $accval;
        $acctype = $type;



        $date = $this->mastermodel->convdatformat($date);



        $mindate = $this->mintransdate($acccode, $acctype);



        if ($acctype == 3)
        {

            $table = 'customer_trans';

            $qry = "select customers.code,customers.type,customer_contact.address
    , customer_contact.postbox,country.countryname
    , city.cityname FROM customers
    INNER JOIN  customer_contact ON (customer_contact.customer_id = customers.id)
    INNER JOIN  country
        ON (country.id = customer_contact.country)
    INNER JOIN  city
        ON (city.id = customer_contact.city)  where customers.id='$cid' ";

            $cdet = $this->db->query($qry);
            $data['accdet'] = $cdet->row();

            //   $table=
            $qry = "SELECT
    customers.code
                    
    , gl_trans.account
    , gl_trans.tran_date
    , gl_trans.amount
   
    , placing_slip.cover_id
    , placing_slip.quotation_ref,
      IFNULL(placing_slip.id,0) as placingid
    , covers.cover
    , insurance_company.company_name
   
    , gl_trans.memo
    , gl_trans.account
    , refs.reference,
       psr.type,psr.pslip_id as qid,plcn.policyno
     FROM
     customers
    INNER JOIN  gl_trans
        ON (customers.code = gl_trans.account)
    INNER JOIN refs
        ON (refs.id = gl_trans.type_no)
    left join placing_slip_refs psr on psr.id=refs.id
    LEFT JOIN  placing_slip
        ON (psr.pslip_id = placing_slip.id)
    LEFT JOIN  covers
        ON (placing_slip.cover_id = covers.id)
    left join policynote plcn
           on plcn.quotation_ref=placing_slip.quotation_ref
    LEFT JOIN  placing_slip_premiumdetails
        ON (placing_slip_premiumdetails.placing_slip_id = placing_slip.id)
    LEFT JOIN  insurance_company
        ON (insurance_company.id = placing_slip_premiumdetails.insurance_company_id)
   

              where gl_trans.tran_date between '$mindate' and '$date' and customers.id='$cid' order by gl_trans.tran_date ";
    
        }
        else if ($acctype == 1)
        {

            $table = 'agent_trans';

            $qry = "Select spd.employeeid as code,spd.name
                , spa.address
                , spa.pobox as postbox
                , country.countryname
                , city.cityname
                from staffpersonaldetails spd
                LEFT JOIN staffpermaddress spa ON spd.id=spa.staffid
                LEFT JOIN  country
                          ON (country.id = spa.country)
                LEFT JOIN  city
                          ON (city.id = spa.city)
               where spd.id='$cid' ";

            $cdet = $this->db->query($qry);
            $data['accdet'] = $cdet->row();


            $qry = "Select

                    spd.employeeid as code
                     
                
                
                , at.tran_date
                , at.amount
               
                , ps.cover_id
                , ps.quotation_ref,
                 IFNULL(ps.id,0) as placingid
                , c.cover
                , ic.company_name
                
                , at.memo
                , at.account
                , r.reference,
                 psr.type,psr.pslip_id as qid,plcn.policyno
                
                   from staffpersonaldetails spd
                LEFT JOIN staffpermaddress spa ON spd.id=spa.staffid
                   INNER JOIN  gl_trans at
                             ON (spd.employeeid = at.account)
                   INNER JOIN refs r
                              ON (r.id = at.type_no)
                    left join placing_slip_refs psr on psr.id=r.id
                    LEFT JOIN  placing_slip ps
                               ON (psr.pslip_id = ps.id)
                 
                    LEFT JOIN  covers c
                             ON (ps.cover_id = c.id)
                left join policynote plcn
                on plcn.quotation_ref=ps.quotation_ref
                  LEFT JOIN  placing_slip_premiumdetails pspd
                          ON (pspd.placing_slip_id = ps.id)
                    LEFT JOIN  insurance_company ic
                                  ON (ic.id = pspd.insurance_company_id)
                
              where at.tran_date  between '$mindate' and '$date'  and spd.id='$cid' order by at.tran_date ";
        }
        else if ($acctype == 2)
        {

            $table = 'company_trans';

            $qry = "select ic.company_code as code
                      
                        , ic.company_name as name
                , ic.address
                , ic.po_box as postbox
                , country.countryname
                , city.cityname
                from insurance_company ic
                   LEFT JOIN  country
                          ON (country.id = ic.country_id)
                LEFT JOIN  city
                          ON (city.id = ic.city_id)
              where ic.id='$cid'  ";

            $cdet = $this->db->query($qry);
            $data['accdet'] = $cdet->row();

            $qry = "Select

                                ic.company_code as code
                              
                , ct.account
                , ct.tran_date
                , ct.amount
                
                , ps.cover_id
                , ps.quotation_ref,
                  IFNULL(ps.id,0) as placingid
                , c.cover

                
                
                , ct.memo
                , ct.account
                , r.reference,
                 psr.type,psr.pslip_id as qid,plcn.policyno
                   from insurance_company ic

                   INNER JOIN gl_trans ct
                             ON (ic.company_code = ct.account)
                   INNER JOIN refs r
                              ON (r.id = ct.type_no)
                left join placing_slip_refs psr on psr.id=r.id
                    LEFT JOIN  placing_slip ps
                               ON (psr.pslip_id = ps.id)
                    LEFT JOIN  covers c
                             ON (ps.cover_id = c.id)
                left join policynote plcn
                on plcn.quotation_ref=ps.quotation_ref
                  LEFT JOIN  placing_slip_premiumdetails pspd
                          ON (pspd.placing_slip_id = ps.id)
                   
                LEFT JOIN  country
                          ON (country.id = ic.country_id)
                LEFT JOIN  city
                          ON (city.id = ic.city_id)
              where ct.tran_date  between '$mindate' and '$date' and ic.id='$cid' order by ct.tran_date  ";
        }


        $res = $this->db->query($qry);

        $data['transdet'] = $res->result_array();
        $empid = $cid;
        $query = $this->db->query("SELECT code,ct.account,c.type,c.id,
                 @cstaff := (select staffid from staffcustomer where customerid = c.id and date <= ct.tran_date order by date desc limit 1) as cStaff,
                 if(@cstaff='$empid', NULL,0) as isStaff,
                sum(if(@cstaff='$empid', if(ct.tran_date <= '$date' , ct.amount,0),0)) as amount1,
                sum(if(@cstaff='$empid', if(DATEDIFF('$date',ct.tran_date) >= '0' AND DATEDIFF('$date',ct.tran_date)  <='1' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0),0)) as amount2,
                sum(if(@cstaff='$empid', if(DATEDIFF('$date',ct.tran_date) > '1' AND DATEDIFF('$date',ct.tran_date)  <='30', if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0),0)) as amount3,
                sum(if(@cstaff='$empid', if(DATEDIFF('$date',ct.tran_date) > '30' AND DATEDIFF('$date',ct.tran_date)  <='90', if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0),0)) as amount4,
                sum(if(@cstaff='$empid', if(DATEDIFF('$date',ct.tran_date) > '90' AND DATEDIFF('$date',ct.tran_date)  <='180', if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0),0)) as amount5,
                sum(if(@cstaff='$empid', if(DATEDIFF('$date',ct.tran_date) > '180' AND DATEDIFF('$date',ct.tran_date)  <='270', if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0),0)) as amount6,
                sum(if(@cstaff='$empid', if(DATEDIFF('$date',ct.tran_date) > '270', if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0),0)) as amount7,
                ct.tran_date FROM   (select sum(amount) as amount,type_no,tran_date,account,memo,method,id from gl_trans where tran_date <= '$date' group by type_no,account) as ct join customers c on ct.account=c.code left join (select sum(amount) as amount,type_no,tran_date,account,memo,alloc,pid,id from customer_trans where tran_date <= '$date' group by type_no,account) as g on ct.type_no=g.type_no and ct.account=g.account ,(select @cstaff:=-1 ) t
                group by cStaff  having isStaff IS NULL ");



        //$query=$this->db->query("select if(SUM(cr.amount)<0,concat(format(abs(sum(cr.amount)),2),' Cr'),concat(format(abs(sum(cr.amount)),2),' Dr')) as amount from (select sum(amount) as amount,type_no,tran_date,account,memo,method,id from gl_trans where tran_date <= '$date' group by type_no,account) as cr left join (select sum(amount) as amount,type_no,tran_date,account,memo,alloc,pid,id from $table where tran_date <= '$date' group by type_no,account) as  ct on cr.type_no=ct.type_no and cr.account=ct.account where cr.tran_date <='$date' and cr.account='$acccode'");
        $bal = $query->row();
        if ($bal->amount1 < 0)
            $sfx1 = ' Cr';
        else
            $sfx1 = ' Dr';

        if ($bal->amount2 < 0)
            $sfx2 = ' Cr';
        else
            $sfx2 = ' Dr';

        if ($bal->amount3 < 0)
            $sfx3 = ' Cr';
        else
            $sfx3 = ' Dr';

        if ($bal->amount4 < 0)
            $sfx4 = ' Cr';
        else
            $sfx4 = ' Dr';

        if ($bal->amount5 < 0)
            $sfx5 = ' Cr';
        else
            $sfx5 = ' Dr';

        if ($bal->amount6 < 0)
            $sfx6 = ' Cr';
        else
            $sfx6 = ' Dr';

        if ($bal->amount7 < 0)
            $sfx7 = ' Cr';
        else
            $sfx7 = ' Dr';


        $data['balance'] = number_format($bal->amount1, 2) . $sfx1;


        //$query=$this->db->query("select if(SUM(if(DATEDIFF('$date',ct.tran_date) >= '0' AND DATEDIFF('$date',ct.tran_date)  <='1' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0))<0,concat(format(abs(sum(if(DATEDIFF('$date',ct.tran_date) >= '0' AND DATEDIFF('$date',ct.tran_date)  <='1' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0))),2),' Cr'),concat(format(abs(sum(if(DATEDIFF('$date',ct.tran_date) >= '0' AND DATEDIFF('$date',ct.tran_date)  <='1' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0))),2),' Dr'))  as amount from (select sum(amount) as amount,type_no,tran_date,account,memo,method,id from gl_trans where tran_date <= '$date' group by type_no,account) as ct left join (select sum(amount) as amount,type_no,tran_date,account,memo,alloc,pid,id from $table where tran_date <= '$date' group by type_no,account) as  cr on cr.type_no=ct.type_no and cr.account=ct.account where  ct.account='$acccode'");
        //$bal=$query->row();
        $data['current'] = number_format($bal->amount2, 2) . $sfx2;



//             $query=$this->db->query("select if(SUM(if(DATEDIFF('$date',ct.tran_date) > '1' AND DATEDIFF('$date',ct.tran_date)  <='30' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0))<0,concat(format(abs(sum(if(DATEDIFF('$date',ct.tran_date) > '1' AND DATEDIFF('$date',ct.tran_date)  <='30' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0))),2),' Cr'),concat(format(abs(sum(if(DATEDIFF('$date',ct.tran_date) > '1' AND DATEDIFF('$date',ct.tran_date)  <='30' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0))),2),' Dr'))  as amount from (select sum(amount) as amount,type_no,tran_date,account,memo,method,id from gl_trans where tran_date <= '$date' group by type_no,account) as ct left join (select sum(amount) as amount,type_no,tran_date,account,memo,alloc,pid,id from $table where tran_date <= '$date' group by type_no,account) as cr on cr.type_no=ct.type_no and cr.account=ct.account where  ct.account='$acccode'");
//             
//             $bal=$query->row();
        $data['lthirty'] = number_format($bal->amount3, 2) . $sfx3;


//             $query=$this->db->query("select if(SUM(if(DATEDIFF('$date',ct.tran_date) > '30' AND DATEDIFF('$date',ct.tran_date)  <='90' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0))<0,concat(format(abs(sum(if(DATEDIFF('$date',ct.tran_date) > '30' AND DATEDIFF('$date',ct.tran_date)  <='90' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0))),2),' Cr'),concat(format(abs(sum(if(DATEDIFF('$date',ct.tran_date) > '30' AND DATEDIFF('$date',ct.tran_date)  <='90' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0))),2),' Dr'))  as amount from (select sum(amount) as amount,type_no,tran_date,account,memo,method,id from gl_trans where tran_date <= '$date' group by type_no,account) as ct left join (select sum(amount) as amount,type_no,tran_date,account,memo,alloc,pid,id from $table where tran_date <= '$date' group by type_no,account) as cr on cr.type_no=ct.type_no and cr.account=ct.account where  ct.account='$acccode'");
//             $bal=$query->row();
        $data['lninty'] = number_format($bal->amount4, 2) . $sfx4;


//             $query=$this->db->query("select if(SUM(if(DATEDIFF('$date',ct.tran_date) > '90' AND DATEDIFF('$date',ct.tran_date)  <='180' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0))<0,concat(format(abs(sum(if(DATEDIFF('$date',ct.tran_date) > '90' AND DATEDIFF('$date',ct.tran_date)  <='180' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0))),2),' Cr'),concat(format(abs(sum(if(DATEDIFF('$date',ct.tran_date) > '90' AND DATEDIFF('$date',ct.tran_date)  <='180' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0))),2),' Dr'))  as amount from (select sum(amount) as amount,type_no,tran_date,account,memo,method,id from gl_trans where tran_date <= '$date' group by type_no,account) as ct left join (select sum(amount) as amount,type_no,tran_date,account,memo,alloc,pid,id from $table where tran_date <= '$date' group by type_no,account) as cr on cr.type_no=ct.type_no and cr.account=ct.account where  ct.account='$acccode'");
//             $bal=$query->row();
        $data['loneeighty'] = number_format($bal->amount5, 2) . $sfx5;


//             $query=$this->db->query("select if(SUM(if(DATEDIFF('$date',ct.tran_date) > '180' AND DATEDIFF('$date',ct.tran_date)  <='270' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0))<0,concat(format(abs(sum(if(DATEDIFF('$date',ct.tran_date) > '180' AND DATEDIFF('$date',ct.tran_date)  <='270' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0))),2),' Cr'),concat(format(abs(sum(if(DATEDIFF('$date',ct.tran_date) > '180' AND DATEDIFF('$date',ct.tran_date)  <='270' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0))),2),' Dr'))  as amount from (select sum(amount) as amount,type_no,tran_date,account,memo,method,id from gl_trans where tran_date <= '$date' group by type_no,account) as ct left join (select sum(amount) as amount,type_no,tran_date,account,memo,alloc,pid,id from $table where tran_date <= '$date' group by type_no,account) as cr on cr.type_no=ct.type_no and cr.account=ct.account where  ct.account='$acccode'");
//             $bal=$query->row();
        $data['ltseventy'] = number_format($bal->amount6, 2) . $sfx6;


//             $query=$this->db->query("select if(SUM(if(DATEDIFF('$date',ct.tran_date) > '270' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0))<0,concat(format(abs(sum(if(DATEDIFF('$date',ct.tran_date) > '270' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0))),2),' Cr'),concat(format(abs(sum(if(DATEDIFF('$date',ct.tran_date) > '270' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0))),2),' Dr'))  as amount from (select sum(amount) as amount,type_no,tran_date,account,memo,method,id from gl_trans where tran_date <= '$date' group by type_no,account) as ct left join (select sum(amount) as amount,type_no,tran_date,account,memo,alloc,pid,id from $table where tran_date <= '$date' group by type_no,account) as cr on cr.type_no=ct.type_no and cr.account=ct.account  where  ct.account='$acccode'");
//             $bal=$query->row();
        $data['ltsixty'] = number_format($bal->amount7, 2) . $sfx7;

        return $data;
    }

    function get_ageingsummary_report($date, $accval, $empid = "")
    {
        $data = array();
        $date = $this->mastermodel->convdatformat($date);
        $mixedqry = "sum(if(ct.tran_date <= '$date' ,ct.amount,0)) as amount1,
                        sum(if(DATEDIFF('$date',ct.tran_date) >= '0' AND DATEDIFF('$date',ct.tran_date)  <='1' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0)) as amount2,
                        sum(if(DATEDIFF('$date',ct.tran_date) > '1' AND DATEDIFF('$date',ct.tran_date)  <='30' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0)) as amount3,
                        sum(if(DATEDIFF('$date',ct.tran_date) > '30' AND DATEDIFF('$date',ct.tran_date)  <='90' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0)) as amount4,
                        sum(if(DATEDIFF('$date',ct.tran_date) > '90' AND DATEDIFF('$date',ct.tran_date)  <='180' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0)) as amount5,
                        sum(if(DATEDIFF('$date',ct.tran_date) > '180' AND DATEDIFF('$date',ct.tran_date)  <='270' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0)) as amount6,
                        sum(if(DATEDIFF('$date',ct.tran_date) > '270' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0)) as amount7";


        if ($accval == 1)
        {

            $qry = "Select spd.employeeid as code,spd.name
                , spa.address
                , spa.pobox as postbox
                , country.countryname
                , city.cityname
                from staffpersonaldetails spd
                LEFT JOIN staffpermaddress spa ON spd.id=spa.staffid
                LEFT JOIN  country
                          ON (country.id = spa.country)
                LEFT JOIN  city
                          ON (city.id = spa.city)
               where spd.id='$empid' ";

            $cdet = $this->db->query($qry);
            $data['accdet'] = $cdet->row();

            $qry = "SELECT code,ct.account,c.type,c.id,
                 @cstaff := (select staffid from staffcustomer where customerid = c.id and date <= ct.tran_date order by date desc limit 1) as cStaff,
                 if(@cstaff='$empid', NULL,0) as isStaff,
                sum(if(@cstaff='$empid', if(ct.tran_date <= '$date' , ct.amount,0),0)) as amount1,
                sum(if(@cstaff='$empid', if(DATEDIFF('$date',ct.tran_date) >= '0' AND DATEDIFF('$date',ct.tran_date)  <='1' , if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0),0)) as amount2,
                sum(if(@cstaff='$empid', if(DATEDIFF('$date',ct.tran_date) > '1' AND DATEDIFF('$date',ct.tran_date)  <='30', if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0),0)) as amount3,
                sum(if(@cstaff='$empid', if(DATEDIFF('$date',ct.tran_date) > '30' AND DATEDIFF('$date',ct.tran_date)  <='90', if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0),0)) as amount4,
                sum(if(@cstaff='$empid', if(DATEDIFF('$date',ct.tran_date) > '90' AND DATEDIFF('$date',ct.tran_date)  <='180', if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0),0)) as amount5,
                sum(if(@cstaff='$empid', if(DATEDIFF('$date',ct.tran_date) > '180' AND DATEDIFF('$date',ct.tran_date)  <='270', if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0),0)) as amount6,
                sum(if(@cstaff='$empid', if(DATEDIFF('$date',ct.tran_date) > '270', if(ct.amount<0,ct.amount+alloc,ct.amount-alloc),0),0)) as amount7,
                ct.tran_date FROM   (select sum(amount) as amount,type_no,tran_date,account,memo,method,id from gl_trans where tran_date <= '$date' group by type_no,account) as ct join customers c on ct.account=c.code left join (select sum(amount) as amount,type_no,tran_date,account,memo,alloc,pid,id from customer_trans where tran_date <= '$date' group by type_no,account) as g on ct.type_no=g.type_no and ct.account=g.account ,(select @cstaff:=-1 ) t
                group by code,cStaff  having isStaff IS NULL and (amount1!=0 OR amount2!=0 OR amount3!=0 OR amount4!=0 OR amount5!=0 OR amount6!=0 OR amount7!=0) order by code desc";

        }
        else if ($accval == 2)
        {
            $data['accdet'] = "";
            $qry = "Select ic.company_code as code ,ic.company_name as name, ct.account,
                    
                    $mixedqry
                    FROM
                    (select sum(amount) as amount,type_no,tran_date,account,memo,method,id from gl_trans where tran_date <= '$date' group by type_no,account) as ct      
                    inner join insurance_company ic ON (ic.company_code = ct.account)
                    inner join refs on refs.id=ct.type_no
                    left JOIN  (select sum(amount) as amount,type_no,tran_date,account,memo,alloc,pid,id from company_trans where tran_date <= '$date' group by type_no,account) as g ON ct.type_no=g.type_no and ct.account=g.account
                    group by code having amount1!=0  ";
        }
        else if ($accval == 3)
        {
            $data['accdet'] = "";
            $qry = "Select customers.code, ct.account,customers.type,customers.id,

                     $mixedqry

                     FROM
                     (select sum(amount) as amount,type_no,tran_date,account,memo,method,id from gl_trans where tran_date <= '$date' group by type_no,account) as ct   
                     inner join customers ON (customers.code = ct.account)
                     inner join refs on refs.id=ct.type_no
                     left JOIN  (select sum(amount) as amount,type_no,tran_date,account,memo,alloc,pid,id from customer_trans where tran_date <= '$date' group by type_no,account) as g on ct.type_no=g.type_no and ct.account=g.account                     
                     group by code having amount1!=0";
        }
        
        $res = $this->db->query($qry);
        $data['transdet'] = $res->result_array();
        return $data;
    }

    function get_ageingsummary_report_new($date, $accval, $empid = "")
    {
        $data = array();
        $date = $this->mastermodel->convdatformat($date);
        $mixedqry = "sum(if(ct.tran_date <= '$date' ,ct.amount,0)) as amount1";


        if ($accval == 1)
        {

            $qry = "select spd.employeeid as code,spd.name
                , spa.address
                , spa.pobox as postbox
                , country.countryname
                , city.cityname
                from staffpersonaldetails spd
                LEFT JOIN staffpermaddress spa ON spd.id=spa.staffid
                LEFT JOIN  country
                          ON (country.id = spa.country)
                LEFT JOIN  city
                          ON (city.id = spa.city)
               where spd.id='$empid' ";

            $cdet = $this->db->query($qry);
            $data['accdet'] = $cdet->row();

            $qry = "SELECT code,ct.account,c.type,c.id,
                 @cstaff := (select staffid from staffcustomer where customerid = c.id and date <= ct.tran_date order by date desc limit 1) as cStaff,
                 if(@cstaff='$empid', NULL,0) as isStaff,
                sum(if(@cstaff='$empid', if(ct.tran_date <= '$date' , ct.amount,0),0)) as amount1,
                ct.tran_date FROM   (select sum(amount) as amount,type_no,tran_date,account,memo,method,id from gl_trans where tran_date <= '$date' group by type_no,account) as ct join customers c on ct.account=c.code left join (select sum(amount) as amount,type_no,tran_date,account,memo,alloc,pid,id from customer_trans where tran_date <= '$date' group by type_no,account) as g on ct.type_no=g.type_no and ct.account=g.account ,(select @cstaff:=-1 ) t
                group by code,cStaff  having isStaff IS NULL and (amount1 > 0 ) order by code desc";

        }
        else if ($accval == 2)
        {
            $data['accdet'] = "";
            $qry = "SELECT ic.company_code as code ,ic.company_name as name, ct.account,
                    
                    $mixedqry
                    FROM
                    (select sum(amount) as amount,type_no,tran_date,account,memo,method,id from gl_trans where tran_date <= '$date' group by type_no,account) as ct      
                    inner join insurance_company ic ON (ic.company_code = ct.account)
                    group by code having amount1 > 0  ";
        }
        else if ($accval == 3)
        {
            $data['accdet'] = "";
            $qry = "SELECT customers.code, ct.account,customers.type,customers.id,

                     $mixedqry

                     FROM
                     (select sum(amount) as amount,type_no,tran_date,account,memo,method,id from gl_trans where tran_date <= '$date' group by type_no,account) as ct   
                     inner join customers ON (customers.code = ct.account)
                     group by code having amount1 > 0";
        }
        $res = $this->db->query($qry);
        $data['transdet'] = $res->result_array();
        return $data;
    }
    
    function opening_trail_balance($code, $date1, $date2)
    {

        $data = array();
        $date1 = $this->mastermodel->convdatformat($date1);
        $qry = "SELECT IFNULL(SUM(if(gt.amount<0,gt.amount,0)),0) as opencredit, IFNULL(SUM(if(gt.amount>0,gt.amount,0)),0) as opendebit FROM gl_trans gt  where  gt.account='$code' and  gt.tran_date < '$date1' ";

        $res = $this->db->query($qry);
        $data = $res->row();
        return $data;
    }

    function opening_maintrail_balance($code, $date1, $date2)
    {

        $data = array();
        $date1 = $this->mastermodel->convdatformat($date1);

        $qry = "select sum(if(gt.tran_date< '$date1',if(gt.amount<0,gt.amount,0),if(glt.tran_date< '$date1',if(glt.amount<0,glt.amount,0),0))) as opencredit,
                sum(if(gt.tran_date< '$date1',if(gt.amount>0,gt.amount,0),if(glt.tran_date< '$date1',if(glt.amount>0,glt.amount,0),0))) as opendebit
                FROM chart_master cm
                left join chart_master cp on cp.parent=cm.id
                left join gl_trans gt ON gt.account=cp.account_code
                left join gl_trans glt ON glt.account=cm.account_code
                 where  cm.account_code='$code'";


        $res = $this->db->query($qry);
        $data = $res->row();
        return $data;
    }

    function get_statement_account($value, $type, $cid, $date1, $date2)
    {

        $data = array();
        $date1 = $this->mastermodel->convdatformat($date1);
        $date2 = $this->mastermodel->convdatformat($date2);
        if ($type == 3)
        {

            $qry = "select customers.code,customers.type,customer_contact.address
                    , customer_contact.postbox,country.countryname
                    , city.cityname FROM customers
                    INNER JOIN  customer_contact ON (customer_contact.customer_id = customers.id)
                    INNER JOIN  country
                        ON (country.id = customer_contact.country)
                    INNER JOIN  city
                        ON (city.id = customer_contact.city)  where customers.id='$cid' ";

            $cdet = $this->db->query($qry);
            $data['accdet'] = $cdet->row();
            $where = "";
            if ($date1 != 0)
            {
                $where = " and gl_trans.tran_date < '$date1' ";
            }
            $qry = "               
            SELECT SUM(IF(gl_trans.amount<0,gl_trans.amount,0)) as credit, 
            SUM(IF(gl_trans.amount>0,gl_trans.amount,0)) as debit,cm.account_name    
            FROM customers
            INNER JOIN  gl_trans ON (customers.code = gl_trans.account)
            INNER join chart_master cm ON gl_trans.account=cm.account_code
            where  customers.id='$cid' $where  group by gl_trans.account";


            $res = $this->db->query($qry);
            $data['openbalance'] = $res->row();

            $qry = "SELECT
                  customers.code
                , customers.type
                , customer_contact.address
                , customer_contact.postbox
                , gl_trans.account
                , gl_trans.tran_date
                , gl_trans.id as lsid
                , gl_trans.amount
                , placing_slip.cover_id
                , placing_slip.quotation_ref
                , IFNULL(placing_slip.id,0) as placingid
                , placing_slip.currencytype
                , covers.cover
                , insurance_company.company_name
                , country.countryname
                , city.cityname
                , gl_trans.memo
                , gl_trans.type_no as refs_no
                , refs.reference,
                psr.type,psr.pslip_id as qid,
                plcn.policyno, placing_slip.remarks as remarks
                FROM
                customers
                INNER JOIN  gl_trans
                    ON (customers.code = gl_trans.account)
                INNER JOIN refs
                    ON (refs.id = gl_trans.type_no)
                left join placing_slip_refs psr on psr.id=refs.id
                LEFT JOIN  placing_slip
                    ON (psr.pslip_id = placing_slip.id)
                LEFT JOIN  customer_contact
                    ON (customer_contact.customer_id = customers.id)
                LEFT JOIN  covers
                    ON (placing_slip.cover_id = covers.id)
                LEFT JOIN  placing_slip_premiumdetails
                    ON (placing_slip_premiumdetails.placing_slip_id = placing_slip.id)
                left join policynote plcn
                    on plcn.quotation_ref=placing_slip.quotation_ref
                LEFT JOIN  insurance_company
                    ON (insurance_company.id = placing_slip_premiumdetails.insurance_company_id)
                left JOIN  country
                    ON (country.id = customer_contact.country)
                left JOIN  city
                    ON (city.id = customer_contact.city)

              where gl_trans.tran_date between '$date1' and '$date2' and customers.id='$cid' order by gl_trans.tran_date,lsid";

        }
        else if ($type == 1)
        {
            $where = "";
            if ($date1 != 0)
            {
                $where = " and at.tran_date < '$date1' ";
            }

            $qry = "               
            SELECT SUM(IF(at.amount<0,at.amount,0)) as credit, SUM(IF(at.amount>0,at.amount,0)) as debit,cm.account_name    
            FROM staffpersonaldetails spd
            INNER JOIN  gl_trans at ON (spd.employeeid = at.account)
            INNER join chart_master cm ON at.account=cm.account_code
            where  spd.id='$cid' $where group by at.account";


            $res = $this->db->query($qry);
            $data['openbalance'] = $res->row();

            $qry = "Select spd.employeeid as code,spd.name
                , spa.address
                , spa.pobox as postbox
                , country.countryname
                , city.cityname
                from staffpersonaldetails spd
                LEFT JOIN staffpermaddress spa ON spd.id=spa.staffid
                LEFT JOIN  country
                          ON (country.id = spa.country)
                LEFT JOIN  city
                          ON (city.id = spa.city)
               where spd.id='$cid' ";

            $cdet = $this->db->query($qry);
            $data['accdet'] = $cdet->row();

            $qry = "Select

                    spd.employeeid as code
                     
    , spd.name
    , spa.address
    , spa.pobox as postbox
    , at.account
    , at.tran_date
    , at.amount
    , at.id as lsid
    , ps.cover_id
    , ps.quotation_ref,
      IFNULL(ps.id,0) as placingid,
      ps.currencytype
    , c.cover
    , ic.company_name
    , country.countryname
    , city.cityname
    , at.type_no as refs_no
    , at.memo
    , at.account
    , r.reference,
     psr.type,psr.pslip_id as qid ,
     plcn.policyno
                   from staffpersonaldetails spd
                LEFT JOIN staffpermaddress spa ON spd.id=spa.staffid
                   INNER JOIN  gl_trans at
                             ON (spd.employeeid = at.account)
                   INNER JOIN refs r
                              ON (r.id = at.type_no)
                 left join placing_slip_refs psr on psr.id=r.id
                    LEFT JOIN  placing_slip ps
                               ON (psr.pslip_id = ps.id)
                    LEFT JOIN  covers c
                             ON (ps.cover_id = c.id)
                  LEFT JOIN  placing_slip_premiumdetails pspd
                          ON (pspd.placing_slip_id = ps.id)
                left join policynote plcn
             on plcn.quotation_ref=ps.quotation_ref
                    LEFT JOIN  insurance_company ic
                                  ON (ic.id = pspd.insurance_company_id)
                LEFT JOIN  country
                          ON (country.id = spa.country)
                LEFT JOIN  city
                          ON (city.id = spa.city)
              where at.tran_date between '$date1' and '$date2' and spd.id='$cid' order by at.tran_date,lsid ";

        }
        else if ($type == 2)
        {


            $qry = "select ic.company_code as code
                      
                        , ic.company_name as name
                , ic.address
                , ic.po_box as postbox
                , country.countryname
                , city.cityname
                from insurance_company ic
                   LEFT JOIN  country
                          ON (country.id = ic.country_id)
                LEFT JOIN  city
                          ON (city.id = ic.city_id)
              where ic.id='$cid'  ";

            $cdet = $this->db->query($qry);
            $data['accdet'] = $cdet->row();
            $qry = "               
    SELECT SUM(IF(ct.amount<0,ct.amount,0)) as credit, 
    SUM(IF(ct.amount>0,ct.amount,0)) as debit
    FROM insurance_company ic
    INNER JOIN  gl_trans ct on (ic.company_code = ct.account)    
    where ct.tran_date < '$date1' and ic.id='$cid' group by ct.account";

            $res = $this->db->query($qry);
            $data['openbalance'] = $res->row();

            $qry = "Select 
    ic.company_code as code,
    ic.company_name as name,
    ic.address,
    ic.po_box as postbox,
    ct.account,
    ct.tran_date,
    ct.amount,
    ct.id as lsid,
    ps.cover_id,
    ps.quotation_ref,
    IFNULL(ps.id, 0) as placingid,
    ps.currencytype,
    c.cover,
    country.countryname,
    city.cityname,
    ct.memo,
    ct.account,
    ct.type_no as refs_no,
    r.reference,
    psr.type,
    psr.pslip_id as qid,
    plcn.policyno,
    ifnull(cpi.insured, cco.insured) as insuredcustomer,
    csr.code as customercode,
    pspd.premium,
    es.brokerage,
    es.ispercentage,
    es.paymentoptions as es_payment_method,
    pspd.payment_method as ps_payment_method
from
    insurance_company ic
        INNER JOIN
    gl_trans ct ON (ic.company_code = ct.account)
        INNER JOIN
    refs r ON (r.id = ct.type_no)
        left join
    placing_slip_refs psr ON psr.id = r.id
        LEFT JOIN
    placing_slip psp ON (psr.pslip_id = psp.id and psr.type = 'issue')
        left join
    endorsement es ON (es.id = psr.pslip_id and psr.type = 'endorsement')
        left join
    cancellation cs ON (cs.id = psr.pslip_id and psr.type = 'cancellation')
        left join
    policynote pln ON (es.policyid = pln.id or cs.policyid = pln.id)
        left join
    placing_slip ps ON (psp.id = ps.id or pln.quotation_ref = ps.quotation_ref)
        LEFT JOIN
    customer_personal_ind cpi ON (ps.customer_id = cpi.customer_id)
        LEFT JOIN
    customer_corp_info cco ON (ps.customer_id = cco.customer_id)
        LEFT JOIN
    customers csr ON csr.id = ps.customer_id
        LEFT JOIN
    covers c ON (ps.cover_id = c.id)
        LEFT JOIN
    placing_slip_premiumdetails pspd ON (pspd.placing_slip_id = ps.id)
        left join
    policynote plcn ON plcn.quotation_ref = ps.quotation_ref
        LEFT JOIN
    country ON (country.id = ic.country_id)
        LEFT JOIN
    city ON (city.id = ic.city_id)
where
    ct.tran_date between '$date1' and '$date2' and ic.id='$cid'
group by r.id
order by ct.tran_date , lsid";
//            echo $qry;die();
        }
        $res = $this->db->query($qry);
        
        $data['transdet'] = $res->result_array();

        $sql = "select *, unposted_pay_dep.method as method,refs.id as refs_id,
            IFNULL(rc.ch_date,'') as ch_date,IFNULL(rc.bank_name,'') as bank_name,IFNULL(rc.cheque_no,'') as ch_no,
            IFNULL(pb.bank_info,0) as bank_info,
            IF(unposted_pay_dep.type=1,'PV',IF(unposted_pay_dep.type=2,'RV','none')) as trans_type
            from refs
            join unposted_pay_dep  on unposted_pay_dep.reference=refs.id
            left join receipt_cheque rc on rc.reference=refs.id
            left join payment_bank_info pb on pb.reference=refs.id
            group by refs.id order by refs.id ";
        $result = $this->db->query($sql);
        foreach ($result->result_array() as $row)
        {
            $data['payments'][$row['refs_id']] = $row;
        }
        return $data;
    }

    function opening_bal_statementacc($date1, $code, $table)
    {

        $data = array();

        $qry = "SELECT SUM(IF(ct.amount<0,ct.amount,0)) as credit, SUM(IF(ct.amount>0,ct.amount,0)) as debit,cm.account_name  FROM $table ct join chart_master cm ON ct.account=cm.account_code
              where ct.account='$code' and tran_date <'$date1'  group by ct.account ";


        $res = $this->db->query($qry);

        return $res;
    }

    function opening_bal_bankstatementacc($date1, $code, $table)
    {

        $data = array();
        $date1 = $this->mastermodel->convdatformat($date1);
        $qry = "SELECT SUM(IF(ct.amount<0,ct.amount,0)) as credit, SUM(IF(ct.amount>0,ct.amount,0)) as debit,ba.bank_account_name as account_name  FROM $table ct JOIN bank_accounts ba ON ba.id=ct.bank_act 
              where ba.account_code='$code' and trans_date <'$date1'  group by ba.account_code ";


        $res = $this->db->query($qry);

        return $res;
    }

    function monthdays($someMonth, $someYear)
    {
        return date("t", strtotime($someYear . "-" . $someMonth . "-01"));
    }

    function get_pslip_transno($id, $type)
    {

        $data = array();
        $qry = "SELECT reference as ref  FROM placing_slip_refs psr join refs r ON r.id=psr.id  where  psr.pslip_id='$id' and r.type='$type'";
        $res = $this->db->query($qry);
        $data = $res->row()->ref;
        return $data;
    }

    function fiscaldate_check($date)
    {

        $data = array();
        $date = $this->mastermodel->convdatformat($date);
        $qry = "SELECT count(*) as count  FROM mycompany mc JOIn  fiscal_year fy ON fy.id=mc.fyear where '$date' between fy.begin and fy.end and fy.closed=0";
        $res = $this->db->query($qry);
        $data = $res->row()->count;
        return $data;
    }

    function mintransdate($acccode, $val)
    {


        if ($val == 3)
        {

            $qery = "Select  min(tran_date) as tran_date from customer_trans where (abs(amount)!=alloc)
               and account='$acccode' ";
        }
        else if ($val == 2)
        {

            $qery = "Select  min(tran_date) as tran_date from company_trans where (abs(amount)!=alloc)
                   and account='$acccode'";
        }
        else if ($val == 1)
        {
            $qery = "Select  min(tran_date) as tran_date from agent_trans where (abs(amount)!=alloc)
                   and account='$acccode'";
        }


        $query = $this->db->query($qery);
        $querydate = $query->row();
        $mindate = $querydate->tran_date;
        return $mindate;
    }

    function checkcustomer_trans($refid)
    {
        $qry = "SELECT count(*) as count  FROM customer_trans where type_no='$refid'";
        $res = $this->db->query($qry);
        $data = $res->row()->count;
        return $data;
    }

    function checkemployee_trans($refid)
    {
        $qry = "SELECT count(*) as count  FROM agent_trans where type_no='$refid'";
        $res = $this->db->query($qry);
        $data = $res->row()->count;
        return $data;
    }

    function findaccountbyno($code)
    {
        $res = $this->db->query("SELECT chart_master.account_code,chart_master.account_name FROM `chart_master` 
                where chart_master.account_code='$code'");
        $result = $res->row();

        if ($res->num_rows() > 0)
        {
            $accountno = $result->account_code;
            //$accountname_id=$result->id;
            $account_name = $result->account_name;

            $resultset = $accountno . '~' . $account_name;
        }
        else
        {
            $resultset = "";
        }

        return $resultset;
        //var_dump($resultset);die();
    }

    function get_allocation_report($value, $type, $cid, $date1, $date2)
    {

        $data = array();


        $date1 = $this->mastermodel->convdatformat($date1);
        $date2 = $this->mastermodel->convdatformat($date2);


        if ($type == 3)
        {

            //   $table=

            $qry = "select customers.code,customers.type,customer_contact.address
    , customer_contact.postbox,country.countryname
    , city.cityname FROM customers
    INNER JOIN  customer_contact ON (customer_contact.customer_id = customers.id)
    INNER JOIN  country
        ON (country.id = customer_contact.country)
    INNER JOIN  city
        ON (city.id = customer_contact.city)  where customers.id='$cid' ";

            $cdet = $this->db->query($qry);
            $data['accdet'] = $cdet->row();

            $res = $this->single_transact($cid, $date1, $date2);
        }
        else if ($type == 1)
        {

            $qry = "select spd.employeeid as code,spd.name
                , spa.address
                , spa.pobox as postbox
                , country.countryname
                , city.cityname
                from staffpersonaldetails spd
                LEFT JOIN staffpermaddress spa ON spd.id=spa.staffid
                LEFT JOIN  country
                          ON (country.id = spa.country)
                LEFT JOIN  city
                          ON (city.id = spa.city)
               where spd.id='$cid' ";

            $cdet = $this->db->query($qry);
            $data['accdet'] = $cdet->row();
            $value = $type . '~' . $value;
            $res = $this->getpayment_list($value, $date1, $date2);
        }
        else if ($type == 2)
        {


            $qry = "select ic.company_code as code
                      
                        , ic.company_name as name
                , ic.address
                , ic.po_box as postbox
                , country.countryname
                , city.cityname
                from insurance_company ic
                   LEFT JOIN  country
                          ON (country.id = ic.country_id)
                LEFT JOIN  city
                          ON (city.id = ic.city_id)
              where ic.id='$cid'  ";

            $cdet = $this->db->query($qry);
            $data['accdet'] = $cdet->row();
            $value = $type . '~' . $value;
            $res = $this->getpayment_list($value, $date1, $date2);
        }



        $data['transdet'] = $res->result_array();



        return $data;
    }
    
    
    function search_customer_receipt($pagenum) 
    {
        $data = array();
        $this->db->select("IFNULL(customer_corp_info.insured,customer_personal_ind.insured) as customer_name", FALSE);
        $this->db->from('customer_receipt');
        $this->db->join('customer_personal_ind', 'customer_personal_ind.customer_id=customer_receipt.customer_id', 'LEFT');
        $this->db->join('customer_corp_info', 'customer_corp_info.customer_id=customer_receipt.customer_id', 'LEFT');
        $this->db->join('insurance_company', 'insurance_company.id=customer_receipt.insurance_company_id', 'LEFT');
        
        $postdata = $_SESSION['searchdata'];
//        if (!empty($postdata)) {
//            $searchtext = $postdata['searchtext'];
//            $searchfield = $postdata['searchopt'];
//            $this->db->like($searchfield, $searchtext);
//        }
        $count = $this->db->count_all_results();
        $arr = $this->fpaginate->paginate($pagenum, $count);
        $data['startpage'] = $arr[0];
        $data['endpage'] = $arr[1];
        $start = $arr[2];
        $perpage = $arr[3];
        $data['count'] = $count;
        if (!empty($postdata)) {
            $searchtext = $postdata['searchtext'];
            $searchfield = $postdata['searchopt'];
            if ($searchfield == 'customer_name') {
                $this->db->having("customer_name like  '%" . $searchtext . "%'", NULL, FALSE);
            } else {
                $this->db->like($searchfield, $searchtext);
            }
            
        }
        $this->db->select("*,IFNULL(customer_corp_info.insured,customer_personal_ind.insured) as customer_name", FALSE);
        $this->db->from('customer_receipt');
        $this->db->join('customer_personal_ind', 'customer_personal_ind.customer_id=customer_receipt.customer_id', 'LEFT');
        $this->db->join('customer_corp_info', 'customer_corp_info.customer_id=customer_receipt.customer_id', 'LEFT');
        $this->db->join('insurance_company', 'insurance_company.id=customer_receipt.insurance_company_id', 'LEFT');
        $this->db->limit($perpage, $start);
        $this->db->order_by('customer_receipt_id', 'desc');
        $data['results'] = $this->db->get();
        return $data;
    }
    
    

    function insert_customer_receipt()
    {
        $sql = "SHOW TABLE STATUS LIKE 'customer_receipt'";
        $result = $this->db->query($sql);
        $increment = $result->row()->Auto_increment;
        $transaction_code = 'REC' . STR_PAD($increment,4,0,STR_PAD_LEFT);
        
        $tblValues = array(
            'transaction_code' => $transaction_code, 
            'customer_id' => $_POST['customer_id'], 
            'insurance_company_id' => $_POST['insurance_company_id'], 
            'customer_receipt_amount' => $_POST['customer_receipt_amount'], 
            'customer_receipt_date' => $this->mastermodel->convertdateformat($_POST['customer_receipt_date']), 
            'customer_payment_method' => $_POST['customer_payment_method'], 
            'customer_receipt_remarks' => $_POST['customer_receipt_remarks'], 
            'insurance_company_payment_date' => $this->mastermodel->convertdateformat($_POST['insurance_company_payment_date']), 
            'insurance_company_payment_method' => $_POST['insurance_company_payment_method'], 
            'insurance_company_receipt_amount' => $_POST['insurance_company_receipt_amount'], 
            'insurance_company_payment_completed' => isset($_POST['insurance_company_payment_completed']) ? 1 : 0, 
            'insurance_company_payment_remarks' => $_POST['insurance_company_payment_remarks']
        );
        $data = $this->db->insert('customer_receipt', $tblValues);
        return $data;
    }
    
    

    function update_customer_receipt()
    {
        
        $tblValues = array(
            'customer_receipt_amount' => $_POST['customer_receipt_amount'], 
            'customer_receipt_date' => $this->mastermodel->convertdateformat($_POST['customer_receipt_date']), 
            'customer_payment_method' => $_POST['customer_payment_method'], 
            'customer_receipt_remarks' => $_POST['customer_receipt_remarks'], 
            'insurance_company_payment_date' => $this->mastermodel->convertdateformat($_POST['insurance_company_payment_date']), 
            'insurance_company_payment_method' => $_POST['insurance_company_payment_method'],  
            'insurance_company_receipt_amount' => $_POST['insurance_company_receipt_amount'], 
            'insurance_company_payment_completed' => isset($_POST['insurance_company_payment_completed']) ? 1 : 0, 
            'insurance_company_payment_remarks' => $_POST['insurance_company_payment_remarks']
        );
        $data = $this->db->where('customer_receipt_id', $_POST['customer_receipt_id']);
        $data = $this->db->update('customer_receipt', $tblValues);
        return $data;
    }
    
    function get_receipt_details($receipt_id)
    {
        $this->db->select("*,IFNULL(customer_corp_info.insured,customer_personal_ind.insured) as customer_name,customer_receipt.customer_id", FALSE);
        $this->db->from('customer_receipt');
        $this->db->join('customer_personal_ind', 'customer_personal_ind.customer_id=customer_receipt.customer_id', 'LEFT');
        $this->db->join('customer_corp_info', 'customer_corp_info.customer_id=customer_receipt.customer_id', 'LEFT');
        $this->db->join('insurance_company', 'insurance_company.id=customer_receipt.insurance_company_id', 'LEFT');
        $this->db->where('customer_receipt_id',$receipt_id);
        $Q = $this->db->get();
        $row = $Q->row();
        return $row;
    }
    
    function delete_customer_receipt($id) 
    {
        return $this->db->delete('customer_receipt', array('customer_receipt_id' => $id));
    }

    function get_policy_details($customer_id, $insurance_company_id)
    {
        $data = array();
        $qry = "SELECT
                placing_slip_premiumdetails.premium
                , placing_slip_premiumdetails.policy_fees 
                , placing_slip.id as pid
                ,'0' as eid
                , customers.id
                , placing_slip.quotation_ref
                , policyno
                , cover
                , placing_slip_premiumdetails.brokerage
                , placing_slip_premiumdetails.ispercentage
                , 0 as mode
                , IFNULL(sum(cr_allocation_amount),0) as allocated_amount
                , placing_slip.remarks as description
            FROM
                placing_slip_premiumdetails
                INNER JOIN placing_slip
                    ON (placing_slip_premiumdetails.placing_slip_id = placing_slip.id)
                LEFT JOIN policynote on
                    policynote.quotation_ref=placing_slip.quotation_ref
                INNER JOIN covers on covers.id=placing_slip.cover_id    
                INNER JOIN customers
                    ON (placing_slip.customer_id = customers.id)    
                LEFT JOIN customer_receipt_allocation
                    ON (placing_slip.id = cr_allocation_pid AND cr_allocation_type = 'issue') 
            where customers.id='$customer_id' AND placing_slip_premiumdetails.payment_method = 'insurance_company'
                AND placing_slip_premiumdetails.insurance_company_id='$insurance_company_id'";
        $qry.=" GROUP BY placing_slip.id";

        $qry.=" UNION SELECT
                endorsement.premiumchange as premium
                , endorsement.policyfeeschange as  policy_fees
                , '0' as pid
                , endorsement.id as eid
                , customers.id
                , endrefno as quotation_ref
                , endorsement.endpolicyno as policyno
                , cover
                , endorsement.brokerage
                , endorsement.ispercentage
                , endorsement.mode as mode
                , IFNULL(sum(cr_allocation_amount),0) as allocated_amount
                , endorsement.remarks as description
            FROM
                endorsement
                INNER JOIN policynote on
                    policynote.id=endorsement.policyid
                INNER JOIN placing_slip on placing_slip.quotation_ref= policynote.quotation_ref   
                INNER JOIN placing_slip_premiumdetails
                    ON (placing_slip_premiumdetails.placing_slip_id = placing_slip.id)
                INNER JOIN covers on covers.id=placing_slip.cover_id     
                INNER JOIN customers
                    ON (placing_slip.customer_id = customers.id)     
                LEFT JOIN customer_receipt_allocation
                    ON (endorsement.id = cr_allocation_pid AND cr_allocation_type = 'endorsement')
            where customers.id='$customer_id' AND endorsement.paymentoptions = 'insurance_company'
                AND placing_slip_premiumdetails.insurance_company_id='$insurance_company_id'";        
        
        $qry.=" GROUP BY endorsement.id";
        
        $res = $this->db->query($qry);

        return $res;
    }
    
    function get_receipt_allocated_amount($receipt_id)
    {
        $this->db->select("SUM(cr_allocation_amount) as allocated_amount", FALSE);
        $this->db->from('customer_receipt_allocation');
        $this->db->where('customer_receipt_id',$receipt_id);
        $Q = $this->db->get();
        $row = $Q->row();
        return $row;
    }
    
    function add_customer_receipt_allocation()
    {
        $this->db->trans_begin();
       
        for ($i = 1; $i <= $_POST['total_records']; $i++)
        {
            if ($_POST['pay_' . $i] != 0 || !empty($_POST['pay_' . $i])) {
                $pid = 0;
                if (isset($_POST['placingslip_id_' . $i])) {
                    $pid = $_POST['placingslip_id_' . $i];
                    $type = 'issue';
                } else if (isset($_POST['endorsement_id_' . $i])) {
                    $pid = $_POST['endorsement_id_' . $i];
                    $type = 'endorsement';
                }
                
                if ($pid > 0 && is_numeric($_POST['pay_' . $i])) {
                    $this->db->delete('customer_receipt_allocation', 
                        array('customer_receipt_id' => $_POST['customer_receipt_id'],
                            'cr_allocation_pid' => $pid));
                    $tblValues = array(
                        'customer_receipt_id' => $_POST['customer_receipt_id'], 
                        'cr_allocation_amount' => $_POST['pay_' . $i], 
                        'cr_allocation_pid' => $pid, 
                        'cr_allocation_type' => $type, 
                    );
                    $this->db->insert('customer_receipt_allocation', $tblValues);
                }
            }
        }
        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return 0;
        }
        else
        {
            $this->db->trans_commit();
            return 1;
        }
    }
}

?>

bypass 1.0, Devloped By El Moujahidin (the source has been moved and devloped)
Email: contact@elmoujehidin.net