<?php

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

class CreateInvoicesTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('invoices', function (Blueprint $table) {
            $table->id();

            // Links
            $table->unsignedBigInteger('order_id')->index();
            $table->unsignedBigInteger('customer_id')->nullable()->index(); // snapshot link if available
            $table->string('mark_no')->nullable()->index();

            // Invoice identity
            $table->string('invoice_number')->unique();
            $table->date('invoice_date')->nullable();
            $table->date('due_date')->nullable();

            // Payment / status
            $table->string('payment_method')->nullable();
            $table->string('reference_no')->nullable();
            $table->enum('status', ['pending','paid','overdue'])->default('pending');

            // Amounts
            $table->decimal('final_amount', 14, 2)->default(0.00);          // editable by user
            $table->decimal('gst_percent', 5, 2)->default(0.00);            // editable by user
            $table->decimal('gst_amount', 14, 2)->default(0.00);           // auto-calculated
            $table->decimal('final_amount_with_gst', 14, 2)->default(0.00); // auto-calculated

            // Customer snapshot (immutable fields)
            $table->string('customer_name')->nullable();
            $table->string('company_name')->nullable();
            $table->string('customer_email')->nullable();
            $table->string('customer_mobile')->nullable();
            $table->text('customer_address')->nullable();
            $table->string('pincode')->nullable();

            // PDF / notes
            $table->string('pdf_path')->nullable();
            $table->text('notes')->nullable();

            $table->timestamps();

            // Foreign keys (optional — adjust table names/namespaces if yours are different)
            $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
            // customer_id may reference users table, keep nullable to avoid migration order issues
            $table->foreign('customer_id')->references('id')->on('users')->onDelete('set null');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('invoices', function (Blueprint $table) {
            $table->dropForeign(['order_id']);
            $table->dropForeign(['customer_id']);
        });
        Schema::dropIfExists('invoices');
    }
}
