<?php

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

/**
 * Description of userinfo_admin
 *
 * @author Igor Ratsun
 */
class Userinfo_admin extends \Ciext\Controller\AbstractAuthController {

    public function __construct() {
        parent::__construct();
        $this->load->language('userinfo/base');
    }

    public function init() {

        $this->load->model('userinfo/userinfo_model');
        $user_name = $this->userinfo_model->get_user_name();
        
        $content = array(
            'user_name' => !empty($user_name) ? $user_name : $this->rt_user->get_user_data('login'),
            'link' => '/' . $this->config->item('admin_page') . '/mconfig/index/userinfo'
        );

        return $this->parser->parse('userinfo/init', array_merge($content, $this->lang->language), TRUE);
    }

    public function change_pass() {
        // Ajax
        if (!empty($_POST)) {
            $errors = array();

            // Check new pass
            $newpass = $this->input->post('newpass');
            if (empty($newpass)) {
                $errors[] = 'newpass';
            }

            // Check new newpassconf
            if ($this->input->post('newpass') !== $this->input->post('newpassconf')) {
                $errors[] = 'newpassconf';
            }

            // check old pass
            $id = $this->rt_user->get_user_id($this->rt_user->get_user_data(), $this->input->post('oldpass'));
            if (empty($id)) {
                $errors[] = 'oldpass';
            }

            if (empty($errors)) {
                $this->rt_user->change_pass($id, $newpass);
                $RS = array('success');
            } else {
                $RS = array(
                    'errors' => $errors
                );
            }

            die(json_encode($RS));
        }

        $this->load->language('userinfo/pass');
        $this->ciext->load_bootstrap();
        $this->js_css->parse_js('userinfo/js/main.js');
        $this->load->helper('form');
        $content = array(
            'form_open' => form_open(base_url() . $this->config->item('admin_page') . '/mconfig/index/userinfo/change_pass', 'id="change_form" class="form-horizontal"'),
            'form_close' => form_close()
        );

        return array(
            'content' => $this->parser->parse('userinfo/change_pass', array_merge($content, $this->lang->language), TRUE),
            'title' => $this->lang->line('title')
        );
    }

    public function change_info()
    {
        $this->load->model('userinfo/crud_userinfo');
        $this->load->language('userinfo/info');

        return ['content' => $this->crud_userinfo->render(), 'title' => $this->lang->line('title')];
    }


}