<?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
    {
        Schema::create('number_sequences', function (Blueprint $table) {
            $table->id();
            $table->string('name'); // invoice, receipt, etc.
            $table->date('date'); // Date for the sequence
            $table->integer('current_number')->default(0);
            $table->string('reset_type')->default('daily'); // daily, monthly, never
            $table->timestamps();
            
            $table->unique(['name', 'date']);
            $table->index(['name', 'date']);
        });
        
        // Add number fields to sales table if not exists
        Schema::table('sales', function (Blueprint $table) {
            if (!Schema::hasColumn('sales', 'invoice_no')) {
                $table->string('invoice_no')->nullable()->after('id');
            }
            if (!Schema::hasColumn('sales', 'receipt_no')) {
                $table->string('receipt_no')->nullable()->after('invoice_no');
            }
            
            $table->index('invoice_no');
            $table->index('receipt_no');
        });
    }
    
    public function down(): void
    {
        Schema::dropIfExists('number_sequences');
        
        Schema::table('sales', function (Blueprint $table) {
            $table->dropColumn(['invoice_no', 'receipt_no']);
        });
    }
};