<?php

namespace EasyLinkAutomations\Triggers\WordPress;

if (!defined('ABSPATH')) {
    exit;
}

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a user views any singular post, page, or custom post type.
 */
final class PostViewedTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'wordpress/post_viewed';
    }

    public static function getName(): string
    {
        return __('User views a post', 'easylink-automations');
    }

    public static function getDescription(): string
    {
        return __('Triggers when a user views any singular post, page, or custom post type', 'easylink-automations');
    }

    public static function getCategory(): string
    {
        return 'WordPress';
    }

    public static function getIcon(): string
    {
        return 'post';
    }

    public static function getOutputFields(): array
    {
        return [
            'post_id'        => ['label' => 'Post ID', 'type' => 'number'],
            'post_title'     => ['label' => 'Post Title', 'type' => 'string'],
            'post_content'   => ['label' => 'Post Content', 'type' => 'html'],
            'post_excerpt'   => ['label' => 'Post Excerpt', 'type' => 'string'],
            'post_url'       => ['label' => 'Post URL', 'type' => 'url'],
            'post_type'      => ['label' => 'Post Type', 'type' => 'string'],
            'post_status'    => ['label' => 'Post Status', 'type' => 'string'],
            'post_date'      => ['label' => 'Post Date', 'type' => 'datetime'],
            'post_author'    => ['label' => 'Author ID', 'type' => 'number'],
            'author_name'    => ['label' => 'Author Name', 'type' => 'string'],
            'author_email'   => ['label' => 'Author Email', 'type' => 'email'],
            'featured_image' => ['label' => 'Featured Image URL', 'type' => 'url'],
            'categories'     => ['label' => 'Categories', 'type' => 'array'],
            'tags'           => ['label' => 'Tags', 'type' => 'array'],
            'custom_metas'   => ['label' => 'Custom Meta Fields', 'type' => 'json'],
            'viewer_id'      => ['label' => 'Viewer User ID', 'type' => 'number'],
            'viewer_login'   => ['label' => 'Viewer Username', 'type' => 'string'],
            'viewer_email'   => ['label' => 'Viewer Email', 'type' => 'email'],
            'is_logged_in'   => ['label' => 'Is Logged In', 'type' => 'string'],
        ];
    }

    public static function getConfigFields(): array
    {
        return [
            'post_type' => [
                'label'   => 'Post Type',
                'type'    => 'select',
                'options' => 'dynamic:post_types',
                'default' => 'any',
            ],
        ];
    }

    public function register(callable $callback): void
    {
        $this->callback = $callback;

        add_action('template_redirect', function (): void {
            if (!is_singular()) {
                return;
            }

            $postId = get_queried_object_id();
            $post   = get_post($postId);

            if (!$post instanceof \WP_Post) {
                return;
            }

            $data = $this->handle($post);
            $this->fire($data);
        }, 10, 0);
    }

    public function handle(mixed ...$args): array
    {
        $post   = $args[0];
        $postId = $post->ID;

        $author        = get_userdata($post->post_author);
        $featuredImage = wp_get_attachment_image_url(get_post_thumbnail_id($postId), 'full') ?: '';
        $categories    = wp_get_post_categories($postId, ['fields' => 'names']);
        $tags          = wp_get_post_tags($postId, ['fields' => 'names']);
        $customMetas   = get_post_meta($postId);

        $viewer     = wp_get_current_user();
        $isLoggedIn = is_user_logged_in() ? 'yes' : 'no';

        return [
            'post_id'        => $postId,
            'post_title'     => $post->post_title,
            'post_content'   => $post->post_content,
            'post_excerpt'   => $post->post_excerpt,
            'post_url'       => get_permalink($postId),
            'post_type'      => $post->post_type,
            'post_status'    => $post->post_status,
            'post_date'      => $post->post_date,
            'post_author'    => (int) $post->post_author,
            'author_name'    => $author->display_name ?? '',
            'author_email'   => $author->user_email ?? '',
            'featured_image' => $featuredImage,
            'categories'     => $categories,
            'tags'           => $tags,
            'custom_metas'   => $customMetas,
            'viewer_id'      => (int) $viewer->ID,
            'viewer_login'   => $viewer->user_login ?? '',
            'viewer_email'   => $viewer->user_email ?? '',
            'is_logged_in'   => $isLoggedIn,
        ];
    }
}
