<?php
namespace Hwapx\Admin\Controller\Admin;

use HwapX\Core\Library\DB\SQL\Mapper;
use Hwapx\Admin\Controller\Admin\Admin;
use HwapX\Admin\Library\Builder\FormBuilder;
use HwapX\Admin\Library\Builder\TableBuilder;

class User extends Admin
{
    protected $form = array(
        //'title'  => '',
        'name'   => 'Usuário',
        'table'  => 'admin_users',
        'fields' => array(
            'name' => array(
                'label' => 'Nome',
                'type'  => 'text',
                'rules' => array(
                    'required'
                )
            ),
            'email'    => array(
                'label' => 'Email',
                'type'  => 'text',
                'rules' => array(
                    'required',
                    'email'
                )
            ),
            'password' => array(
                'label'  => 'Senha',
                'type'   => 'password',
                'rules'  => array(
                    'lengthMin' => 4,
                    'password'
                ),
                'filter' => array(
                    'md5'
                )
            ),
            'group_id' => array(
                'label'   => 'Grupo',
                'type'    => 'dropdown',
                'options' => array(
                    '' => '-- Selecione --'
                ),
                'rules'   => array(
                    'required'
                )
            ),
            'active'   => array(
                'label'   => 'Ativo',
                'type'    => 'radio',
                'options' => array(
                    '1' => 'Sim',
                    '0' => 'Não'
                ),
                'default' => '1',
                'rules'   => array(
                    'required'
                )
            ),
            'photo'    => array(
                'label' => 'Foto',
                'type'  => 'image',
                'rules' => array(
                    'file'
                )
            ),/*,
        'confirm'  => array(
        'label' => 'Confirme a senha',
        'type'  => 'password',
        'rules' => array(
        'equals' => 'password'
        )
        )*/
        )
    );

    protected $logger = null;

    protected $table = array(
        'title'      => 'Lista de Usuários',
        'name'       => 'Usuários',
        'cols'       => array(
            'id'       => '#',
            'name'     => 'Nome',
            'email'    => 'Email',
            'group_s'  => 'Grupo',
            'active_s' => 'Ativo'
        ),
        'actions'    => array(
            array(
                'route'       => 'admin_user_create',
                'description' => 'Novo',
                'class'       => 'btn-primary',
                'role'        => 'hwapx.admin.user_create'
            )
        ),
        'rowactions' => array(
            array(
                'route'       => 'admin_user_edit',
                'description' => 'Alterar',
                'class'       => 'btn-primary',
                'default'     => true,
                'role'        => 'hwapx.admin.user_edit'
            ),
            array(
                'route'       => 'admin_user_reset',
                'description' => 'Enviar senha',
                'class'       => 'btn-default',
                'default'     => false,
                'confirm'     => true,
                'role'        => 'hwapx.admin.user_edit'
            ),
            array(
                'route'       => 'admin_user_remove',
                'description' => 'Remover',
                'class'       => 'btn-danger',
                'confirm'     => true,
                'role'        => 'hwapx.admin.user_remove'
            )
        ),
        'route'  => 'admin_users',
        'legend' => array(
            'default' => 'Ativo',
            'warning' => 'Sem senha definida',
            'danger'  => 'Inativo',
        ),
    );

    protected $validator = null;
    protected $mapper = null;

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


        $db     = $f3->get('db');
        $this->mapper = new \DB\SQL\Mapper($db, 'hwapx_user');

        $mapper = new Mapper($db, 'hwapx_group');

        if($this->module->hasRole('hwapx.admin.user_edit')) {
            foreach ($mapper->find($where) as $row) {
                $this->form['fields']['group_id']['options'][$row->id] = $row->description;
            }
        }

        $this->form['fields']['email']['rules']['notIn']    = $this->getFieldValues('email', $this->mapper, array('NOT id <=> ?', $f3->get('PARAMS.id')));

        $this->logger = new \Log(date('Y-m-d').'_user.log');
    }

    public function alter($f3)
    {
        if ($f3->get('PARAMS.id') == 1 && $f3->get('SESSION.admin.id') != 1) {
            $f3->error(403);
        }
        
        if ($f3->get('PARAMS.id') != $f3->get('SESSION.admin.id')) {
            $this->module->checkRole('hwapx.admin.user_edit');
        }

        $this->mapper->load(array('id = ?', $f3->get('PARAMS.id')));

        if(!in_array($this->mapper->group_id , array_keys($this->form['fields']['group_id']['options']))) {
            unset($this->form['fields']['group_id']);
        }

        if($this->mapper->password === '*') {
            flash('warning', 'Usuário não possui senha definida.');
        }

        echo FormBuilder::instance($this->mapper, $this->form, $this->logger)
                        ->afterSave(function($mapper) use($f3) {
                            if(!$mapper->password) {
                                $mapper->reset_token  = md5($mapper->email . time() . 'set' . rand() . $f3->get('app.password.salt'));
                                $mapper->reset_expire = date('Y-m-d H:i:s', strtotime('+1 day'));
                                $mapper->save();

                                $sent = SMTPMessage('set_password', array('usuario' => $mapper->cast()), $mapper->email);
                            }
                        })
                        ->handle();
    }

    public function create($f3)
    {
        $this->module->checkRole('hwapx.admin.user_create');

        echo FormBuilder::instance($this->mapper, $this->form, $this->logger)
                        ->afterSave(function($mapper) use($f3) {
                            if(!$mapper->password) {
                                $mapper->reset_token  = md5($mapper->email . time() . 'set' . rand() . $f3->get('app.password.salt'));
                                $mapper->reset_expire = date('Y-m-d H:i:s', strtotime('+1 day'));
                                $mapper->save();

                                $sent = SMTPMessage('set_password', array('usuario' => $mapper->cast()), $mapper->email);
                            }
                        })
                        ->handle();
    }

    public function reset($f3) {
        $this->mapper->load(array('id = ?', $f3->get('PARAMS.id')));

        if($this->mapper->dry()) {
            $f3->error(404);
        }

        $this->mapper->reset_token  = md5($this->mapper->email . time() . 'set' . rand() . $f3->get('app.password.salt'));
        $this->mapper->reset_expire = date('Y-m-d H:i:s', strtotime('+1 day'));
        $this->mapper->save();

        $sent = SMTPMessage('reset_password', array('usuario' => $this->mapper->cast()), $this->mapper->email);

        if($sent) {
            flash('success', "Um email com as instruções para redefinição de senha foi enviado para {$this->mapper->email}.");
        } else {
            flash('error', 'Ocorreu um erro ao enviar o email, tente novamente.');
        }

        $f3->reroute('@admin_users');
    }

    public function getFieldValues($fieldname, $mapper, $qry = array())
    {
        $result = array();

        foreach ($mapper->find($qry) as $u) {
            $result[] = $u->{$fieldname};
        }

        return $result;
    }

    public function index($f3)
    {
        $this->module->checkRole('hwapx.admin.user_list');

        $this->mapper->active_s = "CASE active WHEN 1 THEN 'SIM' ELSE 'NÃO' END";
        $this->mapper->group_s  = "SELECT hwapx_group.description FROM hwapx_group WHERE hwapx_group.id = hwapx_user.group_id";

        $this->table['rowcallback'] = function($mapper) use($f3) {
            $data = array();

            if(!$mapper->active) {
                $data['class'] = 'danger';
            } else if ($mapper->password === '*') {
                $data['class'] = 'warning';
            }

            return $data;
        };

        echo TableBuilder::instance($this->mapper, $this->table)->render();
    }

    public function remove($f3)
    {
        $this->module->checkRole('hwapx.admin.user_remove');

        if ($f3->get('PARAMS.id') == 1) {
            flash('error', 'O usuário '.$this->mapper->name.' não pode ser excluido.');
        } else if($f3->get('PARAMS.id') == $f3->get('SESSION.admin.id')) {
            flash('error', 'Você não pode excluir seu próprio usuário.');
        } else {
            //FormBuilder::instance($this->mapper, $this->form, $this->logger)->delete();
            echo FormBuilder::instance($this->mapper, $this->form)->delete();
        }

        $f3->reroute('@admin_users');
    }
}
