<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        // apagar tabelas antigas
        Schema::dropIfExists('model_has_permissions');
        Schema::dropIfExists('model_has_roles');
        Schema::dropIfExists('role_has_permissions');
        Schema::dropIfExists('permissions');
        Schema::dropIfExists('roles');

        Schema::dropIfExists('alunos');
        Schema::dropIfExists('turmas');
        Schema::dropIfExists('users');
        Schema::dropIfExists('escolas');

        // escolas
        Schema::create('escolas', function (Blueprint $table) {

            $table->id();

            $table->string('cnpj', 18)->unique();

            $table->string('nome');

            $table->string('endereco')->nullable();

            $table->timestamps();

        });

        // users
        Schema::create('users', function (Blueprint $table) {

            $table->id();

            $table->foreignId('id_escola')
                ->nullable()
                ->constrained('escolas')
                ->nullOnDelete();

            $table->string('name');

            $table->string('email')->unique();

            $table->string('password');

            $table->boolean('is_super_admin')->default(false);

            $table->rememberToken();

            $table->timestamps();

        });

        // turmas
        Schema::create('turmas', function (Blueprint $table) {

            $table->id();

            $table->foreignId('id_escola')
                ->constrained('escolas')
                ->cascadeOnDelete();

            $table->string('nome');

            $table->text('descricao')->nullable();

            $table->timestamps();

        });

        // alunos
        Schema::create('alunos', function (Blueprint $table) {

            $table->id();

            $table->foreignId('id_escola')
                ->constrained('escolas')
                ->cascadeOnDelete();

            $table->foreignId('id_turma')
                ->constrained('turmas')
                ->cascadeOnDelete();

            $table->string('nome');

            $table->string('cpf', 14)->nullable();

            $table->date('data_nascimento')->nullable();

            $table->date('data_inscricao')->nullable();

            $table->date('data_encerramento')->nullable();

            $table->string('endereco')->nullable();

            $table->timestamps();

        });

    }

    public function down(): void
    {
        Schema::dropIfExists('alunos');
        Schema::dropIfExists('turmas');
        Schema::dropIfExists('users');
        Schema::dropIfExists('escolas');
    }
};
