<?php

namespace App\Http\Controllers\panel;

use App\Department;
use App\Http\Controllers\Controller;
use App\Rules\Mobile;
use App\Staff;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class StaffController extends Controller
{

    public function __construct()
    {
        $this->authorizeResource(Staff::class);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $staffs = Staff::with('departments')->latest()->paginate(20);
        return view('panel.staffs.list', compact('staffs'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        $departments = Department::all();
        return view('panel.staffs.add', compact('departments'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        $hasError = false;
        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users',
            'mobile' => ['required', new Mobile(), 'unique:users'],
            'password' => 'required|min:8',
            'departments' => 'required|array'
        ]);

        $selectedDepartments = $request->departments;

        foreach ($selectedDepartments as $department) {
            if (!Department::whereId($department)->exists()) {
                if ($request->expectsJson()) {
                    return response()->json(['status' => 'fail', 'msg' => 'دپارتمان یافت نشد']);
                }

                return redirect()->back()->with(['status' => 'fail', 'msg' => 'دپارتمان یافت نشد']);
            }
        }

        if ($request->has('status') and $request->status == 'active') {
            $status = 'active';
        }

        $data = $request->all();
        $data['status'] = $status ?? 'disabled';
        $data['mobile_verified_at'] = !$request->has('needsVerification') ? Carbon::now() : null;
        $data['email_verified_at'] = !$request->has('needsVerification') ? Carbon::now() : null;
        $data['role'] = 'staff';


        $user = Staff::create($data);

        if ($request->has('needVerification') and $request->needVerification == 'true') {
            $user->accountVerificationActions();
        }

        $user->departments()->sync($selectedDepartments);


        $responseMsg = 'با موفقیت افزوده شد';
        $responseStatus = 'success';

        if ($request->expectsJson()) {
            return response()->json(['status' => $responseStatus, 'msg' => $responseMsg]);
        }

        return redirect()->route('panel.staffs.index')->with($responseStatus, $responseMsg);
    }

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Staff  $staff
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit(Staff $staff)
    {
        $departments = Department::all();
        $staffDepartments = array_column($staff->departments->toArray(), 'id');
        return view('panel.staffs.edit', compact('staff', 'departments', 'staffDepartments'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Staff  $staff
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, Staff $staff)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users,email,' . $staff->id . ',id',
            'mobile' => ['required', new Mobile(), 'unique:users,mobile,' . $staff->id . ',id'],
            'password' => 'nullable|min:8',
            'departments' => 'required|array',
            'status' => 'required|in:active,disabled,banned',
        ]);

        $selectedDepartments = $request->departments;

        foreach ($selectedDepartments as $department) {
            if (!Department::whereId($department)->exists()) {
                if ($request->expectsJson()) {
                    return response()->json(['status' => 'fail', 'msg' => 'دپارتمان یافت نشد']);
                }

                return redirect()->back()->with(['status' => 'fail', 'msg' => 'دپارتمان یافت نشد']);
            }
        }


        $mobileVerified = $request->has('mobileVerified') ? $request->mobileVerified : null;
        $emailVerified = $request->has('emailVerified') ? $request->emailVerified : null;

        $data = Arr::except($request->all(), 'password');
        $data['mobile_verified_at'] = $mobileVerified;
        $data['email_verified_at'] = $emailVerified;
        $data['role'] = 'staff';
        //change password only if set a new one on form
        if ($request->password) {
            $data['password'] = $request->password;
        }

        $staff->update($data);

        $staff->departments()->sync($selectedDepartments);


        $responseMsg = 'با موفقیت ویرایش شد';
        $responseStatus = 'success';

        if ($request->expectsJson()) {
            return response()->json(['status' => $responseStatus, 'msg' => $responseMsg]);
        }

        return redirect()->route('panel.staffs.index')->with($responseStatus, $responseMsg);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param \App\Staff $staff
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     * @throws \Exception
     */
    public function destroy(Staff $staff, Request $request)
    {
        $staff->delete();

        if ($request->expectsJson()) {
            return response()->json(['status' => 'success', 'msg' => 'با موفقیت حذف شد']);
        }

        return redirect()->route('panel.users.index')->with('success', 'با موفقیت حذف شد');
    }
}
