<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePrCurrenciesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        if (!Schema::hasTable('pr_currencies')) {
            Schema::create('pr_currencies', function (Blueprint $table) {
                $table->increments('id');
                $table->integer('business_id')->unsigned();
                $table->foreign('business_id')->references('id')->on('business')->onDelete('cascade');
                $table->string('code', 10); // USD, CNY, EGP
                $table->string('name', 100);
                $table->string('symbol', 10);
                $table->decimal('conversion_rate_to_egp', 22, 4)->default(1);
                $table->boolean('is_active')->default(true);
                $table->timestamps();

                $table->unique(['business_id', 'code']);
                $table->index('business_id');
            });
        }

        // Add foreign key to pr_supplier_responses table (only if not already present)
        $fkExists = \DB::select("SELECT 1 FROM information_schema.KEY_COLUMN_USAGE
            WHERE TABLE_SCHEMA = DATABASE()
            AND TABLE_NAME = 'pr_supplier_responses'
            AND CONSTRAINT_NAME = 'pr_supplier_responses_currency_id_foreign'
            LIMIT 1");

        if (!$fkExists) {
            Schema::table('pr_supplier_responses', function (Blueprint $table) {
                $table->foreign('currency_id')->references('id')->on('pr_currencies')->onDelete('set null');
            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        // Drop foreign key first
        Schema::table('pr_supplier_responses', function (Blueprint $table) {
            $table->dropForeign(['currency_id']);
        });

        Schema::dropIfExists('pr_currencies');
    }
}
