<?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('promotions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('vendor_id')->nullable()->constrained()->nullOnDelete(); // null = platform-wide
            $table->string('name');
            $table->string('code')->unique()->nullable(); // null = auto-applied
            $table->enum('type', ['percentage', 'flat', 'free_delivery'])->default('percentage');
            $table->decimal('value', 10, 2); // % or PKR amount
            $table->decimal('min_order_value', 10, 2)->default(0);
            $table->decimal('max_discount', 10, 2)->nullable();
            $table->integer('usage_limit')->nullable(); // null = unlimited
            $table->integer('usage_per_user')->default(1);
            $table->integer('used_count')->default(0);
            $table->boolean('is_active')->default(true);
            $table->boolean('is_flash_sale')->default(false);
            $table->integer('flash_sale_stock')->nullable();
            $table->timestamp('starts_at')->nullable();
            $table->timestamp('ends_at')->nullable();

            // Scope
            $table->json('product_ids')->nullable();    // specific products
            $table->json('category_ids')->nullable();   // specific categories
            $table->timestamps();
        });

        Schema::create('promotion_usages', function (Blueprint $table) {
            $table->id();
            $table->foreignId('promotion_id')->constrained()->cascadeOnDelete();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->foreignId('order_id')->constrained()->cascadeOnDelete();
            $table->decimal('discount_applied', 10, 2);
            $table->timestamps();
        });

        // NOTE: the `banners` table lives in its own, richer migration
        // (2026_06_25_000001_create_banners_table.php — adds `placement`/`link_value`).
        // It was duplicated here historically; removed so a fresh migrate doesn't
        // collide. Production already has the canonical schema from that migration.
    }

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