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

class Method_model extends My_Model {

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

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

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

    public function checkIfExist($method_title, $id = NULL)
    {
        $where = ['method_title' => $method_title];
        if($id){ $where['method_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->method_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('method.*');
        get_where($params['where']);
        get_filter_where(METHODS_SEARCHABLE_FIELDS);
        if($params['action'] != 'count'){
            get_filter_order($_REQUEST, $params['order'], METHODS_ORDERABLE_FIELDS);
            get_limit($params['limit'], $params['offset']);
        }
        $this->db->from($this->method_table . ' AS method');
        $query = $this->db->get();
        return get_data($params, $query);
    }

    public function addNew($postdata)
    {
        $row = [
            'method_title' => $postdata['method_title'],
            'method_slug' => url_title($postdata['method_title'],'-',TRUE),
            'method_identifier' => strtolower(str_replace(['_',' '],['-','-'],$postdata['method_identifier'])),
            'is_active' => $postdata['is_active'],
            'created_at' => time(),
            'updated_at' => time(),
        ];
        $flag = $this->db->insert($this->method_table,$row);
        if(!$flag){
            return FALSE;
        }
        return $this->db->insert_id();
    }

    public function updateExisting($postdata, $id)
    {
        $row = [
            'method_title' => $postdata['method_title'],
            'method_slug' => url_title($postdata['method_title'],'-',TRUE),
            'method_identifier' => strtolower(str_replace(['_',' '],['-','-'],$postdata['method_identifier'])),
            'is_active' => $postdata['is_active'],
            'updated_at' => time(),
        ];
        $this->db->where('method_id',$id);
        $flag = $this->db->update($this->method_table,$row);
        if(!$flag){
            return FALSE;
        }
        return $this->db->affected_rows();
    }
}