<?php

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

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

    protected $crud;

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

        $this->load->config('userinfo/config');


        $this->load->library('rtgrid/rtgrid_api');
        $this->crud = new rtgrid_api();

        $this->crud->unset_action('delete');
        $this->crud->unset_action('add');
        $this->crud->unset_action('add_and_next');
        $this->crud->unset_action('save_and_back_to_list');
        $this->crud->unset_action('back_to_list');
        $this->crud->unset_action('clone');
    }

    public function render()
    {
        $id_acl_user = (int)$this->rt_user->id_user;

        if ($this->uri->get_next_segment('edit') != $id_acl_user) {
            redirect($this->config->item('admin_page') . '/mconfig/index/userinfo/change_info/edit/' . $id_acl_user);
        }

        $this->crud->set_table('acl_user');
        $this->crud->fields('photo, email, birth_date, id_lan');
        $this->crud->where('id_acl_user', $id_acl_user);

        $this->crud->required_fields('email');

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

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

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

    protected function callbacks()
    {
        $this->crud->set_image_upload(new image_upload('photo', $this->config->item('photo_path'), $this->config->item('photo_width'), $this->config->item('photo_height')));
        $this->crud->callback('email', 'rtgc_email');
        $this->crud->callback('birth_date', 'date');
        $this->crud->set_relation('id_lan', 'lan', 'name', ['lan.active' => true]);
        $this->crud->multilang(new multilang('translate_name', 'acl_user_translate', 'name'));
        $this->crud->multilang(new multilang('translate_surname', 'acl_user_translate', 'surname'));
        $this->crud->multilang(new multilang('translate_about', 'acl_user_translate', 'about', function ($name, $value){
            return (new \Rtgc_texteditor())->field($name, $value);
        }));

        return $this;
    }

    protected function display_as()
    {
        $this->crud->display_as('photo', $this->lang->line('ln_photo'));
        $this->crud->display_as('email', $this->lang->line('ln_email'));
        $this->crud->display_as('birth_date', $this->lang->line('ln_birth_date'));
        $this->crud->display_as('id_lan', $this->lang->line('Default language'));
        $this->crud->display_as('translate_name', $this->lang->line('ln_name'));
        $this->crud->display_as('translate_surname', $this->lang->line('ln_surname'));
        $this->crud->display_as('translate_about', $this->lang->line('ln_about'));

        return $this;
    }
}
