<?php

namespace Webhooks\Helper;

class Webhooks extends \Lime\Helper {

    protected array $hooks = [];

    protected function initialize() {

        $this->hooks = $this->app['debug'] ? $this->cache(false) : $this->app->memory->get('app.webhooks', function() {
            return $this->cache();
        });
    }

    public function hooks() {

        return $this->hooks;
    }

    public function cache(bool $persistent = true): array {

        $cache = [];

        $cache = $this->app->dataStorage->find('webhooks', [])->toArray();

        if ($persistent) {
            $this->app->memory->set('app.webhooks', $cache);
        }

        return $cache;
    }

    public function generateCurlCommand(array $webhook, $payload = null): string {

        $url = \DotEnv::resolveEnvsInString(\trim($webhook['url']));
        $method = $webhook['method'] ?? 'POST';
        $headers = [];
        $data = null;
        $isJson = false;

        // Process headers from webhook config
        if (\is_array($webhook['headers'])) {
            foreach ($webhook['headers'] as $h) {
                if (!isset($h['key'], $h['val'])) continue;
                if (!$h['key'] || !$h['val']) continue;

                $headers[] = $h['key'] . ': ' . \DotEnv::resolveEnvsInString($h['val']);
            }
        }

        // Process data payload
        if ($webhook['body']['payload']) {
            if ($webhook['body']['custom']) {
                $data = $webhook['body']['contents'] ?? [];
            } elseif ($payload) {
                $data = $payload;
            }

            if ($data && \is_array($data)) {
                \DotEnv::resolveEnvsInArray($data);

                if ($method == 'GET') {
                    $data = \http_build_query($data);
                } else {
                    $data = \json_encode($data);
                    $isJson = true;
                    $headers[] = 'Content-Type: application/json';
                }
            }
        }

        // Add data to URL for GET requests
        if ($data && $method == 'GET') {
            $url .= (\str_contains($url, '?') ? '&' : '?') . $data;
            $data = null; // Clear data since it's in the URL now
        }

        // Start with the basic curl command
        $cmd = "curl -X " . \escapeshellarg($method) . " ";

        // Add headers
        foreach ($headers as $header) {
            $cmd .= "-H " . \escapeshellarg($header) . " ";
        }

        // Add the data if it exists
        if ($data && $method != 'GET') {
            if ($isJson) {
                $cmd .= "-d " . \escapeshellarg($data) . " ";
            } else {
                $cmd .= "--data-raw " . \escapeshellarg($data) . " ";
            }
        }

        if (!\str_starts_with($url, 'https://')) {
            $cmd .= "--insecure ";
        }

        // Add URL
        $cmd .= \escapeshellarg($url);

        return $cmd;
    }

}
