<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Models\User;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'number' => 'required|digits:10',
        ]);
    
        $otp = '123456'; // Static OTP for demonstration. Replace with dynamic generation in production.
    
        // Check if user exists with the given number
        $user = User::where('number', $request->number)->first();
    
        if ($user) {
            // Update OTP for existing user
            $user->update(['otp' => $otp]);
        } else {
            // Create a new user with OTP
            $user = User::create([
                'name' => $request->name,
                'number' => $request->number,
                'otp' => $otp,
            ]);
        }
    
        return response()->json([
            'message' => 'User registered successfully. OTP has been sent.',
            'otp' => $otp, // Send OTP for testing purposes (remove in production)
        ]);
    }
    


    public function login(Request $request)
    {
        $request->validate([
            'number' => 'required|digits:10',
            'otp' => 'required|string',
        ]);
    
        // Check if user exists with the given number and OTP
        $user = User::where('number', $request->number)
                    ->where('otp', $request->otp)
                    ->first();
    
        if (!$user) {
           
            return response()->json(['message' => 'Invalid OTP'], 401);
        }
    
        // Generate token upon successful OTP verification
        $token = $user->createToken('auth_token')->plainTextToken;
    
       
    
        // Return success response with token
        return response()->json([
            'message' => 'Login successful',
            'token' => $token,
        ]);
    }


    public function login1()
    {
       
        return response()->json([
            'message' => 'invalid token',
            
        ]);
    }



    
    

}
