<?php

namespace Modules\User\Http\Controllers;

use App\Classes\Dynamics\Models\Customer;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Facades\Excel;
use Modules\Company\Entities\Company;
use Modules\Country\Entities\Country;
use Modules\User\Entities\User;
use Modules\User\Exports\UsersExport;
use Modules\User\Http\Requests\UserRequest;
use Modules\User\Notifications\AccountRegistered;
use Str;

class AdminController extends Controller
{
    public function __construct()
    {
        $this->authorizeResource(User::class, 'user');
    }

    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = User::query()
                ->with(['country'])
                ->filters($request);

            return User::makeDataTable($data);
        }

        return view('user::admin.index', [
            // 'countries' => Country::has('filteredUsers')->orderBy('name')->pluck('name', 'id'),
        ]);
    }

    public function trashed(Request $request)
    {
        $this->authorize('restore', User::class);

        if ($request->ajax()) {
            $data = User::query()
                ->with(['country'])
                ->onlyTrashed();

            return User::makeDataTable($data, trash: true);
        }

        return view('user::admin.trashed');
    }

    /**
     * Show the form for creating a new resource.
     * @return Renderable
     */
    public function create()
    {
        return view('user::admin.create', [
            'user' => new User(),
        ]);
    }

    /**
     * Store a newly created user in storage
     *
     * @param  \Modules\User\Http\Requests\UserRequest $request
     * @param  \Modules\User\Entities\User $user
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(UserRequest $request, User $user)
    {
        $new_password = generate_password();

        /** @var User $new_user */
        $new_user = $user->create(array_merge($request->validated(), [
            'picture' => upload_file($request, 'photo', 'avatars'),
            'is_active' => $request->boolean('is_active'),
            'password' => Hash::make($new_password),
            // 'email_verified_at' => now(),
        ]));

        try {
            $new_user->notify(new AccountRegistered($new_password));
        } catch (\Exception $e) {
            report($e);
        }

        return redirect()->route('user.index')->withStatus(__('New user successfully created.'));
    }

    /**
     * Show the form for editing the specified user
     *
     * @param  \Modules\User\Entities\User $user
     * @return \Illuminate\View\View
     */
    public function edit(User $user)
    {
        return view('user::admin.edit', [
            'user' => $user,
        ]);
    }

    /**
     * Update the specified user in storage
     *
     * @param  \Modules\User\Http\Requests\UserRequest $request
     * @param  \Modules\User\Entities\User $user
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(UserRequest $request, User $user)
    {
        $input = array_merge($request->validated(), [
            'picture' => upload_file($request, 'photo', 'avatars', $user->picture),
            'is_active' => $request->boolean('is_active'),
        ]);

        data_forget($input, 'password');

        $user->update($input);

        if ($request->filled('password')) {
            $user->password = Hash::make($request->get('password'));
            $user->save();
        }

        return redirect()->route('user.index')->withStatus(__("User #$user->id successfully updated."));
    }

    /**
     * Remove the specified user from storage
     *
     * @param  \Modules\User\Entities\User $user
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(User $user)
    {
        $user->delete();

        return redirect()->route('user.index')->withStatus(__("User #$user->id successfully deleted."));
    }

    public function restore($id)
    {
        $user = User::onlyTrashed()->findOrFail($id);

        $this->authorize('restore', $user);

        if ($user->trashed()) {
            $user->restore();

            return redirect()->route('user.trashed')->withStatus(__("User #$user->id successfully restored."));
        }

        return redirect()->route('user.trashed')->withErrors(__("User #$user->id cannot be restored."));
    }

    public function export(Request $request)
    {
        $this->authorize('export', User::class);

        return Excel::download(new UsersExport($request), 'users-' . now()->format('dmY_His') . '.xlsx');
    }
}
