<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product; 
use App\Models\Sale;
use App\Models\SaleDetail;
use Illuminate\Support\Facades\DB;
//
use App\Models\Client;

class SaleController extends Controller
{
    public function create()
    {
        // Buscamos productos que tengan stock mayor a 0 para mostrar en el selector
        $products = Product::where('stock', '>', 0)->get();

        $clients = \App\Models\Client::orderBy('nombre')->get(); 

        return view('sales.create', compact('products', 'clients'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'payment_method' => 'required|string',
            'client_id' => 'nullable|exists:clients,id',
            'items' => 'required|array',
            'items.*.product_id' => 'required|exists:products,id',
            'items.*.quantity' => 'required|integer|min:1',
        ]);

        try {
            DB::transaction(function () use ($request) {
                $totalVenta = 0;

                foreach ($request->items as $item) {
                    $product = Product::find($item['product_id']);
                    $totalVenta += $product->precio * $item['quantity'];
                    
                    if ($product->stock < $item['quantity']) {
                        throw new \Exception("No hay suficiente stock de " . $product->nombre);
                    }
                }

                //cabecera
                $sale = Sale::create([
                    //'user_id' => auth()->id(), //empleado logueado
                    'client_id' => $request->client_id,
                    'total' => $totalVenta,
                    'payment_method' => $request->payment_method,
                ]);

                foreach ($request->items as $item) {
                    $product = Product::find($item['product_id']);

                    SaleDetail::create([
                        'sale_id' => $sale->id,
                        'product_id' => $product->id,
                        'cantidad' => $item['quantity'],
                        'precio' => $product->precio,
                    ]);
                    $nuevoStock = $product->stock - $item['quantity'];
                    $product->stock = $nuevoStock;
                    $product->save();
                }
            });

            // 5. REDIRECCIÓN DE ÉXITO
            // Redirigimos al usuario con un mensaje flash [cite: 668]
            return redirect()->route('sales.create')->with('success', '¡Venta registrada correctamente!');

        } catch (\Exception $e) {
            // Si algo falló (ej: falta stock), volvemos atrás con el error
            return back()->with('error', 'Error en la venta: ' . $e->getMessage());
        }
    }
}
