<?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
    {
        // Suppliers master
        Schema::create('suppliers', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->nullable()->constrained()->nullOnDelete();
            $table->string('name');
            $table->string('company_name')->nullable();
            $table->string('contact_person')->nullable();
            $table->string('phone')->nullable();
            $table->string('email')->nullable();
            $table->text('address')->nullable();
            $table->enum('supplier_type', ['manufacturer', 'distributor', 'wholesaler', 'local'])->default('distributor');
            $table->decimal('credit_limit', 12, 2)->default(0);
            $table->decimal('current_credit_balance', 12, 2)->default(0);
            $table->unsignedInteger('payment_terms_days')->default(30);
            $table->decimal('opening_balance', 12, 2)->default(0);
            $table->string('tax_number')->nullable();
            $table->string('license_number')->nullable(); // pharmacy/regulated suppliers
            $table->text('notes')->nullable();
            $table->boolean('is_active')->default(true);
            $table->timestamps();
            $table->softDeletes();

            $table->index('tenant_id');
            $table->index('is_active');
        });

        // Supplier invoices (each credit or cash purchase from supplier)
        Schema::create('supplier_invoices', function (Blueprint $table) {
            $table->id();
            $table->foreignId('supplier_id')->constrained()->cascadeOnDelete();
            $table->foreignId('branch_id')->constrained()->cascadeOnDelete();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->foreignId('purchase_order_id')->nullable()->constrained()->nullOnDelete();
            $table->string('invoice_number');
            $table->string('our_reference')->nullable();
            $table->date('invoice_date');
            $table->date('due_date');
            $table->decimal('subtotal', 12, 2)->default(0);
            $table->decimal('discount_amount', 12, 2)->default(0);
            $table->decimal('tax_amount', 12, 2)->default(0);
            $table->decimal('total_amount', 12, 2);
            $table->decimal('paid_amount', 12, 2)->default(0);
            $table->decimal('remaining_amount', 12, 2);
            $table->enum('payment_type', ['credit', 'cash'])->default('credit');
            $table->enum('status', ['draft', 'unpaid', 'partial', 'paid', 'overdue', 'cancelled'])->default('unpaid');
            $table->text('notes')->nullable();
            $table->timestamps();
            $table->softDeletes();

            $table->index('supplier_id');
            $table->index('branch_id');
            $table->index('status');
            $table->index('due_date');
            $table->index('payment_type');
        });

        // Supplier invoice line items
        Schema::create('supplier_invoice_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('supplier_invoice_id')->constrained()->cascadeOnDelete();
            $table->enum('item_type', ['ingredient', 'product', 'other'])->default('other');
            $table->foreignId('ingredient_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('product_id')->nullable()->constrained()->nullOnDelete();
            $table->string('description'); // always filled as fallback label
            $table->decimal('quantity', 10, 3);
            $table->decimal('bonus_quantity', 10, 3)->default(0); // free goods from supplier
            $table->string('unit')->nullable();
            $table->decimal('unit_price', 12, 4);
            $table->decimal('total_price', 12, 2);
            $table->string('batch_number')->nullable();  // pharmacy / perishables
            $table->date('expiry_date')->nullable();     // pharmacy / perishables
            $table->text('notes')->nullable();
            $table->timestamps();

            $table->index('supplier_invoice_id');
            $table->index('ingredient_id');
            $table->index('product_id');
        });

        // Payments made to suppliers
        Schema::create('supplier_payments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('supplier_id')->constrained()->cascadeOnDelete();
            $table->foreignId('branch_id')->constrained()->cascadeOnDelete();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->decimal('amount', 12, 2);
            $table->enum('payment_method', ['cash', 'bank_transfer', 'cheque', 'online', 'other'])->default('cash');
            $table->date('payment_date');
            $table->string('reference_number')->nullable(); // cheque no, txn id
            $table->text('notes')->nullable();
            $table->timestamps();
            $table->softDeletes();

            $table->index('supplier_id');
            $table->index('branch_id');
            $table->index('payment_date');
        });

        // Credit notes / returns / adjustments
        Schema::create('supplier_credit_notes', function (Blueprint $table) {
            $table->id();
            $table->foreignId('supplier_id')->constrained()->cascadeOnDelete();
            $table->foreignId('branch_id')->constrained()->cascadeOnDelete();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->foreignId('supplier_invoice_id')->nullable()->constrained()->nullOnDelete();
            $table->string('credit_note_number');
            $table->decimal('amount', 12, 2);
            $table->enum('reason', [
                'goods_return',
                'damaged',
                'overcharge',
                'discount',
                'expiry_return',
                'recall',
                'other'
            ])->default('goods_return');
            $table->date('date');
            $table->text('notes')->nullable();
            $table->timestamps();
            $table->softDeletes();

            $table->index('supplier_id');
            $table->index('branch_id');
            $table->index('date');
        });

        // Ledger: auto-maintained running statement per supplier
        Schema::create('supplier_ledger', function (Blueprint $table) {
            $table->id();
            $table->foreignId('supplier_id')->constrained()->cascadeOnDelete();
            $table->foreignId('branch_id')->constrained()->cascadeOnDelete();
            $table->enum('transaction_type', [
                'opening_balance',
                'invoice',
                'payment',
                'credit_note',
                'adjustment'
            ]);
            $table->string('reference_type')->nullable(); // SupplierInvoice, SupplierPayment, etc.
            $table->unsignedBigInteger('reference_id')->nullable();
            $table->string('description');
            $table->decimal('debit', 12, 2)->default(0);   // amount owed (invoice)
            $table->decimal('credit', 12, 2)->default(0);  // amount paid/credited
            $table->decimal('balance', 12, 2)->default(0); // running balance
            $table->date('transaction_date');
            $table->timestamps();

            $table->index('supplier_id');
            $table->index('branch_id');
            $table->index('transaction_date');
            $table->index(['reference_type', 'reference_id']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('supplier_ledger');
        Schema::dropIfExists('supplier_credit_notes');
        Schema::dropIfExists('supplier_payments');
        Schema::dropIfExists('supplier_invoice_items');
        Schema::dropIfExists('supplier_invoices');
        Schema::dropIfExists('suppliers');
    }
};
