<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\JsonResponse;
use App\Models\UserStudent;

class AuthController extends Controller
{
    /**
     * Retourne l'utilisateur connecté (compatible User & UserStudent)
     */
    public function me(Request $request): JsonResponse
    {
        try {
            $user = $request->user();

            if (!$user) {
                return response()->json([
                    'valid' => false,
                    'message' => 'Utilisateur non authentifié'
                ], 401);
            }

            // 🔍 Vérifier si c’est un étudiant
            if ($user instanceof UserStudent) {

                $inscription = DB::connection('tenant')
                    ->table('tabinscription')
                    ->where('matricule', $user->matricule)
                    ->first();

                $info = DB::connection('tenant')
                    ->table('tabetudiant')
                    ->where('matricule', $user->matricule)
                    ->first();

                return response()->json([
                    'valid' => true,
                    'type' => 'student',
                    'username' => $user->username,
                    'nom' => $info->nom ?? null,
                    'prenom' => $info->prenom ?? null,
                    'email' => $user->email,
                    'type_user' => $user->type_user,
                    'matricule' => $user->matricule,
                    'id_filiere' => $inscription->idFiliere ?? null,
                    'annee' => $inscription->annee ?? null
                ]);
            }

            // 🔹 Cas utilisateur normal
            $info = DB::connection('mysql')
                ->table('geststudent_r')
                ->where('email', $user->email)
                ->first();

            return response()->json([
                'valid' => true,
                'type' => 'user',
                'username' => $user->username,
                'nom' => $info->nom ?? null,
                'prenom' => $info->prenom ?? null,
                'email' => $user->email,
                'type_user' => $user->type_user,
                'matricule' => $user->matricule
            ]);

        } catch (\Throwable $e) {

            return response()->json([
                'valid' => false,
                'message' => 'Erreur interne',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}