<?php

namespace App\Http\Controllers\panel;

use App\Department;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class DepartmentController extends Controller
{

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

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        $request->validate([
            'departmentName' => 'required'
        ]);

        Department::create([
            'name' => $request->departmentName,
            'is_hidden' => $request->has('isHidden') ? true : false
        ]);

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

        return redirect()->route('panel.departments.index')->with(['success' => 'دپارتمان جدید با موفقیت اضافه شد']);
    }

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Department  $department
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit(Department $department)
    {
        return view('panel.departments.edit', compact('department'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Department  $department
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, Department $department)
    {
        $request->validate([
            'departmentName' => 'required',
            'is_hidden' => 'sometimes|boolean'
        ]);

        $data['name'] = $request->departmentName;
        $data['is_hidden'] = $request->has('is_hidden') ? true : false;

        $department->update($data);

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