<?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(): void
    {
        Schema::create('invoices', function (Blueprint $table) {
            $table->id();
            $table->string('invoice_number')->unique();
            $table->string('status')->default('draft'); // draft, sent, paid, overdue, cancelled

            // Relationships
            $table->foreignId('customer_id')->constrained()->onDelete('cascade');
            $table->foreignId('service_order_id')->nullable()->constrained()->onDelete('set null');
            $table->foreignId('job_card_id')->nullable()->constrained()->onDelete('set null');
            $table->foreignId('estimate_id')->nullable()->constrained()->onDelete('set null');
            $table->foreignId('branch_id')->constrained()->onDelete('cascade');
            $table->foreignId('created_by')->constrained('users')->onDelete('cascade');

            // Invoice Details
            $table->date('invoice_date');
            $table->date('due_date');
            $table->text('description')->nullable();
            $table->text('notes')->nullable();
            $table->text('terms_and_conditions')->nullable();

            // Financial Information
            $table->decimal('subtotal', 10, 2)->default(0);
            $table->decimal('tax_rate', 5, 2)->default(0);
            $table->decimal('tax_amount', 10, 2)->default(0);
            $table->decimal('discount_amount', 10, 2)->default(0);
            $table->decimal('total_amount', 10, 2)->default(0);

            // Payment Information
            $table->timestamp('paid_at')->nullable();
            $table->string('payment_method')->nullable(); // cash, card, check, bank_transfer
            $table->string('payment_reference')->nullable();
            $table->text('payment_notes')->nullable();

            // Delivery Information
            $table->timestamp('sent_at')->nullable();
            $table->string('sent_method')->nullable(); // email, print, portal
            $table->string('sent_to')->nullable(); // email address or delivery method

            $table->timestamps();

            // Indexes
            $table->index(['customer_id', 'status']);
            $table->index(['branch_id', 'invoice_date']);
            $table->index(['status', 'due_date']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('invoices');
    }
};
