<?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
    {
        // Detect customer table name (your schema earlier used 'acc_customers')
        $customerTable = null;
        if (Schema::hasTable('acc_customers')) {
            $customerTable = 'acc_customers';
        } elseif (Schema::hasTable('customers')) {
            $customerTable = 'customers';
        }

        Schema::table('acc_sales', function (Blueprint $table) use ($customerTable) {
            if ($customerTable) {
                $table->foreign('customer_id', 'acc_sales_customer_fk')
                      ->references('id')->on($customerTable)
                      ->onUpdate('cascade')
                      ->onDelete('restrict'); // required
            }

            if (Schema::hasTable('companies')) {
                $table->foreign('company_id', 'acc_sales_company_fk')
                      ->references('id')->on('companies')
                      ->onUpdate('cascade')
                      ->onDelete('set null'); // nullable
            }

            if (Schema::hasTable('users')) {
                $table->foreign('created_by', 'acc_sales_created_by_fk')
                      ->references('id')->on('users')
                      ->onUpdate('cascade')
                      ->onDelete('restrict');

                $table->foreign('updated_by', 'acc_sales_updated_by_fk')
                      ->references('id')->on('users')
                      ->onUpdate('cascade')
                      ->onDelete('set null');
            }
        });
    }

    public function down(): void
    {
        Schema::table('acc_sales', function (Blueprint $table) {
            // Guarded drops in case some weren’t created
            try { $table->dropForeign('acc_sales_customer_fk'); } catch (\Throwable $e) {}
            try { $table->dropForeign('acc_sales_company_fk'); } catch (\Throwable $e) {}
            try { $table->dropForeign('acc_sales_created_by_fk'); } catch (\Throwable $e) {}
            try { $table->dropForeign('acc_sales_updated_by_fk'); } catch (\Throwable $e) {}
        });
    }
};

