<?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('bookings', function (Blueprint $table) {
            $table->id();
            $table->string('booking_code', 14)->unique(); // e.g. BFK-AB12CD
            $table->foreignId('customer_id')->constrained('users')->cascadeOnDelete();
            $table->foreignId('partner_id')->nullable()->constrained('partner_profiles')->nullOnDelete();
            $table->foreignId('service_id')->constrained('services');
            $table->foreignId('area_id')->constrained('areas');
            $table->string('customer_name', 120);
            $table->string('customer_phone', 20);
            $table->text('address');
            $table->string('pincode', 12)->nullable();
            $table->decimal('lat', 10, 7)->nullable();
            $table->decimal('lng', 10, 7)->nullable();
            $table->date('scheduled_date');
            $table->string('scheduled_slot', 20)->nullable(); // e.g. "10:00 AM - 11:00 AM"
            $table->text('notes')->nullable();

            $table->unsignedInteger('amount_paise')->default(0);
            $table->unsignedInteger('tax_paise')->default(0);
            $table->unsignedInteger('total_paise')->default(0);

            $table->enum('status', [
                'pending',     // created, waiting for partner acceptance
                'accepted',    // partner accepted
                'rejected',    // partner rejected
                'on_the_way',  // partner en route
                'arrived',     // partner at location
                'in_progress', // OTP verified, work started
                'completed',   // work finished
                'cancelled',   // cancelled
            ])->default('pending');

            $table->string('payment_status', 20)->default('pending'); // pending, paid, refunded
            $table->string('payment_method', 30)->default('cod'); // cod, online, wallet
            $table->string('transaction_id', 80)->nullable();

            $table->string('start_otp', 6)->nullable();
            $table->timestamp('start_otp_verified_at')->nullable();
            $table->string('completion_otp', 6)->nullable();
            $table->timestamp('completion_otp_verified_at')->nullable();

            $table->timestamp('accepted_at')->nullable();
            $table->timestamp('started_at')->nullable();
            $table->timestamp('completed_at')->nullable();
            $table->timestamp('cancelled_at')->nullable();

            $table->timestamps();

            $table->index(['status', 'scheduled_date']);
            $table->index('customer_id');
            $table->index('partner_id');
        });
    }

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