<?php

namespace App\Http\Controllers\Secretary;

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

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

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

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

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

        if (! $user) {
            return back()->with('error', 'لا يوجد حساب بهذا الرقم');
        }

        if (! $user->is_active) {
            return back()->with('error', 'الحساب غير نشط');
        }

        $doctor = null;

        if ($user->role === 'secretary' && ! empty($user->doctor_id)) {
            $doctor = Doctor::find($user->doctor_id);
        } elseif (in_array($user->role, ['doctor', 'admin'], true)) {
            $doctor = $user->doctor;
            if (! $doctor) {
                $secretary = Secretary::where('user_id', $user->id)->first();
                if ($secretary) {
                    $doctor = Doctor::find($secretary->doctor_id);
                }
            }
        }

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

        session([
            'secretary_user_id'   => $user->id,
            'secretary_doctor_id' => $doctor->id,
            'current_doctor_id'   => $doctor->id,
        ]);

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

    public function logout()
    {
        session()->forget([
            'secretary_user_id',
            'secretary_doctor_id',
            'current_doctor_id',
        ]);

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