<?php

namespace App\Http\Controllers;

use App\Models\Agent;
use App\Models\Currency;
use Illuminate\Http\Request;

class AgentController extends Controller
{
    public function index()
    {
        $agents = Agent::orderBy('name')->get();
        $currencies = Currency::orderBy('code')->get();
        return view('agents.index', compact('agents', 'currencies'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'country' => ['nullable', 'string', 'max:255'],
        ]);

        Agent::create($data);

        return redirect()->route('agents.index')->with('success', 'Agent created successfully.');
    }

    public function edit(Agent $agent)
    {
        $currencies = Currency::orderBy('code')->get();
        return view('agents.edit', compact('agent', 'currencies'));
    }

    public function update(Request $request, Agent $agent)
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'country' => ['nullable', 'string', 'max:255'],
        ]);

        $agent->update($data);

        return redirect()->route('agents.index')->with('success', 'Agent updated successfully.');
    }

    public function destroy(Agent $agent)
    {
        if ($agent->transactions()->exists()) {
            return redirect()->route('agents.index')->with('error', 'Cannot delete agent with existing transactions.');
        }

        $agent->delete();

        return redirect()->route('agents.index')->with('success', 'Agent deleted successfully.');
    }
}
