<?php

namespace GriffinForms\Includes\Publication;

class FrontendUrlLogger
{
    protected \GriffinForms\Config $config;
    protected \GriffinForms\Log $log;

    public function __construct()
    {
        $this->config = \GriffinForms\Config::getInstance();
        $this->log = \GriffinForms\Log::getInstance();
    }

    public function append(int $form_id, string $url): bool
    {
        global $wpdb;

        $form_id = absint($form_id);
        $url = esc_url_raw(trim($url));
        if ($form_id < 1 || $url === '') {
            return false;
        }

        if ($this->shouldSkipUrl($url)) {
            return true;
        }

        $table = $this->config->getTable('form');
        $current = $wpdb->get_var(
            $wpdb->prepare(
                'SELECT frontend_url FROM %i WHERE id = %d',
                $table,
                $form_id
            )
        );

        $urls = [];
        if (is_string($current) && $current !== '') {
            $decoded = maybe_unserialize($current);
            if (is_array($decoded)) {
                $urls = $decoded;
            } else {
                $json = json_decode($current, true);
                if (json_last_error() === JSON_ERROR_NONE && is_array($json)) {
                    $urls = $json;
                }
            }
        } elseif (is_array($current)) {
            $urls = $current;
        }

        $urls = array_values(array_filter(array_map(static function ($item) {
            return esc_url_raw(trim((string) $item));
        }, $urls)));

        if (in_array($url, $urls, true)) {
            return true;
        }

        $urls[] = $url;
        $updated = $wpdb->update(
            $table,
            [
                'frontend_url' => maybe_serialize($urls),
                'last_editor' => get_current_user_id(),
                'last_edited' => current_time('mysql', true),
            ],
            ['id' => $form_id],
            ['%s', '%d', '%s'],
            ['%d']
        );

        if ($updated === false) {
            $this->log->add(
                'warning',
                'form',
                $form_id,
                (int) get_current_user_id(),
                'Failed to persist frontend_url publication footprint.',
                'publication'
            );
            return false;
        }

        return true;
    }

    protected function shouldSkipUrl(string $url): bool
    {
        $query = wp_parse_url($url, PHP_URL_QUERY);
        if (!is_string($query) || $query === '') {
            return false;
        }

        parse_str($query, $params);

        if (isset($params['gf_preview_form']) && absint($params['gf_preview_form']) > 0) {
            return true;
        }

        if (isset($params['gf_sub_id']) && absint($params['gf_sub_id']) > 0) {
            return true;
        }

        return false;
    }
}
