<?php

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

/**
 * Description of CLASSNAME
 *
 * @author CIEXT skeleton
 */
class CLASSNAME extends RT_Model
{

    protected $table = 'TABLE';
    protected $pkey = 'id_TABLE';

    /**
     * Fetch one record
     * @param integer $id
     * @return array
     */
    public function fetch($id = 0)
    {
        $res = $this->db
                ->where($this->get_predicates())
                ->select('t.*')
                ->where('t.' . $this->pkey, (int) $id)
                ->get($this->table . ' t')
                ->row_array();

        // Notify all observers
        $this->notify(__FUNCTION__, ['id' => $id]);

        return $res;
    }

    /**
     * Fetch all records
     * @return array
     */
    public function fetch_all()
    {
        $res = $this->db
                ->where($this->get_predicates())
                ->select('t.*')
                ->order_by('t.view_order')
                ->get($this->table . ' t')
                ->result_array();

        return $res;
    }

    /**
     * Fetch records of page
     * @param integer $page
     * @param integer $limit
     * @return array
     */
    public function fetch_page($page = 1, $limit = 1)
    {
        $offset = ($page <= 1) ? 0 : $page - 1;
        $this->db->limit($limit)->offset($offset * $limit);

        return $this->fetch_all();
    }

    /**
     * Records count
     * @return integer
     */
    public function count()
    {
        $res = $this->db
                ->where($this->get_predicates())
                ->count_all_results($this->table . ' t');

        return $res;
    }

    /**
     * Add record to table
     * @param array $data
     */
    public function add($data = [])
    {
        $this->db->insert($this->table, $data);

        $id = $this->db->insert_id();

        // Notify all observers
        $this->notify(__FUNCTION__, ['id' => $id]);

        return $id;
    }

    /**
     * Update record
     * @param int $id
     * @param array $data
     */
    public function update($id, $data = [])
    {
        $this->db
                ->where($this->get_predicates())
                ->where('t.' . $this->pkey, (int) $id)
                ->update($this->table . ' t', $data);

        $result = ($this->db->affected_rows() > 0);

        // Notify all observers
        $this->notify(__FUNCTION__, [
            'id'            => $id,
            'affected_rows' => $result,
        ]);

        return $result;
    }

    protected function get_predicates()
    {
        $predicates = [
            't.active' => true,
        ];

        return $predicates;
    }

}
