<?php

namespace App\Http\Controllers;

use Exception;
use Illuminate\Http\Request;
use App\Models\Warehouse;
use Illuminate\Support\Facades\Validator;

class WarehouseController extends Controller
{
    // Show form and list of warehouses
    public function create_warehouse()
    {
        $warehouses = Warehouse::all();
        return view('maintanance.inventory.create_warehouse', compact('warehouses'));
    }

    // Store new warehouse
    public function store_warehouse(Request $request)
    {
        try {
            $request->validate([
                'code' => 'required|string|max:255|unique:warehouses,code',
                'description' => 'nullable|string|max:255',
            ], [
                'code.unique' => 'The code you entered already exists. Please use a different code.',
            ]);

            $warehouse = new Warehouse();
            $warehouse->code = $request->code;
            $warehouse->description = $request->description;
            $warehouse->save();

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

    // Edit warehouse
    public function edit_warehouse(Request $request)
    {
        try {
            $request->validate([
                'id' => 'required|integer|exists:warehouses,id',
                'code' => 'required|string|max:255',
                'description' => 'nullable|string|max:255',
            ]);

            $warehouse = Warehouse::findOrFail($request->id);
            $warehouse->code = $request->code;
            $warehouse->description = $request->description;
            $warehouse->save();

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

    // Delete warehouse
    public function delete_warehouse($id)
    {
        try {
            $warehouse = Warehouse::findOrFail($id);
            $warehouse->delete();

            return redirect()->route('supplier.warehouses.create')->with('success', 'Warehouse deleted successfully.');
        } catch (Exception $e) {
            return redirect()->route('supplier.warehouses.create')->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }
    
}
