<?php

namespace Webhooks\Controller;

use App\Controller\App;
use ArrayObject;

class Webhooks extends App {

    protected function before() {

        if (!$this->isAllowed('webhooks/manage')) {
            return $this->stop(401);
        }
    }

    public function index() {

        $this->helper('theme')->favicon('webhooks:icon.svg');

        return $this->render('webhooks:views/index.php');
    }

    public function load() {

        $this->helper('session')->close();
        $this->hasValidCsrfToken(true);

        $options = [
            'sort' => ['name' => 1]
        ];

        $webhooks = $this->app->dataStorage->find('webhooks', $options)->toArray();

        return $webhooks;
    }

    public function webhook($id = null) {

        $webhook = [
            'enabled' => false,
            'name' => '',
            'info' => '',
            'url' => '',
            'method' => 'GET',
            'headers' => [],
            'events' => [],
            'body' => [
                'payload' => false,
                'custom' => false,
                'contents' => null
            ]
        ];

        if ($id) {

            $hook = $this->app->dataStorage->findOne('webhooks', ['_id' => $id]);

            if (!$hook) {
                return false;
            }

            $webhook = \array_merge($webhook, $hook);
        }


        return $this->render('webhooks:views/webhook.php', \compact('webhook'));
    }

    public function save() {

        $this->hasValidCsrfToken(true);

        $webhook = $this->param('webhook');

        if (!$webhook) {
            return false;
        }

        if (
            !isset($webhook['url']) ||
            !\filter_var($webhook['url'] , FILTER_VALIDATE_URL) ||
            !\preg_match('#^(http|https)://#', $webhook['url'])
        ) {
            return $this->stop(['error' => 'Invalid webhook url'], 412);
        }

        $webhook['_modified'] = \time();
        $webhook['_mby'] = $this->user['_id'];

        if (!isset($webhook['_id'])) {
            $webhook['_created'] = $webhook['_modified'];
            $webhook['_cby'] = $this->user['_id'];
        }

        $this->app->dataStorage->save('webhooks', $webhook);

        $this->helper('webhooks')->cache();

        return $webhook;
    }

    public function remove() {

        $this->hasValidCsrfToken(true);

        $webhook = $this->param('webhook');

        if (!$webhook) {
            return $this->stop(['error' => 'Webhook paramater is missing'], 412);
        }

        $this->app->dataStorage->remove('webhooks', ['_id' => $webhook['_id']]);

        $this->helper('webhooks')->cache();

        return ['success' => true];
    }


    public function trigger() {

        $this->helper('session')->close();
        $this->hasValidCsrfToken(true);

        $webhook = $this->param('webhook');

        if (!$webhook) {
            return $this->stop(412);
        }

        if (
            !isset($webhook['url']) ||
            !\filter_var($webhook['url'] , FILTER_VALIDATE_URL) ||
            !\preg_match('#^(http|https)://#', $webhook['url'])
        ) {
            return $this->stop(['error' => 'Invalid webhook url'], 412);
        }

        $result = $this->module('webhooks')->execute($webhook, options: ['curl_command' => true]);

        return \compact('result');
    }

}
