<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Laravel\Socialite\Facades\Socialite;
use App\Models\User;
use Illuminate\Support\Str; // Import Str for generating random passwords
use Illuminate\Support\Facades\Log;
use App\UsersQuestion;


class LoginController extends Controller
{
    public function login(Request $request)
    {
        // Validate the request
        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        // Attempt to log the user in
        if (Auth::attempt($credentials)) {
            $user = Auth::user();

            // Check if the user's email is verified
            // if (!$user->hasVerifiedEmail()) {
            //     return response()->json([
            //         'message' => 'Please verify your email address.'
            //     ], 403);
            // }

            // Generate an API token
            $token = $user->createToken('auth_token')->plainTextToken;

            return response()->json([
                'access_token' => $token,
                'token_type' => 'Bearer',
            ]);
        }

        return response()->json([
            'message' => 'Invalid credentials'
        ], 401);
    }
    public function loginAdmin(Request $request)
{
    // Validate the request
    $credentials = $request->validate([
        'email' => 'required|email',
        'password' => 'required',
    ]);

    // Attempt to log the user in
    if (Auth::attempt($credentials)) {
        $user = Auth::user();

        // Generate an API token
        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'access_token' => $token,
            'token_type' => 'Bearer',
        ]);
    }

    return response()->json([
        'message' => 'Invalid credentials'
    ], 401);
}

    public function redirectToGoogle()
    {
        return Socialite::driver('google')
            ->stateless()
            ->redirect();
    }

// public function handleGoogleCallback(Request $request)
// {
//     try {
//         // Retrieve the user from Google
//         $googleUser = Socialite::driver('google')->stateless()->user();

//         // Check if the user already exists
//         $user = User::where('email', $googleUser->getEmail())->first();

//         if (!$user) {
//             // Create a new user if it doesn't exist
//             $user = User::create([
//                 'name' => $googleUser->getName(),
//                 'email' => $googleUser->getEmail(),
//                 'password' => bcrypt(Str::random(16)),  // random password
//                 'google_id' => $googleUser->getId(),   // Get the Google ID here
//                 'avatar' => $googleUser->getAvatar(),
//             ]);
//         } else {
//             // If the user exists, update the google_id if it is null
//             if (!$user->google_id) {
//                 $user->google_id = $googleUser->getId();
//                 $user->save();
//             }
//         }

//         // Generate an API token
//         $token = $user->createToken('auth_token')->plainTextToken;

//         return response()->json([
//             'access_token' => $token,
//             'token_type' => 'Bearer',
//             'user' => $user,
//         ]);
//     } catch (\Exception $e) {
//         return response()->json(['error' => 'Unable to authenticate.'], 500);
//     }
// }

 public function handleGoogleCallback(Request $request)
{
    try {
        $validatedData = $request->validate([
            'name' => 'max:255',
            'email' => 'required|string|email',
        ]);

        // Check if the user already exists in the database
        $user = User::firstOrCreate(
            ['email' => $validatedData['email']],
            ['name' => $validatedData['name'], 'password' => bcrypt(Str::random(16)),'platform' =>$request->input('platform')]
        );

        // Generate an API token for the user
        $token = $user->createToken('auth_token')->plainTextToken;

        // Return the access token and user details
        return response()->json([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'user' => $user,
        ]);

    } catch (\Exception $e) {
        Log::error('Google Login Error: ' . $e->getMessage());
        return response()->json(['error' => 'Unable to authenticate.'], 500);
    }
}
//  public function handleGoogleCallbackTest(Request $request)
// {
//     try {
//         $validatedData = $request->validate([
//             'name' => 'required|string|max:255',
//             'email' => 'required|string|email',
//         ]);

//         // Check if the user already exists in the database
//         $user = User::firstOrCreate(
//             ['email' => $validatedData['email']],
//             ['name' => $validatedData['name'], 'password' => bcrypt(Str::random(16)),'platform' =>$request->input('platform')]
//         );

//         // Generate an API token for the user
//         $token = $user->createToken('auth_token')->plainTextToken;

//         // Return the access token and user details
//         return response()->json([
//             'access_token' => $token,
//             'token_type' => 'Bearer',
//             'user' => $user,
//         ]);

//     } catch (\Exception $e) {
//         Log::error('Google Login Error: ' . $e->getMessage());
//         return response()->json(['error' => 'Unable to authenticate.'], 500);
//     }
// }
public function storeUserQuestions(Request $request)
    {
        $data = $request->validate([
            'questions' => 'required|json',
            'user_id' => 'required',
        ]);

            $question = new UsersQuestion();
            $question->user = $data['user_id'];
            $question->questions = $data['questions'];

            // Save the recipe to the database
            $question->save();
            
        // $question = UsersQuestion::create($data);

        return response()->json($question, 201);
    }
    public function getUserQuestions(Request $request)
{
    $request->validate([
        'user_id' => 'required'
    ]);

    $questions = UsersQuestion::where('user', $request->user_id)->get();

    return response()->json([
        'status' => true,
        'data' => $questions
    ], 200);
}
}
