<?php

namespace App\Http\Controllers\Inventory;

use Illuminate\Http\Request;
use App\Models\InventoryMovement;
use App\Models\InventoryMovementDetail;
use App\Models\Product\Product;
use App\Models\Supplier\Supplier;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;

class InventoryMovementController extends Controller
{
    public function index(Request $request)
    {
        $search = $request->get("search");
        $tipo = $request->get("tipo");
        $idProveedor = $request->get("idProveedor");
        $start_date = $request->get("start_date");
        $end_date = $request->get("end_date");

        $movements = InventoryMovement::with(['details.product', 'supplier', 'user'])
            ->when($tipo, function($q) use ($tipo) {
                return $q->where('tipo', $tipo);
            })
            ->when($search, function($q) use ($search) {
                return $q->where('codigo_movimiento', 'like', "%$search%");
            })
            ->when($idProveedor, function($q) use ($idProveedor) {
                return $q->where('idProveedor', $idProveedor);
            })
            ->when($start_date && $end_date, function($q) use ($start_date, $end_date) {
                return $q->whereBetween('fecha', [$start_date, $end_date . ' 23:59:59']);
            })
            ->orderBy("id", "desc")
            ->paginate(25);

        return response()->json([
            "total" => $movements->total(),
            "paginate" => 25,
            "movements" => $movements
        ]);
    }

    public function config()
    {
        $products = Product::where('state', 1)->get();
        $suppliers = Supplier::where('state', 1)->get();

        return response()->json([
            "products" => $products->map(function($p) {
                return [
                    "id" => $p->id,
                    "nombre" => $p->title,
                    "precio_venta" => $p->price_general,
                    "unidad_medida" => $p->unidad_medida,
                    "stock_actual" => $p->stock_actual
                ];
            }),
            "suppliers" => $suppliers->map(function($s) {
                return [
                    "id" => $s->idProveedor,
                    "razonSocial" => $s->razonSocial
                ];
            })
        ]);
    }

    public function store(Request $request)
    {
        try {
            DB::beginTransaction();

            // Generar código de movimiento
            $last_mov = InventoryMovement::orderBy('id', 'desc')->first();
            $num = $last_mov ? ($last_mov->id + 1) : 1;
            $codigo = "MOV-" . str_pad($num, 6, "0", STR_PAD_LEFT);

            $data = $request->all();
            $data['codigo_movimiento'] = $codigo;
            $data['user_id'] = auth('api')->user()->id;
            $data['fecha'] = Carbon::now();

            // Manejo de Archivos
            if ($request->hasFile('file_guia_remision')) {
                $data['guia_remision'] = Storage::disk('public')->putFile("inventory/guides", $request->file('file_guia_remision'));
            }
            if ($request->hasFile('file_firma_entrega')) {
                $data['firma_entrega'] = Storage::disk('public')->putFile("inventory/signatures", $request->file('file_firma_entrega'));
            }
            if ($request->hasFile('file_firma_recepcion')) {
                $data['firma_recepcion'] = Storage::disk('public')->putFile("inventory/signatures", $request->file('file_firma_recepcion'));
            }
            if ($request->hasFile('file_recepcion_evidencia')) {
                $data['recepcion_evidencia'] = Storage::disk('public')->putFile("inventory/evidence", $request->file('file_recepcion_evidencia'));
            }

            $movement = InventoryMovement::create($data);

            $details = json_decode($request->details, true);
            foreach ($details as $detail) {
                InventoryMovementDetail::create([
                    'idMovimiento' => $movement->id,
                    'idProducto' => $detail['idProducto'],
                    'cantidad' => $detail['cantidad'],
                    'precioUnitario' => $detail['precioUnitario'] ?? 0
                ]);
            }

            DB::commit();
            return response()->json(["code" => 200, "message" => "Movimiento registrado con éxito"]);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(["code" => 500, "message" => "Error: " . $e->getMessage()], 500);
        }
    }

    public function show($id)
    {
        $movement = InventoryMovement::with(['details.product', 'supplier', 'user', 'receiver'])->find($id);
        if (!$movement) {
            return response()->json(["code" => 404, "message" => "No encontrado"], 404);
        }
        return response()->json(["movement" => $movement, "code" => 200]);
    }
}
