<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home_Model extends CI_Model {
    public function __construct() {
        parent::__construct();
    }
    
    function get($tbl_name, $args ) {
        $args = is_array($args) ? $args : array('where' => array());
        $where = isset($args['where']) ? $args['where'] : array();
        if ( ! is_array($where)) $where = array();
        
        if( empty( $where['status'] ) ) :
            $where['status'] = 1;
        endif;
        
        if( !empty( $args['order_by'] ) ) :
            $this->db->order_by( $args['order_by'] );
        endif;
        
        $q = $this->db->get_where( $tbl_name, $where );
        return $q->result_array();
    }
    
    function ajax() {
        $post   = $this->input->post();
        $cat_id = $post['catID'];
        $general = $this->get_general_setting();
        
        
        $tbl_name = TBL_CATEGORY;
        $join_id = 'bari_cat_id';
        
        $slct = 'SUM(bari.bari_qty) AS total_qty,  SUM(bari.bari_price) AS total_amt';
        $where = array(
            'self.status' => 1,
        );
        
        if( empty( $cat_id ) && $general->is_category == 1) :
            // Get all
            $slct .= ', self.id AS id, self.category_name AS name';
            $this->db->order_by('self.category_order');
            //$this->db->order_by('total_qty DESC');
            $this->db->group_by('bari.bari_cat_id');
        else :
            // Get By Particular Category
            
            $tbl_name = TBL_ITEM;
            $join_id = 'bari_item_id';
            if($general->is_category == 1) {
                $where['self.category_id'] = $cat_id;
            }
            $slct .= ', self.id AS id, self.name AS name';
            $this->db->order_by('self.order_sequence');
            $this->db->group_by('bari.bari_item_id');
        endif;
        
        $date = 'CURDATE()';
        if( !empty( $post['date'] ) ) :
            $e = explode("/", $post['date']);
            $date = 'DATE("'. $e[2] .'-'. $e[1] .'-'. $e[0] .'")';
        endif;
        
        $this->db->select( $slct );
        $this->db->join( TBL_BARI . ' AS bari', 'self.id = bari.'. $join_id .' AND bari.status = 1 AND DATE(bari.created_on) = '.$date );
        $q = $this->db->get_where( $tbl_name . ' AS self', $where );
        #echo "Q: "; error_log($this->db->last_query());
        $results = $q->result_array();
        
        //echo "<pre>"; print_r( $results ); die;
        
        return $results;
        
    }
    
    public function get_general_setting() {
        return $this->db->get(TBL_SETTINGS_GENERAL)->row();
    }
}
?>