<?php

namespace App\Http\Controllers;

use App\Models\User;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Permission;
use Yajra\DataTables\DataTables;

class AdminController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return view('Admins.index');
    }

    public function getAdmins(Request $request)
    {
        if ($request->ajax()) {
            $data = User::all();
            return DataTables::of($data)
                ->addIndexColumn()
                ->addColumn('permissions', function ($row) {
                    $perm_arr = $row->getPermissionNames();
                    $role_arr = $row->getRoleNames();
                    $isSuperAdmin = false;
                    if (!count($role_arr) == 0) if ($role_arr[0] == 'Super Admin') $isSuperAdmin = true;
                    if ($isSuperAdmin == true) return "سوپر ادمین";
                    else return count($perm_arr) == 0 ? '-' : $perm_arr;
                })
                ->addColumn('Actions', function ($row) {
                    $actionBtn = '<button type="button" class="btn bg-transparent _r_btn border-0" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    <span class="_dot _r_block-dot bg-dark"></span>
                                    <span class="_dot _r_block-dot bg-dark"></span>
                                    <span class="_dot _r_block-dot bg-dark"></span>
                                </button>
                                <div class="dropdown-menu" x-placement="bottom-start">
                                    <a href="' . route('admins.destroy', $row->id) . '" class="dropdown-item text-left" onclick="return confirm(\'آیا برای حذف مطمئن هستید؟\')">
                                        <i class="nav-icon i-Close-Window text-danger font-weight-bold mr-2"></i>
                                        حذف
                                    </a>
                                    <a href="' . route('admins.edit', $row->id) . '" class="dropdown-item text-left">
                                        <i class="nav-icon i-Pen-2 font-weight-bold text-success mr-2"></i>
                                        ویرایش
                                    </a>
                                </div>';
                    return $actionBtn;
                })
                ->rawColumns(['Actions', 'permissions'])
                ->make(true);
        }
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('Admins.create');
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return RedirectResponse
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:app_users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
        try {
            User::create([
                'name' => $request['name'],
                'email' => $request['email'],
                'password' => Hash::make($request['password']),
            ]);
        } catch (\Exception $e) {
            Toastr::error('عملیات افزودن ادمین جدید با مشکل مواجه شد.', 'Error');
            return redirect()->back();
        }
        Toastr::success('ادمین جدید با موفقیت ایجاد شد.', 'Success');
        return redirect()->route('admins.index');
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     * @param $id
     */
    public function edit($id)
    {
        $admin = User::find($id);
        $permissions = Permission::select('name')->get();
        return view('Admins.edit', compact('permissions', 'admin'));
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param $id
     */
    public function update(Request $request, $id)
    {
        // Validate
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:app_users,email,' . $id . ''],
        ]);
        try {
            $user = User::find($id);
            // Update user information
            $user->update([
                'name' => $request['name'],
                'email' => $request['email']
            ]);
            // Update permissions
            $user->syncPermissions($request['permissions']);
        } catch (\Exception $e) {
            Toastr::error('عملیات ویرایش ادمین با مشکل مواجه شد.', 'Error');
            return redirect()->back();
        }
        Toastr::success('ادمین با موفقیت ویرایش شد.', 'Success');
        return redirect()->route('admins.index');
    }

    /**
     * Update the user password
     * @param Request $request
     * @param $id
     */
    public function updatePassword(Request $request, $id)
    {
        $request->validate([
            'current_password' => 'required',
            'password' => 'required|same:password',
            'password_confirmation' => 'required|same:password',
        ]);
        $user = User::find($id);
        if (Hash::check($request->current_password, $user->password)) {
            $user->password = Hash::make($request->password);;
            $user->save();
        } else {
            Toastr::error('خطا در تغییر رمز عبور!', 'Error');
            return redirect()->back();
        }
        Toastr::success('رمز عبور با موفقیت تغییر یافت.', 'Success');
        return redirect()->route('admins.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $admin = User::find($id);
        $permissions = Permission::select('name')->get();
        try {
            $admin->delete();
        } catch (\Exception $e) {
            Toastr::error('عملیات حذف با مشکل مواجه شد.', 'Success');
            return redirect()->back();
        }
        Toastr::success('مدیر مورد نظر حذف گردید.', 'Success');
        return redirect()->back();
    }
}
