<?php

namespace App\Http\Controllers\Assets\Settings;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\TeqtivityUsers\StoreTeqtivityUser;
use App\Http\Requests\TeqtivityUsers\UpdateTeqtivityUser;
use App\Models\AssetHistory;
use App\Services\Settings\TeqtivityUserService;
use App\User;
use Illuminate\Support\Facades\Password;
use Exception;
use Illuminate\Support\Facades\DB;

class TeqtivityUserController extends Controller
{
    private $teqtivityUserService;

    public function __construct(TeqtivityUserService $teqtivityUserService)
    {
        $this->teqtivityUserService = $teqtivityUserService;
    }

    /**
     * List all teqtivity users
     * 
     * @return view
     */
    public function index()
    {
        $teqtivityUsers = User::teqtivityUser()->get();
        return view('settings.teqtivity-users.teqtivity-users', compact('teqtivityUsers'));
    }

    /**
     * Stores the new teqtivity user
     * @param StoreTeqtivityUser $request
     * 
     * @return [type]
     */
    public function store(StoreTeqtivityUser $request)
    {
        $data = $request->only(['first_name', 'last_name', 'email', 'password', 'user_type_id']);
        $user = User::create($data);

        $user->assignRole($user->userType->name);

        Password::sendResetLink(array('email' => $data['email']));

        $this->teqtivityUserService->createHistory('teq_user_created', $user);

        return redirect('/teqtivity-users')->with('message', __('message.user_created'));
    }

    /**
     * Updates the teqtivity user
     * @param UpdateTeqtivityUser $request
     * 
     * @return [type]
     */
    public function update(UpdateTeqtivityUser $request)
    {
        $data = $request->only(['status']);

        $user = User::findOrFail($request->id);

        $user->update($data);

        return redirect('/teqtivity-users')->with('message', __('message.user_updated'));
    }

    /**
     * handles the reset password operation
     * @param mixed $id
     * 
     * @return [type]
     */
    public function resetPassword($id)
    {
        $user = User::findOrFail($id);

        Password::sendResetLink(array('email' => $user->email));

        return redirect('/teqtivity-users')->with('message', __('message.password_reset'));
    }

    /**
     * Delete the teqtivity user
     * 
     * @return [type]
     */
    public function delete()
    {
        $user = User::findOrFail(request('user_id'));
        $canbeDeleted = true;
        if ($this->checkUserHistoryExists()) {
            $canbeDeleted = $this->updateUserAssetHistory();
        }
        if ($canbeDeleted) {
            $this->teqtivityUserService->createHistory('teq_user_deleted', $user);
            $user->delete();
            return redirect('/teqtivity-users')->with('message', __('message.deleted'));
        }
        return redirect('/teqtivity-users')->with('error', 'Operation failed.');
    }


    /**
     * check asset history exists for selected user
     * 
     * @return [type]
     */
    public function checkUserHistoryExists()
    {
        $userId = request('user_id');
        $userHistoryCount = AssetHistory::select('id')->where(function ($query) use ($userId) {
            $query->where('user_id', $userId)
                ->orWhere('old_user_id', $userId)
                ->orWhere('new_user_id', $userId);
        })->count();

        if ($userHistoryCount > 0) {
            return true;
        }
        return false;
    }

    /**
     * update deleted user asset history to selected user
     * 
     * @return void
     */
    public function updateUserAssetHistory()
    {
        try {
            AssetHistory::where('user_id', request('user_id'))->update(['user_id' => request('history_assigned_to')]);

            AssetHistory::where('old_user_id', request('user_id'))->update(['old_user_id' => request('history_assigned_to')]);

            AssetHistory::where('new_user_id', request('user_id'))->update(['new_user_id' => request('history_assigned_to')]);

            return true;
        } catch (Exception $e) {
            return false;
        }
    }
}
