<?php

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

/**
 * CRUD model
 * 
 * @author CIEXT skeleton
 */
class Crud_review extends \Ciext\Model\AbstractEventModel
{

    protected $crud;

    public function __construct()
    {
        parent::__construct();
        $this->load->library('rtgrid/rtgrid_api');
        $this->crud = new rtgrid_api();
        
        // Access check
        if (!$this->rt_user->isAllowed('review', 'view_review')) {
            $this->admin_lib->show_denied();
        }
        if (!$this->rt_user->isAllowed('review', 'edit_review')) {
            $this->crud->unset_action('edit');
            $this->crud->unset_action('delete');
            $this->crud->unset_action('add');
        }
    }

    public function render()
    {
        $this->crud->set_table('review');
        $this->crud->columns('author, text, view_order, active');
        $this->crud->fields('author, text, view_order, active');
        
        $this->crud->required_fields('author', 'text');

        $this->callbacks()->display_as()->observers();

        // Notify
        $this->notify(__FUNCTION__, ['crud' => $this->crud]);
        
        return $this->crud->render();
    }

    protected function callbacks()
    {
        $this->crud->callback('author', 'rtgc_edit_link');
        $this->crud->callback('text', 'rtgc_textarea');
        $this->crud->callback('view_order', 'rtgc_view_order', ['crud' => $this->crud]);
        $this->crud->callback('active', 'rtgc_active');

        return $this;
    }

    protected function display_as()
    {
        $this->crud->display_as('author', $this->lang->line('Author'));
        $this->crud->display_as('text', $this->lang->line('Text'));
        $this->crud->display_as('view_order', $this->lang->line('View order'));
        $this->crud->display_as('active', $this->lang->line('Active'));

        return $this;
    }
    
    protected function observers()
    {
        $this->load->helper('rtgrid/rtgrid_obs');
        $action = 'edit_review';
        $moreBtn = ' <a href="{link}">>>></a>';

        $this->crud->attach(make_rtgrid_add_obs('review', $action, $this->lang->line('Review was added') . $moreBtn));
        $this->crud->attach(make_rtgrid_edit_obs('review', $action, $this->lang->line('Review was edited') . $moreBtn));
        $this->crud->attach(make_rtgrid_delete_obs('review', $action, $this->lang->line('Review was deleted')));

        return $this;
    }

}
