<?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_book_purchases table — records course book
     * purchases by both registered users and guests (identified by email).
     * Not tied to an enrollment; a purchase grants a time-limited signed
     * download URL for the course PDF book.
     */
    public function up(): void
    {
        Schema::create('self_paced_book_purchases', function (Blueprint $table) {
            $table->id();

            $table->unsignedBigInteger('course_id');
            $table->unsignedBigInteger('user_id')->nullable()->comment('NULL for guest purchases');

            $table->string('email', 255);
            $table->string('payment_reference', 100);
            $table->enum('payment_method', ['paystack', 'cash'])->default('paystack');
            $table->decimal('amount_paid', 12, 2);
            $table->string('currency', 10)->default('KES');

            $table->unsignedBigInteger('proof_id')->nullable();

            $table->string('download_token', 64)->nullable()
                ->comment('Signed URL token (derived, not stored)');
            $table->timestamp('downloaded_at')->nullable();
            $table->timestamp('payment_date')->nullable();

            $table->timestamps();

            // Foreign keys
            $table->foreign('course_id', 'fk_sp_book_course')
                ->references('id')->on('self_paced_courses')
                ->cascadeOnDelete();

            $table->foreign('user_id', 'fk_sp_book_user')
                ->references('id')->on('users')
                ->nullOnDelete();

            $table->foreign('proof_id', 'fk_sp_book_proof')
                ->references('id')->on('self_paced_payment_proofs')
                ->nullOnDelete();

            // Indexes
            $table->index('course_id', 'idx_sp_book_course');
            $table->index('email', 'idx_sp_book_email');
            $table->index('payment_reference', 'idx_sp_book_reference');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('self_paced_book_purchases');
    }
};
