<?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
    {
        Schema::create('transport_routes', function (Blueprint $table) {
            $table->id();
            $table->branchColumn();
            $table->string('name');
            $table->string('code', 30)->nullable();
            $table->decimal('fare', 10, 2)->default(0);
            $table->boolean('is_active')->default(true)->index();
            $table->auditColumns();
            $table->timestamps();
            $table->softDeletes();
        });

        Schema::create('transport_stops', function (Blueprint $table) {
            $table->id();
            $table->branchColumn();
            $table->foreignId('transport_route_id')->constrained('transport_routes')->cascadeOnDelete();
            $table->string('name');
            $table->decimal('fare', 10, 2)->default(0);
            $table->time('pickup_time')->nullable();
            $table->timestamps();
        });

        Schema::create('vehicles', function (Blueprint $table) {
            $table->id();
            $table->branchColumn();
            $table->string('registration_no', 40);
            $table->string('model')->nullable();
            $table->unsignedSmallInteger('capacity')->nullable();
            $table->string('driver_name')->nullable();
            $table->string('driver_phone', 30)->nullable();
            $table->string('driver_license', 50)->nullable();
            $table->foreignId('transport_route_id')->nullable()->constrained('transport_routes')->nullOnDelete();
            $table->boolean('is_active')->default(true)->index();
            $table->auditColumns();
            $table->timestamps();
            $table->softDeletes();

            $table->unique(['branch_id', 'registration_no']);
        });

        // Student transport assignment.
        Schema::table('students', function (Blueprint $table) {
            $table->foreignId('transport_route_id')->nullable()->after('section_id')->constrained('transport_routes')->nullOnDelete();
            $table->foreignId('transport_stop_id')->nullable()->after('transport_route_id')->constrained('transport_stops')->nullOnDelete();
        });
    }

    public function down(): void
    {
        Schema::table('students', function (Blueprint $table) {
            $table->dropForeign(['transport_route_id']);
            $table->dropForeign(['transport_stop_id']);
            $table->dropColumn(['transport_route_id', 'transport_stop_id']);
        });
        Schema::dropIfExists('vehicles');
        Schema::dropIfExists('transport_stops');
        Schema::dropIfExists('transport_routes');
    }
};
