<?php

namespace App\Http\Controllers;

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

class AgentController extends Controller
{
    public function index()
    {
        $agents = Agent::orderBy('name')->paginate(20);
        return view('admin.agents.index', compact('agents'));
    }

    public function create()
    {
        return view('admin.agents.create');
    }

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

        $data['active'] = true;
        Agent::create($data);

        return redirect()->route('admin.agents.index')
            ->with('success', "Agent {$data['name']} added to directory.");
    }

    public function edit(Agent $agent)
    {
        return view('admin.agents.edit', compact('agent'));
    }

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

        $data['active'] = $request->has('active');
        $agent->update($data);

        return redirect()->route('admin.agents.index')
            ->with('success', "Agent {$agent->name} updated.");
    }

    public function toggleStatus(Agent $agent)
    {
        $agent->update(['active' => !$agent->active]);
        $status = $agent->active ? 'activated' : 'deactivated';

        return back()->with('success', "Agent {$agent->name} {$status}.");
    }
}
