<?php

namespace App\Http\Controllers\admin;

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

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

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

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

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

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

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

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