<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Category_model extends My_Model {

    public function __construct()
    {
        parent::__construct();
    }

    public function getRow($id)
    {
        return $this->getRecords(['where'=>['category_id'=>$id],'action'=>'row']);
    }

    public function getRowByName($category_label)
    {
        return $this->getRecords(['where' => ['category_label' => $category_label], 'action' => 'row']);
    }

    public function checkIfExist($category_label, $id = NULL)
    {
        $where = ['category_label' => $category_label];
        if($id){ $where['category_id != '] = $id; }
        return $this->getRecords(['where' => $where, 'action' => 'row']);
    }

    public function getRecords($params = [])
    {
        $params = init_model_params($params);
        get_where($params['where']);
        $this->db->from($this->category_table);
        if($params['action'] != 'count') get_order($params['order']);
        get_limit($params['limit'],$params['offset']);
        $query = $this->db->get();
        return get_data($params, $query);
    }

    public function getDatatableList($params)
    {
        $params = init_model_params($params);
        $this->db->select('cat.*');
        get_where($params['where']);
        get_filter_where(CATEGORIES_SEARCHABLE_FIELDS);
        if($params['action'] != 'count'){
            get_filter_order($_REQUEST, $params['order'], CATEGORIES_ORDERABLE_FIELDS);
            get_limit($params['limit'], $params['offset']);
        }
        $this->db->from($this->category_table . ' AS cat');
        $query = $this->db->get();
        return get_data($params, $query);
    }

    public function addNew($postdata)
    {
        $row = [
            'category_label' => $postdata['category_label'],
            'category_slug' => url_title($postdata['category_label'],'-',TRUE),
            'is_active' => $postdata['is_active'],
            'created_at' => time(),
            'updated_at' => time(),
        ];
        $flag = $this->db->insert($this->category_table,$row);
        if(!$flag){
            return FALSE;
        }
        return $this->db->insert_id();
    }

    public function updateExisting($postdata, $id)
    {
        $row = [
            'category_label' => $postdata['category_label'],
            'category_slug' => url_title($postdata['category_label'],'-',TRUE),
            'is_active' => $postdata['is_active'],
            'updated_at' => time(),
        ];
        $this->db->where('category_id',$id);
        $flag = $this->db->update($this->category_table,$row);
        if(!$flag){
            return FALSE;
        }
        return $this->db->affected_rows();
    }
}