<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\Buyer;
use Illuminate\Http\Request;

class BuyerController extends Controller
{
    public function index()
    {
        $buyers = Buyer::latest()->paginate(10);
        return view('superadmin.buyers.index', compact('buyers'));
    }

    public function create()
    {
        return view('superadmin.buyers.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|unique:buyers,code|max:50',
            'address' => 'nullable|string',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
        ]);

        Buyer::create($request->all());

        return redirect()->route('superadmin.buyers.index')->with('success', 'Buyer berhasil ditambahkan!');
    }

    public function edit(Buyer $buyer)
    {
        return view('superadmin.buyers.edit', compact('buyer'));
    }

    public function update(Request $request, Buyer $buyer)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:buyers,code,' . $buyer->id,
            'address' => 'nullable|string',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
        ]);

        $buyer->update($request->all());

        return redirect()->route('superadmin.buyers.index')->with('success', 'Buyer berhasil diupdate!');
    }

    public function destroy(Buyer $buyer)
    {
        $buyer->delete();
        return redirect()->route('superadmin.buyers.index')->with('success', 'Buyer berhasil dihapus!');
    }
}