<?php

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

/**
 * Description of product_tmodel
 *
 * @author CIEXT skeleton
 */
class Product_tmodel extends \Ciext\Model\AbstractTableModel
{

    protected $table = 'product';
    protected $pkey = 'id_product';
    protected $id_lan;

    /**
     * cache
     */
    protected $cache_product_icons = [];

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

        $this->id_lan = $this->load->library('db_lang_lib')->get_current_lang_id();
    }

    public function fetch($id = 0)
    {
        $res = $this->where()
                ->where($this->get_predicates())
                ->select($this->select, $this->select_escape)
                ->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->where()
                ->select('t.*, p.alias, pt.name, pt.short_desc, pt.description')
                ->get($this->table . ' t')
                ->result_array();

        // Notify all observers
        $this->notify(__FUNCTION__, ['ids' => array_column($res, $this->pkey)]);

        return $this->prepare($res);
    }

    /**
     * Get all group products
     * @param integer $id_product_group
     * @return type
     */
    public function fetch_all_by_group_id($id_product_group = 0)
    {
        $this->db->where('t.id_product_group', (int) $id_product_group);

        return $this->fetch_all();
    }

    /**
     * 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->where()->count_all_results($this->table . ' t');

        return $res;
    }

    /**
     * Fetch product photos
     * @param int $id_product
     * @return array
     */
    public function fetch_photos($id_product = 0)
    {
        $photos = $this->load->library('alphagallery/alphagallery_api', [
                    'main_table'  => 'product_photo',
                    'foreign_key' => 'id_product'
                ])->get_photos((int) $id_product);

        return $photos;
    }

    /**
     * Fetch product videos
     * @param int $id_product
     * @return array
     */
    public function fetch_videos($id_product = 0)
    {
        $videos = json_decode($this->load->library('rtgrid_video/rtgrid_video_api', array(
                    'table'        => 'product_video',
                    'parent_field' => 'id_product'
                ))->getItems((int) $id_product), true);

        return $videos;
    }

    /**
     * Fetch product icons
     * @param integer $id_product
     * @param array $available_ids
     * @return array
     */
    public function fetch_icons($id_product = 0, $available_ids = [])
    {
        if (empty($this->cache_product_icons[$id_product])) {
            if (!empty($available_ids)) {
                $this->db->where_in('pil.id_product', array_map('intval', $available_ids));
            }
            $q = $this->db->
                            select('i.icon, pil.id_product')->
                            join('product_icon i', 'pil.id_product_icon=i.id_product_icon', 'left')->
                            get('product_icon_linker pil')->result_array();
            foreach ($q as $icon) {
                $this->cache_product_icons[$icon['id_product']][] = $icon['icon'];
                $this->cache_product_icons[$icon['id_product']] = array_unique($this->cache_product_icons[$icon['id_product']]);
            }
        }

        return isset($this->cache_product_icons[$id_product]) ? $this->cache_product_icons[$id_product] : [];
    }

    protected function where()
    {
        $this->db->join('product_translate pt', 'pt.id_product=t.id_product AND pt.id_lan=' . $this->id_lan, 'left');

        return $this->db->join('resource_type_page p', 'p.id_resource_type_page=t.id_resource_type_page', 'left')->where('p.active', TRUE);
    }

    protected function prepare($data = [])
    {
        $this->load->model('ciext/core_model');

        foreach ($data as &$v) {
            $v['url'] = isset($v['alias']) ? $this->core_model->create_page_url($v['alias']) : '';
            $v['icons'] = $this->fetch_icons($v['id_product'], array_column($data, 'id_product'));
        }
        unset($v);

        return $data;
    }

}
