<?php

namespace App\Http\Controllers\Website;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ListUserController extends Controller
{
    public function index()
    {
        return view('website.app.list-user');
    }

    public function getListUserData()
    {
        $listUserData = User::all();

        return response()->json([
            'listUserData' => $listUserData
        ]);
    }

    public function updateListUser(Request $request)
    {
        $userById = User::where('id', $request->input('user_id'))->first();

        if (Auth::user()['id'] == $userById['id']) {
            toast('Anda sedang login, status tidak dapat diperbarui!', 'error');
            return redirect()->back();
        } else {
            $userById['status'] = $request->input('status_user');
            $userById->save();
            toast('Status user berhasil diubah', 'success');
            return redirect()->back();
        }
    }

    public function deleteUser($id)
    {
        $userById = User::where('id', $id)->first();
        if (Auth::user()['id'] == $userById['id']) {
            toast('Anda sedang login, data user tidak dapat dihapus!', 'error');
            return redirect()->back();
        } else if ($userById['status'] == 'aktif') {
            toast('User status aktif, data user tidak dapat dihapus!', 'error');
            return redirect()->back();
        } else {
            $userById->delete();
            toast('Data user berhasil dihapus', 'success');
            return redirect()->back();
        }
    }
}
