<?php

namespace App\Livewire;

use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use App\Models\Sale;
use App\Models\SaleDetail;
use App\Models\Product;
use App\Models\Client;
use Illuminate\Support\Facades\DB;

class Sales extends Component
{
    // Datos del formulario
    public $client_id;
    public $bcv_rate; // Tasa del día
    public $sale_date;
    public $notes;
    
    // Lista de productos en el carrito
    // Cada item será: ['product_id' => x, 'quantity' => y, 'price' => z, 'subtotal' => w]
    public $orderProducts = []; 
    
    // Totales
    public $total_usd = 0;
    public $total_ves = 0;

    public function mount()
    {
        // Valores iniciales
        $this->sale_date = date('Y-m-d');
        $this->bcv_rate = 60.00; // Valor por defecto (puedes cambiarlo al cargar)
        $this->addProductRow(); // Agregamos una fila vacía al iniciar
    }

    public function render()
    {
        return view('livewire.sales', [
            'clients' => Client::all(),
            'products' => Product::where('is_active', true)->get()
        ]);
    }

    // Agregar una línea nueva al pedido
    public function addProductRow()
    {
        $this->orderProducts[] = [
            'product_id' => '',
            'quantity' => 1,
            'price' => 0,
            'subtotal' => 0
        ];
    }

    // Eliminar una línea
    public function removeProductRow($index)
    {
        unset($this->orderProducts[$index]);
        $this->orderProducts = array_values($this->orderProducts); // Reordenar índices
        $this->calculateTotal();
    }

    // Cuando seleccionas un producto, buscamos su precio automáticamente
    public function updatedOrderProducts($value, $key)
    {
        // $key viene como "0.product_id" o "0.quantity"
        $parts = explode('.', $key);
        $index = $parts[0];
        $field = $parts[1];

        if ($field === 'product_id') {
            $product = Product::find($value);
            if ($product) {
                $this->orderProducts[$index]['price'] = $product->price_usd;
            }
        }

        $this->calculateRow($index);
    }

    // Calcular subtotal de una fila
    public function calculateRow($index)
    {
        $qty = (float)($this->orderProducts[$index]['quantity'] ?? 0);
        $price = (float)($this->orderProducts[$index]['price'] ?? 0);
        
        $this->orderProducts[$index]['subtotal'] = $qty * $price;
        $this->calculateTotal();
    }

    // Calcular el total general de la factura
    public function calculateTotal()
    {
        $this->total_usd = 0;
        foreach ($this->orderProducts as $item) {
            $this->total_usd += $item['subtotal'];
        }
        
        // Calcular Bolívares según la tasa
        $this->total_ves = $this->total_usd * (float)$this->bcv_rate;
    }

    // Si cambio la tasa BCV manualmente, recalcula los bolívares
    public function updatedBcvRate()
    {
        $this->calculateTotal();
    }

    public function saveSale()
    {
        $this->validate([
            'client_id' => 'required',
            'bcv_rate' => 'required|numeric|min:1',
            'sale_date' => 'required|date',
            'orderProducts' => 'required|array|min:1',
            'orderProducts.*.product_id' => 'required',
            'orderProducts.*.quantity' => 'required|numeric|min:0.1',
        ]);

        // Usamos DB Transaction por seguridad (si falla algo, no guarda nada)
        DB::transaction(function () {
            // 1. Crear el Encabezado de la Venta
            $sale = Sale::create([
                'client_id' => $this->client_id,
                'user_id' => Auth::id(), // El usuario logueado
                'sale_date' => $this->sale_date,
                'bcv_rate' => $this->bcv_rate,
                'total_usd' => $this->total_usd,
                'total_ves' => $this->total_ves,
                'notes' => $this->notes
            ]);

            // 2. Crear los Detalles (Productos)
            foreach ($this->orderProducts as $item) {
                SaleDetail::create([
                    'sale_id' => $sale->id,
                    'product_id' => $item['product_id'],
                    'quantity' => $item['quantity'],
                    'price_at_moment_usd' => $item['price'],
                    'subtotal_usd' => $item['subtotal']
                ]);
            }
        });

        session()->flash('message', '¡Venta registrada con éxito!');
        
        // Resetear formulario
        $this->reset(['client_id', 'total_usd', 'total_ves', 'notes', 'orderProducts']);
        $this->addProductRow(); 
    }
}