<?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('caja_movimientos', function (Blueprint $table) {
            $table->id();
            $table->foreignId('sesion_id')->constrained('caja_sesiones')->cascadeOnDelete();
            $table->foreignId('sucursal_id')->constrained('sucursales')->cascadeOnDelete();
            $table->enum('tipo', ['ingreso', 'egreso']);
            $table->string('concepto', 200);
            $table->enum('categoria', [
                'venta_efectivo', 'venta_tarjeta', 'venta_transferencia',
                'adelanto_cliente', 'devolucion_cliente',
                'pago_proveedor', 'pago_servicio', 'gasto_operativo',
                'retiro_caja', 'deposito_banco', 'otro',
            ]);
            $table->decimal('monto', 10, 2);
            $table->decimal('subtotal', 10, 2)->default(0);  // monto sin IGV
            $table->decimal('igv', 10, 2)->default(0);
            // Referencia opcional a otro módulo
            $table->string('referencia_tipo', 50)->nullable();
            $table->unsignedBigInteger('referencia_id')->nullable();
            // Comprobante (preparado para SUNAT)
            $table->enum('comprobante_tipo', ['boleta', 'factura', 'ticket', 'ninguno'])->default('ninguno');
            $table->string('comprobante_numero', 30)->nullable();
            $table->string('ruc_cliente', 11)->nullable();
            $table->string('razon_social_cliente', 150)->nullable();
            // Anulación
            $table->boolean('anulado')->default(false);
            $table->foreignId('anulado_por')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamp('anulado_at')->nullable();
            $table->text('motivo_anulacion')->nullable();
            // Control
            $table->foreignId('user_id')->constrained()->restrictOnDelete();
            $table->timestamp('created_at')->useCurrent();

            $table->index('sesion_id', 'idx_cm_sesion');
            $table->index('created_at', 'idx_cm_fecha');
            $table->index(['tipo', 'anulado'], 'idx_cm_tipo');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('caja_movimientos');
    }
};