<?php

namespace App\Http\Controllers;

use App\ApiClasses\Error;
use App\ApiClasses\Success;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use OwenIt\Auditing\Models\Audit;
use Spatie\Permission\Models\Role;

class AccountController extends Controller
{
    public function myProfile()
    {
        $user = User::find(auth()->user()->id);

        $auditLogs = Audit::where('user_id', auth()->user()->id)
            ->where('auditable_type', 'App\Models\User')
            ->orderBy('created_at', 'desc')
            ->get();

        $role = $user->roles()->first();

        return view('account.my-profile', [
            'user' => $user,
            'auditLogs' => $auditLogs,
            'role' => $role,
        ]);
    }

    public function getRolesAjax()
    {
        $roles = Role::get();

        return Success::response($roles);
    }

    public function getUsersByRoleAjax($role)
    {
        if (! $role) {
            return Error::response('Role is required');
        }

        if ($role == 'all') {
            $users = User::activeEmployees()->get();

            return Success::response($users);
        }

        $role = Role::find($role);

        $users = $role->users()->activeEmployees()->get();

        return Success::response($users);
    }

    public function getUsersAjax()
    {
        $users = User::activeEmployees()
            ->where('id', '!=', auth()->user()->id)
            ->get();

        return Success::response($users);
    }

    public function changePassword(Request $request)
    {

        if (config('app.demo')) {
            return Error::response('This feature is disabled in the demo.');
        }

        $request->validate([
            'oldPassword' => 'required|min:8',
            'newPassword' => 'required|min:8',
        ]);

        if (! (Hash::check($request->oldPassword, auth()->user()->password))) {
            return redirect()->back()->with('error', 'Your current password does not matches with the password you provided. Please try again.');
        }

        $user = User::find(auth()->user()->id);
        $user->password = bcrypt($request->newPassword);
        $user->save();

        return redirect()->back()->with('success', 'Password changed successfully');
    }
}
