<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Http\Requests\API\Config\AllowSettingConfig;
use App\Models\Config;
use App\Models\Enums\ConfigGroup;
use App\Models\Enums\ObjectAction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ConfigController extends Controller
{
    public function index(Request $request)
    {
        $groups = $request->get("group", []);

        $data = [];

        if ($groups) {
            $data = Config::query()->whereIn("group", $groups)->get([
                'group', 'key', 'value'
            ])->groupBy("group");
        }

        return $this->success([
            'data' => $data
        ]);
    }

    public function setting(Request $request)
    {
        $allowSettingConfig = new AllowSettingConfig();

        foreach ($request->all() as $item) {
            try {
                $allowSettingConfig->check($item['group'], $item['key'], $item['value']);
            } catch (\Exception $exception) {
                return $this->forbidden($exception->getMessage());
            }
        }

        foreach ($request->all() as $item) {
            Config::query()->updateOrCreate([
                'group' => $item['group'],
                'key' => $item['key'],
                'company_id' => Auth::user()->company_id,
            ], [
                'value' => $item['value']
            ]);
        }

        return $this->noContent();
    }

    public function messageNotificationSetting()
    {
        $relations = ObjectAction::messageNotificationItems();

        $settingResult = Config::query()
            ->where("group", ConfigGroup::MESSAGE_NOTIFICATION)
            ->where("key", "setting")
            ->first();

        $setting = $settingResult ? json_decode($settingResult->value, true) : [];

        $items = [];
        foreach ($relations as $group => $relation) {
            $item = [
                'group_key' => $group,
                'group_name' => __("action-labels.object_type." . $group),
                'email' => [],
                'browser' => [],
            ];

            foreach ($relation as $action) {
                $actionItem = [
                    'key' => $action->value,
                    'name' => __("action-labels.label." . $action->value),
                ];

                $item['email'][] = [
                    ...$actionItem,
                    'checked' => in_array($action->value, $setting[$group]['email'] ?? []),
                ];

                $item['browser'][] = [
                    ...$actionItem,
                    'checked' => in_array($action->value, $setting[$group]['browser'] ?? []),
                ];
            }

            $items[] = $item;
        }

        return $this->success([
            'data' => $items
        ]);
    }

    public function storeMessageNotificationSetting(Request $request)
    {
        $relations = ObjectAction::messageNotificationItems();

        $settings = [];
        foreach ($request->all() as $group => $items) {
            if (! isset($relations[$group])) {
                return $this->badRequest(sprintf("Group '%s' does not exist", $group));
            }

            foreach(['email', 'browser'] as $settingItem) {
                foreach ($items[$settingItem] as $item) {
                    $action = ObjectAction::tryFrom($item);
                    if (! in_array($action, $relations[$group])) {
                        return $this->badRequest(sprintf("In group '%s', '%s' exists", $group, $item));
                    }
                }
            }

            $settings[$group] = $items;
        }

        Config::query()->updateOrCreate([
            'group' => ConfigGroup::MESSAGE_NOTIFICATION,
            'key' => 'setting',
            'company_id' => Auth::user()->company_id,
        ], [
            'value' => json_encode($settings),
        ]);

        return $this->noContent();
    }
}