<?php

namespace App\Http\Controllers\Menu;

use App\Http\Controllers\Controller;
use App\Models\Log as LogModel;
use App\Models\Menu;
use App\Http\Resources\MenusResource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\Utils\FormatUtils;

class MenusController extends Controller
{
    public function __construct(Request $request)
    {
        $this->log = new LogModel([
            'module' => 'menu',
            'action' => $request->getMethod(),
            'target_type' => 'menu',
        ]);
    }

    public function index(Request $request)
    {
        $permissions = $request->user()->getPermissionsViaRoles()->toArray();
        $permissions = array_column($permissions, 'name');
        $menus = Menu::query()->get()->toArray();
        $hasPermissionMenus = [];
        foreach ($menus as $menu) {
            if (in_array($menu['code'], $permissions, true)) {
                $hasPermissionMenus[] = $menu;
            }
        }
        $menus = FormatUtils::formatTreeData($hasPermissionMenus, 0);

        return MenusResource::collection($menus);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:32',
            'code' => 'required|string|max:32|unique:menus,code',
            'parent_id' => 'required|integer',
            'seq' => 'required|integer',
        ]);
        if ($validator->fails()) {
            $this->setValidatorFailResponse($validator->getMessageBag()->getMessages());

            return response($this->res, $this->res['httpCode']);
        }
        $menu = new Menu();
        $menu->name = $request->name;
        $menu->code = $request->code;
        $menu->parent_id = $request->parent_id;
        $menu->seq = $request->seq;
        $menu->save();
        $this->setAfterUpdate($menu->toArray());
        $this->addLog($menu->id, 'add');

        return response($this->res, $this->res['httpCode']);
    }

    public function show($id)
    {
        return new MenusResource(Menu::query()->find($id));
    }

    public function update($id, Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => ['required', 'string', 'max:32',],
            'code' => ['required', 'string', 'max:32', Rule::unique('menus')->ignore($id),],
            'parent_id' => ['required', 'integer',],
            'seq' => ['required', 'integer',],
        ]);
        if ($validator->fails()) {
            $this->setValidatorFailResponse($validator->getMessageBag()->getMessages());

            return response($this->res, $this->res['httpCode']);
        }
        $menu = Menu::query()->find($id);
        $this->setBeforeUpdate($menu->toArray());
        $menu->name = $request->name;
        $menu->code = $request->code;
        $menu->parent_id = $request->parent_id;
        $menu->seq = $request->seq;
        $menu->save();
        $this->setAfterUpdate($menu->toArray());
        $this->addLog($id, 'update');

        return new MenusResource($menu);
    }

    public function destroy($id)
    {
        $menu = Menu::query()->find($id);
        try {
            $menu->delete();
        } catch (\Exception $e) {
            $this->res = [
                'httpCode' => 500,
                'errorCode' => 500416,
                'errorMessage' => $e->getMessage(),
            ];
        }

        return response($this->res, $this->res['httpCode']);
    }
}
