<?php

use Phalcon\Db\Column;
use Phalcon\Db\Index;
use Phalcon\Db\Reference;
use Phalcon\Mvc\Model\Migration;

/**
 * Class RolesMigration_211
 */
class RolesScopesMigration_123 extends Migration
{
    /**
     * Define the table structure
     *
     * @return void
     */
    public function morph()
    {
        $this->morphTable('roles_scopes', [
            'columns' => [
                new Column(
                    'id',
                    [
                        'type' => Column::TYPE_INTEGER,
                        'notNull' => true,
                        'autoIncrement' => true,
                        'primary' => true
                    ]
                ),
                new Column(
                    'role_id',
                    [
                        'type' => Column::TYPE_INTEGER,
                        'notNull' => true
                    ]
                ),
                new Column(
                    'scope_id',
                    [
                        'type' => Column::TYPE_INTEGER,
                        'notNull' => true
                    ]
                ),
                new Column(
                    'created_at',
                    [
                        'type' => Column::TYPE_TIMESTAMP,
                    ]
                ),
                new Column(
                    'updated_at',
                    [
                        'type' => Column::TYPE_TIMESTAMP,
                    ]
                ),
                new Column(
                    'deleted_at',
                    [
                        'type' => Column::TYPE_TIMESTAMP,
                    ]
                )
            ],
            'indexes' => [
                new Index(
                    'roles_scopes_unique',
                    [
                        'role_id',
                        'scope_id'
                    ],
                    'UNIQUE'
                )
            ]
        ]);
    }

    /**
     * Run the migrations
     *
     * @return void
     */
    public function up()
    {
    }

    /**
     * Reverse the migrations
     *
     * @return void
     */
    public function down()
    {
        self::$connection->execute('DROP TABLE roles_scopes');
    }


    /**
     * This method is called after the table was created
     *
     * @return void
     */
    public function afterCreateTable()
    {
        $this->batchInsert('roles_scopes', [
            'role_id',
            'scope_id'
        ]);

        self::$connection->execute("SELECT setval('roles_scopes_id_seq', (SELECT MAX(id) FROM roles_scopes));");

    }
}
