<?php

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

/**
 * Description of user_register_model
 *
 * @author Igor Ratsun
 */
class user_register_model extends RT_Model
{

    public function __construct()
    {
        // Attach observers
        $this->load->config('user/events');
        if (!empty($this->config->item('user_events_user_register_model'))) {
            foreach ($this->config->item('user_events_user_register_model') as $obs) {
                $this->attach($this->load->library($obs));
            }
        }
    }

    public function add_new($form_name)
    {
        $lib = $this->config->item('user_prepare_data');

        // Insert main data
        $ins = $this->load->library($lib['main_data'])->prepare($form_name);
        $this->db->insert('acl_user', $ins);

        $id_acl_user = $this->db->insert_id();

        if (empty($id_acl_user)) {

            return FALSE;
        }

        // insert translate
        $ins_tr = $this->load->library($lib['translate_data'])
                ->prepare($id_acl_user, $form_name);
        $this->db->insert('acl_user_translate', $ins_tr);

        $this->notify(__FUNCTION__, $id_acl_user);

        return TRUE;
    }

    public function update_current_user($form_name)
    {
        $id_user = $this->rt_user->id_user;
        $lib = $this->config->item('user_prepare_data');

        // Update main data
        $main = $this->load->library($lib['main_data'])
                ->prepare($form_name, false);
        $this->db
                ->where('id_acl_user', $id_user)
                ->update('acl_user', $main);

        // Update translate
        $trans = $this->load->library($lib['translate_data'])
                ->prepare($id_user, $form_name);
        $this->db
                ->where('id_acl_user', $id_user)
                ->update('acl_user_translate', $trans);

        $this->notify(__FUNCTION__, $id_user);
    }

    public function confirm_registration($id)
    {
        $this->db
                ->where('id_acl_user', $id)
                ->update('acl_user', array('confirmed' => TRUE, 'active' => TRUE));

        $res = ($this->db->affected_rows() > 0);

        $this->notify(__FUNCTION__, ['id' => $id, 'res' => $res]);

        return $res;
    }

}
