<?php

namespace NewsletterBridge\Services\Post;

use NewsletterBridge\Config\FeaturedConfig;

/**
 * Meta box e lettura campi newsletter sui post (compatibile con ACF oltre a post_meta nativo).
 */
class NewsletterPostFields {

    public const ADMIN_LIST_FILTER_PARAM = 'newsletter_in_evidenza';

    public static function init(): void {
        add_action('add_meta_boxes', [self::class, 'registerMetaBoxes']);
        add_action('save_post', [self::class, 'savePostMeta'], 10, 2);
        add_action('init', [self::class, 'registerPostMeta']);
        add_action('restrict_manage_posts', [self::class, 'renderAdminListFilter']);
        add_action('pre_get_posts', [self::class, 'filterAdminListQuery']);
    }

    public static function registerPostMeta(): void {
        foreach (FeaturedConfig::getEnabledPostTypes() as $post_type) {
            register_post_meta($post_type, FeaturedConfig::META_IN_EVIDENZA, [
                'type' => 'string',
                'single' => true,
                'show_in_rest' => true,
                'auth_callback' => static fn () => current_user_can('edit_posts'),
            ]);
            register_post_meta($post_type, FeaturedConfig::META_SUBJECT, [
                'type' => 'string',
                'single' => true,
                'show_in_rest' => true,
                'auth_callback' => static fn () => current_user_can('edit_posts'),
            ]);
        }
    }

    public static function registerMetaBoxes(): void {
        foreach (FeaturedConfig::getEnabledPostTypes() as $post_type) {
            add_meta_box(
                'newsletter_bridge_fields',
                'Campi per Newsletter',
                [self::class, 'renderMetaBox'],
                $post_type,
                'side',
                'high'
            );
        }
    }

    public static function renderMetaBox(\WP_Post $post): void {
        wp_nonce_field('newsletter_bridge_post_fields', 'newsletter_bridge_post_fields_nonce');

        $in_evidenza = self::isInEvidenzaNewsletter($post->ID);
        $subject = self::getNewsletterSubject($post->ID);
        ?>
        <p>
            <label for="newsletter_bridge_in_evidenza">
                <strong>In evidenza newsletter</strong>
            </label>
        </p>
        <p class="description" style="margin-top:0;">Quando un articolo è in evidenza per la newsletter, viene messo in alto e grande.</p>
        <p>
            <label>
                <input type="checkbox" name="newsletter_bridge_in_evidenza" id="newsletter_bridge_in_evidenza" value="1" <?php checked($in_evidenza); ?> />
                Sì
            </label>
        </p>
        <p>
            <label for="newsletter_bridge_subject">
                <strong>Oggetto newsletter</strong>
            </label>
        </p>
        <p>
            <input type="text" class="widefat" name="newsletter_bridge_subject" id="newsletter_bridge_subject" value="<?php echo esc_attr($subject); ?>" />
        </p>
        <?php
    }

    public static function savePostMeta(int $post_id, \WP_Post $post): void {
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        if (!isset($_POST['newsletter_bridge_post_fields_nonce'])
            || !wp_verify_nonce($_POST['newsletter_bridge_post_fields_nonce'], 'newsletter_bridge_post_fields')) {
            return;
        }
        if (!in_array($post->post_type, FeaturedConfig::getEnabledPostTypes(), true)) {
            return;
        }
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        if (!empty($_POST['newsletter_bridge_in_evidenza'])) {
            update_post_meta($post_id, FeaturedConfig::META_IN_EVIDENZA, '1');
        } else {
            delete_post_meta($post_id, FeaturedConfig::META_IN_EVIDENZA);
        }

        $subject = isset($_POST['newsletter_bridge_subject'])
            ? sanitize_text_field(wp_unslash($_POST['newsletter_bridge_subject']))
            : '';
        if ($subject !== '') {
            update_post_meta($post_id, FeaturedConfig::META_SUBJECT, $subject);
        } else {
            delete_post_meta($post_id, FeaturedConfig::META_SUBJECT);
        }
    }

    public static function isInEvidenzaNewsletter(int $post_id): bool {
        if (function_exists('get_field')) {
            $acf = get_field(FeaturedConfig::META_IN_EVIDENZA, $post_id);
            if ($acf === true || $acf === 1 || $acf === '1') {
                return true;
            }
        }

        return get_post_meta($post_id, FeaturedConfig::META_IN_EVIDENZA, true) === '1';
    }

    public static function getNewsletterSubject(int $post_id): string {
        if (function_exists('get_field')) {
            foreach ([FeaturedConfig::META_SUBJECT, 'oggetto_newsletter'] as $key) {
                $acf = get_field($key, $post_id);
                if ($acf !== null && $acf !== false && $acf !== '') {
                    return is_string($acf) ? $acf : (string) $acf;
                }
            }
        }

        foreach ([FeaturedConfig::META_SUBJECT, 'oggetto_newsletter'] as $key) {
            $meta = get_post_meta($post_id, $key, true);
            if ($meta !== '' && $meta !== false) {
                return (string) $meta;
            }
        }

        return '';
    }

    /**
     * Titolo per subject MailUp / feed: se in evidenza usa oggetto newsletter, altrimenti titolo articolo.
     */
    public static function resolveNewsletterTitle(int $post_id): string {
        $post = get_post($post_id);
        if (!$post) {
            return '';
        }

        if (self::isInEvidenzaNewsletter($post_id)) {
            $subject = self::getNewsletterSubject($post_id);
            if ($subject !== '') {
                return $subject;
            }
        }

        return apply_filters('the_title_rss', $post->post_title);
    }

    /**
     * Clausola meta_query per filtro feed (only|exclude).
     *
     * @return array<int, array<string, mixed>>|null
     */
    public static function buildInEvidenzaMetaQuery(string $filter): ?array {
        if ($filter === 'only') {
            return [
                [
                    'key' => FeaturedConfig::META_IN_EVIDENZA,
                    'value' => '1',
                    'compare' => '=',
                ],
            ];
        }

        if ($filter === 'exclude') {
            return [
                [
                    'relation' => 'OR',
                    [
                        'key' => FeaturedConfig::META_IN_EVIDENZA,
                        'compare' => 'NOT EXISTS',
                    ],
                    [
                        'key' => FeaturedConfig::META_IN_EVIDENZA,
                        'value' => '1',
                        'compare' => '!=',
                    ],
                ],
            ];
        }

        return null;
    }

    /**
     * Dropdown filtro nella lista articoli (solo post type abilitati in tab In Evidenza).
     */
    public static function renderAdminListFilter(string $post_type): void {
        if (!in_array($post_type, FeaturedConfig::getEnabledPostTypes(), true)) {
            return;
        }

        $current = isset($_GET[self::ADMIN_LIST_FILTER_PARAM])
            ? sanitize_text_field(wp_unslash($_GET[self::ADMIN_LIST_FILTER_PARAM]))
            : '';
        ?>
        <label for="filter-by-newsletter-in-evidenza" class="screen-reader-text">Newsletter in evidenza</label>
        <select name="<?php echo esc_attr(self::ADMIN_LIST_FILTER_PARAM); ?>" id="filter-by-newsletter-in-evidenza">
            <option value="" <?php selected($current, ''); ?>>Newsletter: tutti</option>
            <option value="1" <?php selected($current, '1'); ?>>Newsletter: solo in evidenza</option>
        </select>
        <?php
    }

    /**
     * Applica il filtro "solo in evidenza" alla query della lista admin.
     */
    public static function filterAdminListQuery(\WP_Query $query): void {
        if (!is_admin() || !$query->is_main_query()) {
            return;
        }

        global $pagenow;
        if ($pagenow !== 'edit.php') {
            return;
        }

        $post_type = $query->get('post_type');
        if ($post_type === '' || $post_type === 'any') {
            $post_type = 'post';
        }
        if (is_array($post_type)) {
            return;
        }

        if (!in_array($post_type, FeaturedConfig::getEnabledPostTypes(), true)) {
            return;
        }

        if (!isset($_GET[self::ADMIN_LIST_FILTER_PARAM])
            || sanitize_text_field(wp_unslash($_GET[self::ADMIN_LIST_FILTER_PARAM])) !== '1') {
            return;
        }

        $meta_query = $query->get('meta_query');
        if (!is_array($meta_query)) {
            $meta_query = [];
        }
        if ($meta_query !== [] && !isset($meta_query['relation'])) {
            $meta_query = array_merge(['relation' => 'AND'], $meta_query);
        }

        $clause = self::buildInEvidenzaMetaQuery('only');
        if ($clause === null) {
            return;
        }

        foreach ($clause as $part) {
            $meta_query[] = $part;
        }

        $query->set('meta_query', $meta_query);
    }
}
