<?php

namespace GriffinForms\Includes\Publication;

use GriffinForms\Traits\Singleton;

class PostSaveTracker
{
    use Singleton;

    protected $frontend_url_logger;
    protected $placement_service;

    protected function setFrontendUrlLogger(): void
    {
        $this->frontend_url_logger = new FrontendUrlLogger();
    }

    protected function setPlacementService(): void
    {
        $this->placement_service = \GriffinForms\Includes\Onboarding\PlacementService::getInstance();
    }

    public function registerHooks(): void
    {
        add_action('wp_after_insert_post', [$this, 'capturePublicationUrls'], 10, 4);
    }

    public function capturePublicationUrls(int $post_id, \WP_Post $post, bool $update, ?\WP_Post $post_before): void
    {
        unset($update, $post_before);

        if ($post_id < 1) {
            return;
        }

        if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) {
            return;
        }

        if (!in_array($post->post_type, ['post', 'page'], true)) {
            return;
        }

        if (!in_array($post->post_status, ['publish', 'future', 'private'], true)) {
            return;
        }

        $form_ids = $this->placement_service->extractPlacedFormIdsFromContent((string) $post->post_content);
        if (empty($form_ids)) {
            return;
        }

        $url = (string) get_permalink($post_id);
        if ($url === '') {
            return;
        }

        foreach ($form_ids as $form_id) {
            $this->frontend_url_logger->append((int) $form_id, $url);
        }
    }
}
