<?php

namespace App\Http\Controllers\Admin\Master;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Master\UserRequest;
use App\Models\Barbershop;
use App\Models\Biography;
use App\Models\Role;
use App\Models\User;
use App\Traits\UploadAttachment;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller
{
    use UploadAttachment;

    public function index(): View
    {
        return view('pages.admin.master.user.index', [
            'pageTitle' => 'Pegawai',
            'users' => User::with(['biography', 'attachments'])
                ->barbershop()
                ->latest()
                ->get(),
        ]);
    }

    public function create(): View
    {
        return view('pages.admin.master.user.create', [
            'pageTitle' => 'Tambah Pegawai',
            'roles' => Role::latest()->get(),
            'barbershop' => Barbershop::latest()->get(),
        ]);
    }

    public function store(UserRequest $request): RedirectResponse
    {
        $validatedData = $request->validated();

        DB::transaction(function () use ($validatedData) {
            $newUser = User::create(array_merge($validatedData, [
                'role_id' => $validatedData['role'],
                'barbershop_id' => $validatedData['barbershop'],
                'password' => Hash::make(env('PASSWORD_DEFAULT_USER')),
            ]));
            Biography::create(array_merge($validatedData, [
                'user_id' => $newUser->id,
            ]), $validatedData);
            $this->uploadAttachment($validatedData['avatar'], 'users', User::class, $newUser->id, 'avatar');
            $this->uploadAttachment($validatedData['ktp'], 'users', User::class, $newUser->id, 'ktp');
        });

        notify()->success('Data berhasil ditambahkan', 'Berhasil');

        return redirect('dashboard/master/users');
    }

    public function edit(User $user): View
    {
        return view('pages.admin.master.user.edit', [
            'pageTitle' => 'Edit Pegawai',
            'roles' => Role::latest()->get(),
            'barbershop' => Barbershop::latest()->get(),
            'user' => $user,
        ]);
    }

    public function update(User $user, UserRequest $request): RedirectResponse
    {
        $validatedData = $request->validated();

        DB::transaction(function () use ($validatedData, $user) {
            $user->update(array_merge($validatedData, [
                'role_id' => $validatedData['role'],
                'barbershop_id' => $validatedData['barbershop'],
            ]));

            $biographyData = collect($validatedData)
                ->except([
                    'email',
                    'username',
                    'role',
                    'barbershop',
                    'entry_date',
                    'base_salary',
                    'sop',
                    'avatar',
                    'ktp',
                ])
                ->toArray();
            $user->biography()->update($biographyData);
            if (isset($validatedData['avatar'])) {
                $this->uploadAttachment($validatedData['avatar'], 'users', User::class, $user->id, 'avatar');
            }
            if (isset($validatedData['ktp'])) {
                $this->uploadAttachment($validatedData['ktp'], 'users', User::class, $user->id, 'ktp');
            }
        });

        notify()->success('Data berhasil diubah', 'Berhasil');

        return redirect('dashboard/master/users');
    }

    public function delete(User $user): RedirectResponse
    {
        if (Auth::id() === $user->id) {
            notify()->info('Ini adalah akun Anda, Anda tidak dapat menghapus akun ini', 'Informasi');

            return back();
        }
        $user->delete();

        notify()->success('Data berhasil dihapus', 'Berhasil');

        return back();
    }

    public function resetPassword(User $user): RedirectResponse
    {
        $user->update([
            'password' => Hash::make(env('PASSWORD_DEFAULT_USER')),
        ]);
        notify()->success('Kata sandi berhasil direset menjadi '.env('PASSWORD_DEFAULT_USER'), 'Berhasil');

        return back();
    }

    public function activation(User $user): RedirectResponse
    {
        if (Auth::id() === $user->id) {
            notify()->info('Ini adalah akun Anda, Anda tidak dapat monaktifkannya akun ini', 'Informasi');

            return back();
        }
        $user->update([
            'is_active' => $user->is_active === '1' ? '0' : '1',
        ]);
        notify()->success('Status berhasil diubah', 'Berhasil');

        return back();
    }
}
