<?php

namespace App\Http\Controllers;

use Exception;
use Illuminate\Http\Request;
use App\Models\UomConversion;
use App\Models\Uom;
use App\Models\UomCategory;

class UomConversionController extends Controller
{
    /**
     * Display the form to create a new conversion and list existing conversions.
     */
    public function index()
    {
        $uom_categories = UomCategory::all();
        $uoms = Uom::all();
        $conversions = UomConversion::with(['fromUnit', 'toUnit', 'category'])->get();
        return view('maintanance.inventory.create_conversion', compact('uom_categories', 'uoms', 'conversions'));
    }

    /**
     * Store a newly created conversion.
     */
    public function store(Request $request)
    {
        try {
            // Validate input
            $request->validate([
                'uom_category_id' => 'required|integer|exists:uom_categories,id',
                'from_uom_id'     => 'required|integer|exists:uoms,id',
                'to_uom_id'       => 'required|integer|exists:uoms,id|different:from_uom_id',
                'factor'          => 'required|numeric|gt:0',
            ]);

            // Ensure UOMs belong to selected category
            $from = Uom::find($request->from_uom_id);
            $to   = Uom::find($request->to_uom_id);
            if (!$from || !$to
                || $from->uom_category_id != $request->uom_category_id
                || $to->uom_category_id   != $request->uom_category_id
            ) {
                return redirect()->back()
                    ->withErrors(['error' => 'Selected units must belong to the chosen category.'])
                    ->withInput();
            }

            UomConversion::create([
                'uom_category_id' => $request->uom_category_id,
                'from_uom_id'     => $request->from_uom_id,
                'to_uom_id'       => $request->to_uom_id,
                'factor'          => $request->factor,
            ]);

            return redirect()->route('uom_conversions.index')
                             ->with('success', 'Conversion created successfully.');
        } catch (Exception $e) {
            return redirect()->back()
                             ->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }

    /**
     * Update an existing conversion.
     * Expects 'id' in the request.
     */
    public function edit(Request $request)
    {
        try {
            $request->validate([
                'id'              => 'required|integer|exists:uom_conversions,id',
                'uom_category_id' => 'required|integer|exists:uom_categories,id',
                'from_uom_id'     => 'required|integer|exists:uoms,id',
                'to_uom_id'       => 'required|integer|exists:uoms,id|different:from_uom_id',
                'factor'          => 'required|numeric|gt:0',
            ]);

            $conv = UomConversion::findOrFail($request->id);

            // Ensure UOMs belong to selected category
            $from = Uom::find($request->from_uom_id);
            $to   = Uom::find($request->to_uom_id);
            if ($from->uom_category_id != $request->uom_category_id
                || $to->uom_category_id   != $request->uom_category_id
            ) {
                return redirect()->back()
                    ->withErrors(['error' => 'Selected units must belong to the chosen category.'])
                    ->withInput();
            }

            $conv->uom_category_id = $request->uom_category_id;
            $conv->from_uom_id     = $request->from_uom_id;
            $conv->to_uom_id       = $request->to_uom_id;
            $conv->factor          = $request->factor;
            $conv->save();

            return redirect()->route('uom_conversions.index')
                             ->with('success', 'Conversion updated successfully.');
        } catch (Exception $e) {
            return redirect()->back()
                             ->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }

    /**
     * Delete a conversion by ID.
     */
    public function delete($id)
    {
        try {
            $conv = UomConversion::findOrFail($id);
            $conv->delete();
            return redirect()->route('uom_conversions.index')
                             ->with('success', 'Conversion deleted successfully.');
        } catch (Exception $e) {
            return redirect()->route('uom_conversions.index')
                             ->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }
}
