<?php

namespace App\Http\Controllers\Doctor;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function showLogin()
    {
        if (session('doctor_id')) {
            return redirect()->route('doctor.dashboard');
        }

        return view('doctor.auth.login');
    }

    public function login(Request $request)
    {
        $data = $request->validate([
            'phone' => 'required|string',
        ]);

        $user = User::findByPhone($data['phone']);

        if (! $user || $user->role !== 'doctor') {
            return back()->with('error', 'رقم الهاتف غير مسجّل كطبيب');
        }

        if (! $user->is_active) {
            return back()->with('error', 'حسابك موقوف');
        }

        $doctor = $user->doctor;
        if (! $doctor || $doctor->status !== 'active') {
            return back()->with('error', 'الحساب غير نشط أو بانتظار الموافقة');
        }

        session(['doctor_id' => $doctor->id]);

        return redirect()->route('doctor.dashboard');
    }

    public function logout()
    {
        session()->forget('doctor_id');

        return redirect()->route('login')->with('success', 'تم تسجيل الخروج');
    }
}
