<?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('orders', function (Blueprint $table) {
            $table->id();
            $table->string('order_number')->unique();
            $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();

            // Shipping details are captured as a plain snapshot (not a saved
            // address FK) so guest checkout works and receipts stay accurate
            // even if a logged-in customer edits their profile later.
            $table->string('customer_name');
            $table->string('customer_phone', 20);
            $table->string('customer_email')->nullable();
            $table->string('shipping_address', 500);
            $table->string('shipping_city');
            $table->string('shipping_area');
            $table->text('order_notes')->nullable();

            $table->decimal('subtotal', 10, 2);
            $table->decimal('shipping_charge', 10, 2)->default(0);
            $table->decimal('discount_amount', 10, 2)->default(0);
            $table->foreignId('coupon_id')->nullable()->constrained()->nullOnDelete();
            $table->string('coupon_code')->nullable();
            $table->decimal('grand_total', 10, 2);

            $table->enum('payment_method', ['cod', 'easypaisa']);
            $table->enum('payment_status', ['pending', 'paid', 'rejected'])->default('pending');
            $table->enum('order_status', [
                'pending', 'confirmed', 'packing', 'shipped', 'delivered', 'cancelled',
            ])->default('pending');
            $table->string('cancelled_reason')->nullable();

            $table->timestamps();

            $table->index('order_status');
            $table->index('payment_status');
        });
    }

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