<?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
    {
        // Homework / assignments / notes posted by teachers to a class.
        Schema::create('learning_materials', function (Blueprint $table) {
            $table->id();
            $table->branchColumn();
            $table->foreignId('class_id')->constrained('classes')->cascadeOnDelete();
            $table->foreignId('section_id')->nullable()->constrained('sections')->nullOnDelete();
            $table->foreignId('subject_id')->nullable()->constrained('subjects')->nullOnDelete();
            $table->enum('type', ['homework', 'assignment', 'notes'])->default('homework');
            $table->string('title');
            $table->text('description')->nullable();
            $table->string('attachment')->nullable();
            $table->date('due_date')->nullable();
            $table->boolean('is_published')->default(true)->index();
            $table->foreignId('posted_by')->nullable()->constrained('users')->nullOnDelete();
            $table->auditColumns();
            $table->timestamps();
            $table->softDeletes();

            $table->index(['class_id', 'type']);
        });

        // Student submissions against an assignment.
        Schema::create('assignment_submissions', function (Blueprint $table) {
            $table->id();
            $table->branchColumn();
            $table->foreignId('learning_material_id')->constrained('learning_materials')->cascadeOnDelete();
            $table->foreignId('student_id')->constrained('students')->cascadeOnDelete();
            $table->text('note')->nullable();
            $table->string('attachment')->nullable();
            $table->enum('status', ['submitted', 'graded', 'returned'])->default('submitted');
            $table->decimal('marks', 6, 2)->nullable();
            $table->string('feedback')->nullable();
            $table->timestamp('submitted_at')->nullable();
            $table->foreignId('graded_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();

            $table->unique(['learning_material_id', 'student_id'], 'submission_unique');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('assignment_submissions');
        Schema::dropIfExists('learning_materials');
    }
};
