<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up()
    {
        if (!Schema::hasColumn('sales_dashboard', 'user_id')) {
            Schema::table('sales_dashboard', function (Blueprint $table) {
                $table->foreignId('user_id')->nullable()->constrained('users')->onDelete('cascade')->after('id');
            });
        }

        if (!Schema::hasColumn('sales_dashboard', 'payment_method')) {
            Schema::table('sales_dashboard', function (Blueprint $table) {
                $table->string('payment_method')->nullable()->after('cash_received_by');
            });
        }

        if (!Schema::hasColumn('sales_dashboard', 'bank_account_id')) {
            Schema::table('sales_dashboard', function (Blueprint $table) {
                $table->foreignId('bank_account_id')->nullable()->constrained('bank_accounts')->onDelete('set null')->after('payment_method');
            });
        }

        if (!Schema::hasColumn('sales_dashboard', 'digital_payment_id')) {
            Schema::table('sales_dashboard', function (Blueprint $table) {
                $table->foreignId('digital_payment_id')->nullable()->constrained('digital_payments')->onDelete('set null')->after('bank_account_id');
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down()
    {
        Schema::table('sales_dashboard', function (Blueprint $table) {
            if (Schema::hasColumn('sales_dashboard', 'user_id')) {
                $table->dropForeignKey(['user_id']);
                $table->dropColumn('user_id');
            }
            if (Schema::hasColumn('sales_dashboard', 'digital_payment_id')) {
                $table->dropForeignKey(['digital_payment_id']);
                $table->dropColumn('digital_payment_id');
            }
            if (Schema::hasColumn('sales_dashboard', 'bank_account_id')) {
                $table->dropForeignKey(['bank_account_id']);
                $table->dropColumn('bank_account_id');
            }
            if (Schema::hasColumn('sales_dashboard', 'payment_method')) {
                $table->dropColumn('payment_method');
            }
        });
    }
};
