<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * Creates the self_paced_certificates table — issued certificates of completion.
     * Each certificate has a unique certificate_number and verification_code used
     * for the public Certificate_Verification page and QR code.
     */
    public function up(): void
    {
        Schema::create('self_paced_certificates', function (Blueprint $table) {
            $table->id();

            $table->foreignId('user_id')
                ->constrained('users')
                ->cascadeOnDelete();
            $table->foreignId('course_id')
                ->constrained('self_paced_courses')
                ->cascadeOnDelete();
            $table->foreignId('enrollment_id')
                ->constrained('self_paced_enrollments')
                ->cascadeOnDelete();
            $table->foreignId('result_id')
                ->constrained('self_paced_exam_results')
                ->cascadeOnDelete();

            // Unique identifiers
            $table->string('certificate_number', 100)->unique();
            $table->string('verification_code', 100)->unique();

            $table->date('issue_date');

            // Revocation
            $table->boolean('is_revoked')->default(false);
            $table->timestamp('revoked_at')->nullable();
            $table->foreignId('revoked_by')->nullable()->constrained('users')->nullOnDelete();
            $table->text('revocation_reason')->nullable();

            // PDF storage
            $table->string('pdf_path')->nullable();

            // Verification tracking
            $table->unsignedInteger('verification_count')->default(0);
            $table->timestamp('last_verified_at')->nullable();

            // Audit
            $table->foreignId('generated_by')
                ->nullable()
                ->constrained('users')
                ->nullOnDelete();

            $table->timestamps();

            $table->index('user_id');
            $table->index('course_id');
            $table->index('enrollment_id');
            $table->index('certificate_number');
            $table->index('verification_code');
            $table->index('is_revoked');
        });
    }

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