<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Tenant\Supplier;

class SupplierController extends Controller
{
    public function index()
    {
        $suppliers = Supplier::orderBy('name')->paginate(10);
        return view('tenant.inventory.suppliers.index', compact('suppliers'));
    }

    public function create()
    {
        return view('tenant.inventory.suppliers.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'contact' => 'nullable|string|max:255',
            'email' => 'nullable|email|max:255',
        ]);
        Supplier::create($validated);
        return redirect()->route('tenant.suppliers.index')->with('success', 'Supplier created successfully.');
    }

    public function edit($id)
    {
        $supplier = Supplier::on('tenant')->findOrFail($id);
        return view('tenant.inventory.suppliers.edit', compact('supplier'));
    }

    public function update(Request $request, $id)
    {
        $supplier = Supplier::on('tenant')->findOrFail($id);
        
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'contact' => 'nullable|string|max:255',
            'email' => 'nullable|email|max:255',
        ]);
        $supplier->update($validated);
        return redirect()->route('tenant.suppliers.index')->with('success', 'Supplier updated successfully.');
    }

    public function destroy($id)
    {
        $supplier = Supplier::on('tenant')->findOrFail($id);
        $supplier->delete();
        return redirect()->route('tenant.suppliers.index')->with('success', 'Supplier deleted successfully.');
    }
}
