<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Cart;
use App\Models\PendingUser;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;

class LoginRegisterController extends Controller
{
    public function loginRegisterForm()
    {
        return view('auth.login-register');
    }

    public function register(Request $request)
    {
        $randomString = Str::random(100);
        $email = $request->email;
        $password = $request->password;
        $name = $request->name;

        try {
            DB::beginTransaction();

            PendingUser::create([
                'name' => $name,
                'email' => $email,
                'password' => Hash::make($password),
                'token' => $randomString,
                'contact_number' => $request->contact_number
            ]);

            Mail::send('emails.email_verification', ['token' => $randomString], function ($message) use ($email) {
                $message->to($email, $email)
                    ->subject('Email Verification');
            });

            DB::commit(); // Commit the transaction if everything was successful.
            
            if($request->wantsJson())
            {
                return response()->json(['status'=>200,'message'=>'A verification email has been sent to your email. Please check!']);
            }

            return redirect()->route('home')->with('success', 'A verification email has been sent to your email. Please check');
        } catch (\Throwable $th) {
            DB::rollBack(); // Rollback the transaction in case of an error.
            if($request->wantsJson())
            {
                return response()->json(['status'=>201,'message'=>'There is an error in the registration process']);
            }
            // You can log the error or return an error message if needed.
            return redirect()->route('home')->with('error', 'An error occurred during registration.');
        }
    }

    public function verifyEmail(Request $request)
    {
        try {
            DB::beginTransaction();
            $token = $request->token;

            $pending_user = PendingUser::where('token', $token)->first();

            if ($pending_user) {
                $user = User::create([
                    'name' => $pending_user->name,
                    'password' => $pending_user->password,
                    'email' => $pending_user->email,
                    'contact_number' => $pending_user->contact_number
                ]);

                $pending_user->delete();

                Cart::where('session_id', session()->getId())->update(['user_id' => $user->id, 'session_id' => null]);

                DB::commit(); // Commit the transaction if everything was successful.

                return redirect()->route('home')->with('success', 'Your email has been verified. You can now login to your account.');
            }
        } catch (\Throwable $th) {
            DB::rollBack(); // Rollback the transaction in case of an error.
            // You can log the error or return an error message if needed.
            return redirect()->route('home')->with('error', 'An error occurred during registration.');
        }
    }

    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if ($request->wantsJson()) {
            if (!$token = auth()->attempt($credentials)) {
                return response()->json(['error' => 'Unauthorized'], 401);
            }
            $user = auth()->user(); // Use auth()->user() to get the authenticated user
            Cart::where('session_id', $request->session_id)->update(['user_id' => $user->id, 'session_id' => null]);
            return $this->respondWithToken($token, $user);
        }

        if (Auth::attempt($credentials)) {
            // Authentication passed
            $user = Auth::user(); // Use Auth::user() to get the authenticated user
            Cart::where('session_id', session()->getId())->update(['user_id' => $user->id, 'session_id' => null]);
            return redirect()->intended('/'); // Redirect to a protected page
        }

        return back()->withErrors(['email' => 'Invalid credentials']);
    }


    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token, $user)
    {
        return response()->json([
            'token' => $token,
            'user' => $user,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 6000
        ]);
    }

    public function logout()
    {
        Auth::logout();

        return redirect('/'); // Redirect to the login page
    }
}