<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class AutoLoginController extends Controller
{
    public function emailLogin(Request $request)
    {
        // dd($request->user_id);
        try {
            // Decrypt the token
            $decryptedToken = Crypt::decryptString($request->user_id);
            // dd($decryptedToken);
            // Retrieve the user based on the decrypted ID
            $user = User::where('id', unserialize($decryptedToken))->first();
            
            if ($user !== null) {
                // Automatically log in the user without requiring the password (since you trust the token)
                Auth::login($user);

                // Generate a token (if using JWT or similar system)
                $token = Auth::tokenById($user->id);  // If you're using JWT, use this for token generation

                // Assuming the profile picture URL is needed, and `employee_profile_picture_url` is an accessor in the User model
                $profilePictureUrl = $user->employee_profile_picture; // This accessor should be defined in the User model

                // Prepare user data with profile picture URL
                $userData = $user->toArray();
                $userData['profile_picture_url'] = $profilePictureUrl ? asset('storage/employee-profile/' . $profilePictureUrl->attachment) : '';

                // dd($userData);

                return response()->json([
                    'user' => $userData,
                    'authorization' => [
                        'token' => $token,
                        'type' => 'bearer',
                    ]
                ]);
            } else {
                return response()->json(['error' => 'User not found.'], 404);
            }
        } catch (\Exception $e) {
            return response()->json(['error' => 'Invalid token or an error occurred.', 'details' => $e->getMessage()], 400);
        }
    }

}

