<?php

namespace Modules\Admin\Http\Controllers;

use Modules\Docs\Models\Document;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\Bitrix\Models\BitrixWebhooks;
use Modules\Bitrix\Enums\BitrixWebhooksEnum;

class AdminBitrixWebhooksController extends Controller
{

    public function index()
    {
        $webhooks = BitrixWebhooks::all()->keyBy('name')->toArray();

        return view('admin::bitrix.webhooks', [
            'webhooksEnumCases' => BitrixWebhooksEnum::cases(),
            'webhooks'          => $webhooks
        ]);
    }

    public function create(Request $request)
    {
        foreach (BitrixWebhooksEnum::cases() as $webhook)
        {
            $webhookName = $webhook->name;
            if ($request->has($webhookName) && $request->$webhookName)
            {
                BitrixWebhooks::updateOrCreate(
                    ['name' => $webhookName],
                    [
                        'name' => $webhookName,
                        'url'  => $request->$webhookName
                    ]
                );
            }
        }
        return back();
    }

    public function delete($name)
    {
        BitrixWebhooks::where('name', $name)->delete();
    }
}