<?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('supplier_bills', function (Blueprint $table) {
            $table->id();
            $table->foreignId('supplier_id')->constrained('suppliers')->cascadeOnDelete();
            $table->string('bill_number'); // Supplier's bill/invoice number
            $table->date('bill_date');
            $table->string('batch_id')->unique()->index(); // Generated batch ID for this bill
            $table->string('batch_hash')->unique()->index(); // Hash for verification
            $table->decimal('total_amount', 12, 2)->default(0);
            $table->string('bill_file')->nullable(); // Path to uploaded bill PDF/image
            $table->foreignId('restaurant_id')->constrained('restaurants')->cascadeOnDelete();
            $table->foreignId('branch_id')->nullable()->constrained('branches')->nullOnDelete();
            $table->text('notes')->nullable();
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
            
            // Indexes
            $table->index('supplier_id');
            $table->index(['restaurant_id', 'bill_date']);
            $table->index('bill_date');
            
            // Unique constraint: prevent duplicate bills from same supplier
            $table->unique(['supplier_id', 'bill_number'], 'supplier_bills_supplier_bill_number_unique');
        });
    }

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