<?php
class AccountModel extends CI_Model
{
    function __construct() {
        parent::__construct();
        $this->load->database();
    }

    public function add_account($data){
        //$this->db->insert('ACCOUNTHEADS',$data);
        $this->db->insert('ACCOUNTS',$data);
        return true;
    }

    public function update_account($id, $data){
        $this->db->where(array('id'=>$id));
        $this->db->update('ACCOUNTS', $data);
        return true;
    }
    public function get_account($id){
        $this->db->where('id', $id);
        $query = $this->db->get('ACCOUNTS');
        return $query->result();
    }

    public function delete_accounts($ids){
        $this->db->where_in('id', $ids);
        $this->db->delete('ACCOUNTS');
        return true;
    }

    public function update_balance($id='', $amount=''){
        $this->db->set('AVAILABLE_BALANCE', 'AVAILABLE_BALANCE+'.$amount, FALSE);
        $this->db->where('ID', $id);
        $this->db->update('ACCOUNTS');
    }
    
    function all_accounts_count(){   
        $query = $this->db->get('ACCOUNTS');
        return $query->num_rows();  
    }

    function all_accounts(){   
        $this->db->select('*');
        $this->db->from('ACCOUNTS');
        $this->db->order_by("ACCOUNT_NAME", "asc");
        $query = $this->db->get();
        if($query->num_rows()>0){
            return $query->result(); 
        } else {
            return null;
        }
    }
   
    function accounts_search($limit,$start,$search,$col,$dir){
        $query = $this->db->like('account_name',$search)->or_like('account_number',$search)->limit($limit,$start)->order_by($col,$dir)->get('ACCOUNTS');
        if($query->num_rows()>0){
            return $query->result();  
        } else {
            return null;
        }
    }

    function accounts_search_count($search){
        $query = $this->db->like('account_name',$search)->or_like('account_number',$search)->get('ACCOUNTS');
        return $query->num_rows();
    } 

    function dropdown_acounts(){
        $this->db->select('*');
        $this->db->from('ACCOUNTS');
        $query = $this->db->get();
        if($query->num_rows()>0){
            return $query->result(); 
        }else{
            return null;
        }
    }

    function initial_balance($ownerid, $account_id){
        $sql = 'select initial_balance FROM ACCOUNTS where ID="'.$account_id.'"';
        $query = $this->db->query($sql);
        return $query->row()->initial_balance;
    }
    
    function searchdatebalanceaccount($fromdate='',$accountid='') {
        $sql = 'SELECT SUM(AMOUNT) AS CURBALANCE FROM TRANSACTIONS 
WHERE ACCOUNT_ID="'.$accountid.'" AND TRANSACTION_DATE<"'.date("Y-m-d", strtotime($fromdate)).'" AND STATUS=1';
        $query = $this->db->query($sql);
        return $query->row()->CURBALANCE;
    }
}