<?php

namespace App\Http\Controllers;

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

class UserController extends Controller
{
    public function addUser(Request $request)
    {
        $this->validate($request, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'unique:users'],
            'password' => ['required', 'string', 'min:8'],
        ]);
        
        $company = getSelectedCompany();

        $user = new User;
        $user->role_id = 3;
        $user->name = $request->name;
        $user->email = $request->email;
        $user->password = Hash::make($request->password);
        $user->save();
        
        //Update Company User
        CompanyUser::updateOrCreate([
            'user_id' => $user->id
        ],[
            'user_id' => $user->id,
            'company_id' => $company,
            'access' => json_encode($request->access)
        ]);

        return redirect()->back()->with('success', 'User Added Successfully');
    }

    public function deleteUser($id)
    {
        $user = User::find($id);
        $user->delete();
        return redirect()->back()->with('success', 'User Deleted Successfully');
    }
    
    public function updateChatAvailability(Request $request)
    {
        $user = Auth::user();
        
        //update user
        if($request->status == "on") {
            $user->is_available = 1;
            $user->save();
        } else {
            $user->is_available = 0;
            $user->save();
        }
        
        return response()->json(['success' => 'Updated Successfully']);
    }
    
    public function updateLastOnline()
    {
        $user = Auth::user();
        
        //update last online
        $user->last_online = Carbon::now();
        $user->save();
        
        return response()->json(['success' => true]);
    }
}
