<?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('manychat_pedidos', function (Blueprint $table): void {
            $table->id();
            $table->unsignedBigInteger('empresa_id');
            $table->string('cliente_nombre', 160);
            $table->string('telefono', 30)->nullable();
            $table->text('direccion')->nullable();
            $table->text('observaciones')->nullable();
            $table->decimal('total', 14, 2)->default(0);
            $table->enum('estado', ['pendiente', 'confirmado', 'en_proceso', 'entregado', 'cancelado'])->default('pendiente');
            $table->string('origen', 60)->default('whatsapp_manychat');
            $table->timestamps();

            $table->index(['empresa_id', 'estado']);
            $table->foreign('empresa_id')->references('id')->on('empresas')->onDelete('cascade');
        });

        Schema::create('manychat_pedido_detalles', function (Blueprint $table): void {
            $table->id();
            $table->unsignedBigInteger('pedido_id');
            $table->unsignedBigInteger('producto_id');
            $table->string('producto_nombre', 200);
            $table->decimal('precio_unitario', 14, 2);
            $table->decimal('cantidad', 10, 2);
            $table->decimal('subtotal', 14, 2);
            $table->timestamps();

            $table->foreign('pedido_id')->references('id')->on('manychat_pedidos')->onDelete('cascade');
            $table->foreign('producto_id')->references('id')->on('productos')->onDelete('restrict');
        });
    }

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