<?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
    {
        if (!Schema::hasTable('customer_ledgers')) return;

        // Detect which customer table you use
        $customerTable = null;
        foreach (['customers', 'acc_customers'] as $cand) {
            if (Schema::hasTable($cand)) { $customerTable = $cand; break; }
        }

        Schema::table('customer_ledgers', function (Blueprint $table) use ($customerTable) {
            // customer_id → customers/acc_customers
            if ($customerTable) {
                $table->foreign('customer_id', 'cl_customer_fk')
                      ->references('id')->on($customerTable)
                      ->onUpdate('cascade')
                      ->onDelete('restrict');
            }

            // sale_id → acc_sales (most setups)
            if (Schema::hasTable('acc_sales')) {
                $table->foreign('sale_id', 'cl_sale_fk')
                      ->references('id')->on('acc_sales')
                      ->onUpdate('cascade')
                      ->onDelete('restrict');
            }

            // account_id → accounts (nullable)
            if (Schema::hasTable('accounts')) {
                $table->foreign('account_id', 'cl_account_fk')
                      ->references('id')->on('accounts')
                      ->onUpdate('cascade')
                      ->onDelete('set null');
            }

            // users (created_by required → RESTRICT; updated_by nullable → SET NULL)
            if (Schema::hasTable('users')) {
                $table->foreign('created_by', 'cl_created_by_fk')
                      ->references('id')->on('users')
                      ->onUpdate('cascade')
                      ->onDelete('restrict');

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

    public function down(): void
    {
        if (!Schema::hasTable('customer_ledgers')) return;

        Schema::table('customer_ledgers', function (Blueprint $table) {
            foreach (['cl_customer_fk','cl_sale_fk','cl_account_fk','cl_created_by_fk','cl_updated_by_fk'] as $fk) {
                try { $table->dropForeign($fk); } catch (\Throwable $e) {}
            }
        });
    }
};
