<?php

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

/**
 * Description of rtgrid_video_api
 *
 * @author Igor Ratsun
 */
class Rtgrid_video_api
{

    protected $ci = null;
    protected $config = array();

    public function __construct($config = array())
    {
        $this->ci = & get_instance();
        $this->config = $config;

        if (empty($this->config['table'])) {
            show_error('Please, set table');
        }
        if (empty($this->config['parent_field'])) {
            show_error('Please, set parent_field');
        }
        
        // Load language file
        $this->ci->load->library('gettext_language');
        $this->ci->gettext_language->load(__DIR__ . '/../language/' . $this->ci->config->item('language') . '.po');
    }
    
    public function attach_crud(rtgrid_api $crud, $tab_title = '')
    {
        if (!$crud->is_grid()) {
            $tab_title = !empty($tab_title) ? $tab_title : $this->ci->lang->line('Videos');
            $crud->add_tab($tab_title, $this->render());
            $crud->callback_after_edit(array($this, 'callback_after_edit'));
        } else {
            $crud->before_action('delete', array($this, 'callback_before_delete'));
        }
    }

    public function install()
    {
        $file = dirname(__DIR__) . '/data/install.sql';
        if (!file_exists($file)) {
            show_error('File ' . $file . ' not found');
        }
        $query = str_replace(array('TABLE_NAME', 'PARENT_FIELD'), array($this->config['table'], $this->config['parent_field']), file_get_contents($file));

        $this->ci->db->query($query);

        return TRUE;
    }

    public function render($id_parent = 0)
    {
        if (empty($id_parent)) {
            $id_parent = (int) $this->ci->uri->get_next_segment('edit');
        } else {
            $id_parent = (int) $id_parent;
        }
        
        if ($this->ci->input->post('getItems')) {

            return $this->renderJSON($this->getItems($id_parent));
        } elseif ($this->ci->input->post('saveItem')) {

            return $this->renderJSON($this->saveItem($id_parent, $this->ci->input->post('saveItem')));
        } elseif ($this->ci->input->post('removeItem')) {

            return $this->renderJSON($this->removeItem($id_parent, $this->ci->input->post('removeItem')));
        }

        $content = array();

        return $this->ci->parser->parse('rtgrid_video/template', $content, TRUE);
    }

    public function renderJSON($data = '')
    {
        header('Content-Type: application/json');
        die($data);
    }

    public function getItems($id_parent = 0)
    {
        $data = $this->ci->db->
                        select('link')->
                        where($this->config['parent_field'], $id_parent)->
                        get($this->config['table'])->result_array();

        if (!empty($data)) {
            $data = array_column($data, 'link');
        }

        return json_encode($data);
    }

    public function saveItem($id_parent = 0, $link = '')
    {
        $this->ci->db->insert($this->config['table'], array(
            $this->config['parent_field'] => $id_parent,
            'link' => $link,
        ));

        $data = array(
            'success' => ($this->ci->db->insert_id() > 0),
        );

        return json_encode($data);
    }

    public function removeItem($id_parent = 0, $link = '')
    {
        $this->ci->db
                ->where(array(
                    $this->config['parent_field'] => $id_parent,
                    'link' => $link,
                ))
                ->delete($this->config['table']);

        $data = [
            'success' => ($this->ci->db->affected_rows() > 0),
        ];

        return json_encode($data);
    }

    public function callback_after_edit($post_data, $pkey)
    {
        $this->ci->db
                ->where($this->config['parent_field'], 0)
                ->update($this->config['table'], array(
                    $this->config['parent_field'] => $pkey
        ));

        return TRUE;
    }
    
    public function callback_before_delete($items)
    {
        $this->ci->db
                ->where_in($this->config['parent_field'], $items)
                ->delete($this->config['table']);
        
        return TRUE;
    }

}
