<?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
    {
        // 1. Enhanced coupons
        Schema::table('coupons', function (Blueprint $table) {
            if (!Schema::hasColumn('coupons', 'vendor_id')) {
                $table->foreignId('vendor_id')->nullable()->after('id')->constrained()->onDelete('cascade');
            }
            if (!Schema::hasColumn('coupons', 'created_by')) {
                $table->enum('created_by', ['admin', 'vendor'])->default('admin')->after('vendor_id');
            }
            if (!Schema::hasColumn('coupons', 'scope')) {
                $table->enum('scope', ['global', 'vendor', 'products'])->default('global')->after('created_by');
            }
            if (!Schema::hasColumn('coupons', 'description')) {
                $table->string('description')->nullable()->after('code');
            }
            if (!Schema::hasColumn('coupons', 'max_discount')) {
                $table->decimal('max_discount', 10, 2)->nullable()->after('value');
            }
            if (!Schema::hasColumn('coupons', 'per_user_limit')) {
                $table->integer('per_user_limit')->nullable()->after('usage_limit');
            }
        });

        // Coupon-Product pivot
        if (!Schema::hasTable('coupon_product')) {
            Schema::create('coupon_product', function (Blueprint $table) {
                $table->id();
                $table->foreignId('coupon_id')->constrained()->onDelete('cascade');
                $table->foreignId('product_id')->constrained()->onDelete('cascade');
                $table->timestamps();
            });
        }

        // 2. Announcements
        if (!Schema::hasTable('announcements')) {
            Schema::create('announcements', function (Blueprint $table) {
                $table->id();
                $table->foreignId('created_by_user_id')->constrained('users')->onDelete('cascade');
                $table->string('title');
                $table->text('message');
                $table->enum('type', ['info', 'warning', 'success', 'danger'])->default('info');
                $table->enum('target', ['all_vendors', 'specific_vendors'])->default('all_vendors');
                $table->boolean('is_pinned')->default(false);
                $table->timestamp('published_at')->nullable();
                $table->timestamp('expires_at')->nullable();
                $table->timestamps();
            });
        }

        if (!Schema::hasTable('announcement_vendor')) {
            Schema::create('announcement_vendor', function (Blueprint $table) {
                $table->id();
                $table->foreignId('announcement_id')->constrained()->onDelete('cascade');
                $table->foreignId('vendor_id')->constrained()->onDelete('cascade');
                $table->boolean('is_read')->default(false);
                $table->timestamp('read_at')->nullable();
                $table->timestamps();
            });
        }

        // 3. Vendor settings (image limits, storefront)
        if (!Schema::hasTable('vendor_settings')) {
            Schema::create('vendor_settings', function (Blueprint $table) {
                $table->id();
                $table->foreignId('vendor_id')->constrained()->onDelete('cascade');
                $table->string('key');
                $table->text('value')->nullable();
                $table->timestamps();
                $table->unique(['vendor_id', 'key']);
            });
        }

        // Seed default admin settings for vendor controls
        $vendorSettings = [
            ['key' => 'vendor_max_product_images', 'value' => '10', 'group' => 'vendor_limits', 'type' => 'integer', 'label' => 'Max Product Images Per Product', 'description' => 'Maximum number of images a vendor can upload per product'],
            ['key' => 'vendor_max_image_size_kb', 'value' => '4096', 'group' => 'vendor_limits', 'type' => 'integer', 'label' => 'Max Image Size (KB)', 'description' => 'Maximum size per image in kilobytes'],
            ['key' => 'vendor_max_logo_size_kb', 'value' => '2048', 'group' => 'vendor_limits', 'type' => 'integer', 'label' => 'Max Logo Size (KB)', 'description' => 'Maximum vendor logo size in kilobytes'],
            ['key' => 'vendor_max_banner_size_kb', 'value' => '5120', 'group' => 'vendor_limits', 'type' => 'integer', 'label' => 'Max Banner Size (KB)', 'description' => 'Maximum vendor banner size in kilobytes'],
            ['key' => 'vendor_allowed_image_types', 'value' => 'jpg,jpeg,png,webp', 'group' => 'vendor_limits', 'type' => 'string', 'label' => 'Allowed Image Types', 'description' => 'Comma-separated list of allowed image extensions'],
            ['key' => 'vendor_can_create_coupons', 'value' => '1', 'group' => 'vendor_limits', 'type' => 'boolean', 'label' => 'Allow Vendors to Create Coupons', 'description' => 'Whether vendors can create coupons for their products'],
            ['key' => 'vendor_store_theme', 'value' => 'default', 'group' => 'storefront', 'type' => 'string', 'label' => 'Default Vendor Store Theme', 'description' => 'Default theme for vendor storefronts'],
            ['key' => 'vendor_custom_banner_enabled', 'value' => '1', 'group' => 'storefront', 'type' => 'boolean', 'label' => 'Allow Custom Banners', 'description' => 'Allow vendors to upload custom store banners'],
            ['key' => 'vendor_custom_colors_enabled', 'value' => '0', 'group' => 'storefront', 'type' => 'boolean', 'label' => 'Allow Custom Colors', 'description' => 'Allow vendors to customize store colors'],
            ['key' => 'vendor_store_layout', 'value' => 'grid', 'group' => 'storefront', 'type' => 'string', 'label' => 'Default Store Layout', 'description' => 'Default product layout in vendor stores (grid/list)'],
            ['key' => 'vendor_products_per_page', 'value' => '12', 'group' => 'storefront', 'type' => 'integer', 'label' => 'Products Per Page', 'description' => 'Number of products per page in vendor stores'],
            ['key' => 'vendor_show_rating', 'value' => '1', 'group' => 'storefront', 'type' => 'boolean', 'label' => 'Show Vendor Rating', 'description' => 'Display vendor rating on store page'],
        ];

        foreach ($vendorSettings as $setting) {
            if (!\DB::table('settings')->where('key', $setting['key'])->exists()) {
                \DB::table('settings')->insert(array_merge($setting, [
                    'is_public' => false,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]));
            }
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('announcement_vendor');
        Schema::dropIfExists('announcements');
        Schema::dropIfExists('coupon_product');
        Schema::dropIfExists('vendor_settings');
        
        Schema::table('coupons', function (Blueprint $table) {
            foreach (['vendor_id', 'created_by', 'scope', 'description', 'max_discount', 'per_user_limit'] as $col) {
                if (Schema::hasColumn('coupons', $col)) {
                    $table->dropColumn($col);
                }
            }
        });

        \DB::table('settings')->where('group', 'vendor_limits')->orWhere('group', 'storefront')->delete();
    }
};
