<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\Telemedpro;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;

class AgentController extends Controller
{
    public function index()
    {
        $agents = Telemedpro::all();
        return  view('admin.agents.index', ['agents' => $agents]);
    }

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

    public function save(Request $request)
    {
        $agent = Telemedpro::where('email',$request->input('email'))->first();
        if($agent)
        {
            $request->session()->flash('error', 'The email has already been taken.');
            return redirect()->back();
        }
        Telemedpro::create([
            'name' => $request->input('name'),
            'email' => $request->input('email'),
            'password' => bcrypt($request->input('password')),
        ]);
        $request->session()->flash('message', 'Agent created successfully');
        return redirect()->back();
    }

    public function edit($id)
    {
        $agent = Telemedpro::where('id',$id)->first();
        return  view('admin.agents.edit', ['agent' => $agent]);
    }

    public function update($id,Request $request)
    {
        $agent = Telemedpro::where('id',$id)->first();
        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:telemed_pros,email,' . $id,
            // Other validation rules...
        ]);
        $agent->name = $request->input('name');
        $agent->email = $request->input('email');
        if($request->input('password'))
            $agent->password = $request->input('password');
        $agent->save();

        $request->session()->flash('message', 'Agent updated successfully');
        return redirect()->back();
    }

    public function delete($id,Request $request)
    {
        Telemedpro::where('id',$id)->delete();
        $request->session()->flash('message', 'Agent deleted successfully');
        return redirect()->back();
    }
}
