<?php

namespace App\Http\Controllers;

use App\Models\Supplier;
use Illuminate\Http\Request;

class SupplierController extends Controller
{
    public function index(Request $request) { $suppliers = Supplier::when($request->search, fn ($q, $s) => $q->where('name', 'like', "%{$s}%")->orWhere('phone', 'like', "%{$s}%"))->latest()->paginate(15); return view('suppliers.index', compact('suppliers')); }
    public function create() { return view('suppliers.form', ['supplier' => new Supplier()]); }
    public function store(Request $request) { Supplier::create($this->data($request)); return redirect()->route('suppliers.index')->with('success', __('Supplier saved successfully.')); }
    public function edit(Supplier $supplier) { return view('suppliers.form', compact('supplier')); }
    public function update(Request $request, Supplier $supplier) { $supplier->update($this->data($request)); return redirect()->route('suppliers.index')->with('success', __('Supplier updated successfully.')); }
    public function destroy(Supplier $supplier) { $supplier->delete(); return back()->with('success', __('Supplier removed.')); }
    private function data(Request $request): array { return $request->validate(['name' => ['required', 'string', 'max:120'], 'phone' => ['nullable', 'string', 'max:30'], 'email' => ['nullable', 'email'], 'address' => ['nullable', 'string', 'max:255'], 'opening_balance' => ['nullable', 'numeric'], 'notes' => ['nullable', 'string']]); }
}
