<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use App\Models\Cart;

class AuthController extends Controller
{
    //
    public function show_login(){
        if(Auth::check()){
            return redirect(route('home'));
        }
        return View('auth.login');
    }

    public function Login(Request $request){
        $request->validate([
            'email' =>'required',
            'password' =>'required',
        ]);
        $credentials=$request->only('email','password');
       
        if(Auth::attempt($credentials)){
            if(session()->get('temp_user_id')){
                $temp_user_id= $request->session()->get('temp_user_id');
                 $cart=Cart::where('temp_user_id', $temp_user_id)->get();
                 foreach ($cart as $key => $cartitems) {
                     $cartitem = Cart::find($cartitems->id); // Find the user by ID
                     $cartitem->user_id =  Auth::user()->id;
                     $cartitem->save(); 
                 }
             }
            $request->session()->regenerateToken();
            return redirect(route('home'))->with("success","Welcome Back");
        }
        return redirect(route('login'))->with("error","Login Details are not velid");

    }

    public function logout(){
        Session::flush();
        request()->session()->invalidate();
        Auth::logout();

        return redirect(route('login'));
    }


    
    public function show_register(){

        return View('auth.register');
    }
    public function register(Request $request){
        $request->validate([
        'firstname' => 'required|string|max:255',
        'lastname'  => 'required|string|max:255',
        'email'     => 'required|email|unique:users',
        'phone'     => 'required|numeric',
        'password'  => 'required|confirmed|min:6',
    ]);
     if($request->password != $request->password_confirmation){
            return redirect(route('register'))->with("error","password can't match");
        }

    $user = User::create([
        'first_name' => $request->firstname,
        'last_name'  => $request->lastname,
        'email'      => $request->email,
        'phone'      => $request->phone,
        'password'   => Hash::make($request->password),
    ]);


       
        
        
        if(!$user){
            return redirect(route('register'))->with("error","Registration Failed");
        }
        return $this->Login($request);
        //return redirect(route('login'))->with("Success","Registration Successfully");
       
    }
}
