<?php

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

/**
 * Migration 12 – Extend customers/suppliers with missing Saudi ERP fields
 * and create opening balance ledger tables.
 *
 * NOTE: We use hasColumn() guards everywhere because migration 11 and the original
 * Prompt 1 migration may have already added some of these columns.
 */
return new class extends Migration
{
    public function up(): void
    {
        // ---- CUSTOMERS -------------------------------------------------------
        Schema::table('customers', function (Blueprint $table) {
            // Extend columns that are NOT in the original Prompt-1 customers table
            if (!Schema::hasColumn('customers', 'vat_registered')) {
                $table->boolean('vat_registered')->default(false)->after('customer_type');
            }
            if (!Schema::hasColumn('customers', 'customer_ref')) {
                $table->string('customer_ref')->nullable()->after('cr_number');
            }
            if (!Schema::hasColumn('customers', 'contact_person')) {
                $table->string('contact_person')->nullable()->after('customer_ref');
            }
            if (!Schema::hasColumn('customers', 'mobile')) {
                $table->string('mobile')->nullable()->after('phone');
            }
            // Saudi address (columns already present from prompt 1 as street_name_en/ar, using them as is)
            if (!Schema::hasColumn('customers', 'street_en')) {
                // street_name_en exists, we use a different column name to avoid collision
                $table->string('street_en')->nullable()->after('building_number');
            }
            if (!Schema::hasColumn('customers', 'street_ar')) {
                $table->string('street_ar')->nullable()->after('street_en');
            }
            if (!Schema::hasColumn('customers', 'national_address')) {
                $table->text('national_address')->nullable()->after('additional_number');
            }
            if (!Schema::hasColumn('customers', 'credit_days')) {
                $table->integer('credit_days')->default(0)->after('credit_limit');
            }
            if (!Schema::hasColumn('customers', 'price_level')) {
                $table->enum('price_level', ['retail', 'wholesale', 'special'])->default('retail')->after('customer_type');
            }
            if (!Schema::hasColumn('customers', 'credit_allowed')) {
                $table->boolean('credit_allowed')->default(false)->after('price_level');
            }
            if (!Schema::hasColumn('customers', 'opening_balance')) {
                $table->decimal('opening_balance', 18, 2)->default(0.00);
            }
            if (!Schema::hasColumn('customers', 'opening_balance_type')) {
                $table->enum('opening_balance_type', ['receivable', 'advance'])->default('receivable');
            }
            if (!Schema::hasColumn('customers', 'default_payment_type')) {
                $table->enum('default_payment_type', ['cash', 'credit'])->default('cash');
            }
            if (!Schema::hasColumn('customers', 'salesman')) {
                $table->string('salesman')->nullable();
            }
            if (!Schema::hasColumn('customers', 'route')) {
                $table->string('route')->nullable();
            }
            if (!Schema::hasColumn('customers', 'branch_id')) {
                $table->foreignId('branch_id')->nullable()->constrained('branches')->onDelete('set null');
            }
            if (!Schema::hasColumn('customers', 'is_system')) {
                $table->boolean('is_system')->default(false);
            }
            if (!Schema::hasColumn('customers', 'notes')) {
                $table->text('notes')->nullable();
            }
        });

        // ---- SUPPLIERS -------------------------------------------------------
        Schema::table('suppliers', function (Blueprint $table) {
            if (!Schema::hasColumn('suppliers', 'vat_registered')) {
                $table->boolean('vat_registered')->default(false)->after('supplier_code');
            }
            if (!Schema::hasColumn('suppliers', 'contact_person')) {
                $table->string('contact_person')->nullable()->after('cr_number');
            }
            if (!Schema::hasColumn('suppliers', 'mobile')) {
                $table->string('mobile')->nullable()->after('phone');
            }
            if (!Schema::hasColumn('suppliers', 'building_number')) {
                $table->string('building_number')->nullable();
            }
            if (!Schema::hasColumn('suppliers', 'street')) {
                $table->string('street')->nullable();
            }
            if (!Schema::hasColumn('suppliers', 'district')) {
                $table->string('district')->nullable();
            }
            if (!Schema::hasColumn('suppliers', 'city')) {
                $table->string('city')->nullable();
            }
            if (!Schema::hasColumn('suppliers', 'postal_code')) {
                $table->string('postal_code')->nullable();
            }
            if (!Schema::hasColumn('suppliers', 'additional_number')) {
                $table->string('additional_number')->nullable();
            }
            if (!Schema::hasColumn('suppliers', 'country')) {
                $table->string('country')->default('Saudi Arabia');
            }
            if (!Schema::hasColumn('suppliers', 'payment_terms')) {
                $table->string('payment_terms')->nullable();
            }
            if (!Schema::hasColumn('suppliers', 'credit_days')) {
                $table->integer('credit_days')->default(0);
            }
            if (!Schema::hasColumn('suppliers', 'credit_limit')) {
                $table->decimal('credit_limit', 18, 2)->default(0.00);
            }
            if (!Schema::hasColumn('suppliers', 'opening_balance')) {
                $table->decimal('opening_balance', 18, 2)->default(0.00);
            }
            if (!Schema::hasColumn('suppliers', 'opening_balance_type')) {
                $table->enum('opening_balance_type', ['payable', 'advance'])->default('payable');
            }
            if (!Schema::hasColumn('suppliers', 'bank_name')) {
                $table->string('bank_name')->nullable();
            }
            if (!Schema::hasColumn('suppliers', 'iban')) {
                $table->string('iban')->nullable();
            }
            if (!Schema::hasColumn('suppliers', 'notes')) {
                $table->text('notes')->nullable();
            }
        });

        // ---- OPENING BALANCE LEDGER TABLES -----------------------------------
        Schema::create('customer_opening_balances', function (Blueprint $table) {
            $table->id();
            $table->foreignId('customer_id')->constrained('customers')->onDelete('cascade');
            $table->foreignId('financial_year_id')->constrained('financial_years')->onDelete('cascade');
            $table->date('opening_date');
            $table->string('reference')->unique();
            $table->decimal('amount', 18, 2)->default(0.00);
            $table->enum('type', ['receivable', 'advance'])->default('receivable');
            $table->enum('status', ['draft', 'approved'])->default('approved');
            $table->foreignId('created_by')->nullable()->constrained('users')->onDelete('set null');
            $table->foreignId('approved_by')->nullable()->constrained('users')->onDelete('set null');
            $table->text('notes')->nullable();
            $table->timestamps();
        });

        Schema::create('supplier_opening_balances', function (Blueprint $table) {
            $table->id();
            $table->foreignId('supplier_id')->constrained('suppliers')->onDelete('cascade');
            $table->foreignId('financial_year_id')->constrained('financial_years')->onDelete('cascade');
            $table->date('opening_date');
            $table->string('reference')->unique();
            $table->decimal('amount', 18, 2)->default(0.00);
            $table->enum('type', ['payable', 'advance'])->default('payable');
            $table->enum('status', ['draft', 'approved'])->default('approved');
            $table->foreignId('created_by')->nullable()->constrained('users')->onDelete('set null');
            $table->foreignId('approved_by')->nullable()->constrained('users')->onDelete('set null');
            $table->text('notes')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('supplier_opening_balances');
        Schema::dropIfExists('customer_opening_balances');
    }
};
