<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|unique:users',
            'country_code' => 'required|string|max:5',
            'telephone' => 'required|string|max:15|unique:users',
            'password' => ['required', 'confirmed', Password::min(8)->mixedCase()->numbers()],
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'country_code' => $request->country_code,
            'telephone' => $request->telephone,
            'password' => Hash::make($request->password),
        ]);

        $otp = $user->generateOtp();
        // Envoyer l'OTP par SMS/Email ici

        return response()->json([
            'message' => 'Inscription réussie. OTP envoyé.',
            'data' => $user->only(['id', 'name', 'email', 'telephone'])
        ], 201);
    }

    public function verifyOtp(Request $request)
    {
        $request->validate([
            'telephone' => 'required|string',
            'otp_code' => 'required|numeric|digits:6'
        ]);

        $user = User::where('telephone', $request->telephone)->firstOrFail();

        if (!$user->verifyOtp($request->otp_code)) {
            return response()->json([
                'message' => 'OTP invalide ou expiré'
            ], 400);
        }

        return response()->json([
            'message' => 'OTP vérifié avec succès',
            'token' => $user->createToken('mobile-auth')->plainTextToken
        ]);
    }

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

        $user = User::where('telephone', $request->telephone)->first();

        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->json([
                'message' => 'Identifiants incorrects'
            ], 401);
        }

        if (!$user->otp_verified_at) {
            $otp = $user->generateOtp();
            // Renvoyer l'OTP
            return response()->json([
                'message' => 'OTP requis pour la connexion',
                'requires_otp' => true
            ], 403);
        }

        return response()->json([
            'token' => $user->createToken('mobile-auth')->plainTextToken,
            'user' => $user->only(['id', 'name', 'email', 'telephone'])
        ]);
    }
}
// }
