<?php
namespace services;

use models\Page;

class CreateDatabase {
    private $schema;

    public function __construct( $schema ) {
        $this->schema = $schema;
    }

    public function perform() {
        if ( !in_array( 'page', $this->schema->getTables() ) ) {
            $this->schema->createTable( 'page', [
                'page_id' => ['integer', ['not_null' => true, 'primary_key' => true, 'identity' => true]],
                'name' => ['varchar', ['length' => 100, 'not_null' => true]],
                'content' => ['clob', ['default'=> 'NULL']],
                'created_at' => ['datetime', ['not_null' => true]],
                'updated_at' => ['datetime', ['default' => 'NULL']]
            ] );

            $this->schema->addIndex( 'UX_page_name', 'page', 'name', true );

            $page = new Page();
            $page->name = 'Home';
            $page->content = file_get_contents( APP_DIR . TEMPLATES_DIR . 'home.txt' );
            if ( !$page->save() ) {
                throw new \RuntimeException( 'Error while creating page.' );
            }
        }
    }

}
