<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Doctor;
use App\Models\Patient;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    // ===== تسجيل مريض جديد (بانتظار تفعيل الإدارة) =====
    public function registerPatient(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name'          => 'required|string|max:100',
            'email'         => 'nullable|email|unique:users,email',
            'phone'         => 'required|string|unique:users,phone',
            'date_of_birth' => 'nullable|date',
            'gender'        => 'nullable|in:male,female',
        ]);

        $email = ! empty($data['email']) ? $data['email'] : null;

        $user = User::create([
            'name'      => $data['name'],
            'email'     => $email,
            'phone'     => $data['phone'],
            'password'  => User::randomPasswordHash(),
            'role'      => 'patient',
            'is_active' => false,
        ]);

        Patient::create([
            'user_id'       => $user->id,
            'date_of_birth' => $data['date_of_birth'] ?? null,
            'gender'        => $data['gender'] ?? null,
        ]);

        return response()->json([
            'message' => 'تم إنشاء الطلب. سيتم تفعيل حسابك من الإدارة — بعدها يمكنك تسجيل الدخول برقم الهاتف.',
            'user'    => $user->load('patient'),
        ], 201);
    }

    // ===== تسجيل طبيب جديد =====
    public function registerDoctor(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name'            => 'required|string|max:100',
            'email'           => 'nullable|email|unique:users,email',
            'phone'           => 'required|string|unique:users,phone',
            'specialty'       => 'required|string|max:100',
            'license_number'  => 'required|string|unique:doctors,license_number',
            'clinic_name'     => 'nullable|string',
            'clinic_address'  => 'nullable|string',
            'latitude'        => 'nullable|numeric|between:-90,90',
            'longitude'       => 'nullable|numeric|between:-180,180',
            'city'            => 'nullable|string',
        ]);

        $email = ! empty($data['email']) ? $data['email'] : null;

        $user = User::create([
            'name'      => $data['name'],
            'email'     => $email,
            'phone'     => $data['phone'],
            'password'  => User::randomPasswordHash(),
            'role'      => 'doctor',
        ]);

        Doctor::create([
            'user_id'        => $user->id,
            'specialty'      => $data['specialty'],
            'license_number' => $data['license_number'],
            'clinic_name'    => $data['clinic_name'] ?? null,
            'clinic_address' => $data['clinic_address'] ?? null,
            'latitude'       => $data['latitude'] ?? null,
            'longitude'      => $data['longitude'] ?? null,
            'city'           => $data['city'] ?? null,
            'status'         => 'pending',
        ]);

        return response()->json([
            'message' => 'تم التسجيل، يرجى انتظار موافقة الإدارة',
            'user'    => $user->load('doctor'),
        ], 201);
    }

    // ===== تسجيل الدخول — رقم الهاتف فقط =====
    public function login(Request $request): JsonResponse
    {
        $data = $request->validate([
            'phone' => 'required|string',
        ]);

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

        if (! $user) {
            throw ValidationException::withMessages([
                'phone' => ['لا يوجد حساب بهذا الرقم'],
            ]);
        }

        if (! $user->is_active) {
            $msg = $user->role === 'patient'
                ? 'حسابك غير مفعّل — انتظر موافقة الإدارة'
                : 'حسابك موقوف';

            return response()->json(['message' => $msg], 403);
        }

        if ($user->role === 'doctor') {
            $doctor = $user->doctor;
            if (! $doctor || $doctor->status !== 'active') {
                return response()->json(['message' => 'حساب الطبيب غير نشط أو قيد المراجعة'], 403);
            }
        }

        $user->tokens()->delete();

        $tokenName = $user->role . '-token';
        $token = $user->createToken($tokenName)->plainTextToken;

        $userData = match ($user->role) {
            'doctor'  => $user->load('doctor'),
            'patient' => $user->load('patient'),
            default   => $user,
        };

        return response()->json([
            'message' => 'تم تسجيل الدخول بنجاح',
            'token'   => $token,
            'user'    => $userData,
        ]);
    }

    // ===== تسجيل الخروج =====
    public function logout(Request $request): JsonResponse
    {
        $request->user()->currentAccessToken()->delete();

        return response()->json(['message' => 'تم تسجيل الخروج']);
    }

    // ===== نسيان كلمة المرور =====
    public function forgotPassword(Request $request): JsonResponse
    {
        $request->validate(['email' => 'required|email|exists:users,email']);

        return response()->json(['message' => 'تم إرسال رابط إعادة تعيين كلمة المرور']);
    }

    // ===== إعادة تعيين كلمة المرور =====
    public function resetPassword(Request $request): JsonResponse
    {
        $request->validate([
            'email'    => 'required|email',
            'token'    => 'required|string',
            'password' => 'required|string|min:8|confirmed',
        ]);

        return response()->json(['message' => 'تم تغيير كلمة المرور بنجاح']);
    }
}
