<?php
namespace Hwapx\Redirect;

use DB\SQL\Schema;
use DB\SQL\Mapper;
use Hwapx\Core\Library\Modulebase;

class Module extends Modulebase
{
    public static $roles = array(
        'redirect_create' => 'Criar Redirecionamento',
        'redirect_edit'   => 'Editar Redirecionamento',
        'redirect_remove' => 'Remover Redirecionamento',
        'redirect_list'   => 'Listar Redirecionamentos'
    );

    public static $sidebar = array(
        'system' => array(
            array(
                'icon' => 'refresh',
                'label' => 'Redirecionamentos',
                'route' => 'admin_redirects',
                'role' => 'redirect_list'
            )
        )
    );

    protected $f3 = null;

    /**
     * @param $f3
     */
    public function __construct($f3)
    {
        $this->f3 = $f3;
    }

    public function boot($f3)
    {
        $db  = $f3->get('db');
        $schema = new Schema($db);

        if (!in_array('hwapx_redirect', $schema->getTables())) {
            return;
        }

        $mapper = new Mapper($db, 'hwapx_redirect');
        $redirects = $mapper->find(array("active = 1"));

        foreach ($redirects as $redirect) {
            $f3->redirect($redirect->method . ' ' . $redirect->url_from, $redirect->url_to, $redirect->permanent);
        }
    }

    public function install()
    {
        $db     = $this->f3->get('db');
        $schema = new Schema($db);

        $table = $schema->createTable('hwapx_redirect');
        $table->addColumn('description')->type_varchar(32)->nullable(false);
        $table->addColumn('url_from')->type_varchar()->nullable(false);
        $table->addColumn('url_to')->type_varchar()->nullable(false);
        $table->addColumn('active')->type_bool()->nullable(false);
        $table->addColumn('permanent')->type_bool()->nullable(false);
        $table->addColumn('method')->type_varchar()->nullable(false);
        $table->addColumn('created_on')->type_datetime(true)->nullable(false);
        $table->addColumn('updated_on')->type_datetime()->nullable(true);
        $table->build();
    }

    public function uninstall()
    {
        $db     = $this->f3->get('db');
        $schema = new Schema($db);

        $schema->dropTable('hwapx_redirect');
    }
}
