<?php

namespace App\Http\Controllers;

use App\Models\Buyer;
use App\Models\Bank;

use Illuminate\Http\Request;

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


    public function orderHistory($id)
{
    $buyer = Buyer::with('orders')->findOrFail($id);
    return view('admin.buyers.order-history', compact('buyer'));
}


    public function create()
    {
        $banks = Bank::all(); // show available banks in dropdown

        return view('admin.buyers.create', compact('banks'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'company_name' => 'required',
            'contact_person' => 'required',
            'email' => 'required|email|unique:buyers',
            'phone' => 'nullable|string|max:20',
            'fax' => 'nullable|string|max:20',
            'vat' => 'nullable|string|max:20',
            'address' => 'nullable|string',
            'country' => 'nullable|string|max:100',
            'bank_id' => 'nullable|exists:banks,id', // selected bank


        ], [
    'email.unique' => 'This email is already taken.',
]);

        Buyer::create($request->all());
        return redirect()->route('admin.buyers.index')->with('success', 'Buyer created successfully.');
    }

    public function edit(Buyer $buyer)
    {
         $banks = Bank::all();
        return view('admin.buyers.edit', compact('buyer','banks'));
    }

    public function update(Request $request, Buyer $buyer)
    {
        $request->validate([
            'company_name' => 'required',
            'contact_person' => 'required',
            'email' => 'required|email|unique:buyers,email,' . $buyer->id,
            'phone' => 'nullable|string|max:20',
               'fax' => 'nullable|string|max:20',
            'vat' => 'nullable|string|max:20',
            'address' => 'nullable|string',
            'country' => 'nullable|string|max:100',
                        'bank_id' => 'nullable|exists:banks,id',

        ], [
    'email.unique' => 'This email is already taken.',
]);

        $buyer->update($request->all());
        return redirect()->route('admin.buyers.index')->with('success', 'Buyer updated successfully.');
    }

    public function destroy(Buyer $buyer)
    {
        $buyer->delete();
        return redirect()->route('admin.buyers.index')->with('success', 'Buyer deleted successfully.');
    }
}
