<?php

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

/**
 * CRUD model
 * 
 * @author CIEXT skeleton
 */
class crud_emailmng extends CI_Model
{

    protected $crud;

    public function __construct()
    {
        parent::__construct();
        $this->load->library('rtgrid/rtgrid_api');
        $this->crud = new rtgrid_api();

        // Acceess check
        if (!$this->rt_user->isAllowed('emailmng', 'view_emailmng')) {
            $this->admin_lib->show_denied();
        }
        if (!$this->rt_user->isAllowed('emailmng', 'edit_emailmng')) {
            $this->crud->unset_action('edit');
        }
        if(!$this->rt_user->isAllowed('emailmng', 'can_delete')){
            $this->crud->unset_action('delete');
            $this->crud->unset_action('add');
            $this->crud->readonly('code');
        }
    }

    public function render()
    {
        $this->crud->set_table('emailmng');
        $this->crud->columns('code, subject, mailtype');
        $this->crud->fields('code, copy_to, hidden_copy_to, subject, message, mailtype');
        $this->crud->unique_fields('code');
        $this->crud->required_fields('code');

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

        return $this->crud->render();
    }

    protected function callbacks()
    {
        $this->crud->callback('code', 'input');
        $this->crud->callback('copy_to', 'input');
        $this->crud->callback('hidden_copy_to', 'input');
        $this->crud->callback('subject', 'input');
        $this->crud->callback('message', 'texteditor');
        $this->crud->callback('mailtype', 'rtgc_select', $this->config->item('mailtype'));

        return $this;
    }

    protected function display_as()
    {
        $this->crud->display_as('code', $this->lang->line('Code of template'));
        $this->crud->display_as('copy_to', $this->lang->line('Send copy to'));
        $this->crud->display_as('hidden_copy_to', $this->lang->line('Send hidden copy to'));
        $this->crud->display_as('subject', $this->lang->line('Message subject'));
        $this->crud->display_as('message', $this->lang->line('Message'));
        $this->crud->display_as('mailtype', $this->lang->line('Mail type'));

        return $this;
    }

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

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

        return $this;
    }

}
