<?php
if (!defined('ABSPATH')) exit;

/**
 * Flipboard helper (no OAuth / no direct publishing).
 * - Stores an RSS feed URL to use in Flipboard Publisher / Magazine.
 * - Provides a share URL generator.
 * - Can test the RSS feed and report whether it includes images.
 */
class Calliope_SP_Flipboard {

    /**
     * Returns the configured feed URL (or a sensible default).
     */
    public function get_feed_url() {
        $saved = (string) get_option('calliope_sp_flipboard_feed_url', '');
        $saved = trim($saved);
        if ($saved) return esc_url_raw($saved);
        // Default WordPress RSS feed.
        return esc_url_raw(trailingslashit(get_site_url()) . 'feed/');
    }

    /**
     * Builds the Flipboard share URL (bookmarklet popout).
     * Note: the `title` parameter often breaks with emojis or long titles
     * and can trigger a generic "something went wrong" error.
     * For that reason, the plugin sends only the `url` by default and lets
     * Flipboard resolve title and image data from OG or canonical metadata.
     */
    public function build_share_url($url, $title = '') {
        $url = trim((string) $url);
        if (!$url) return '';
        // URL only (more compatible).
        return 'https://share.flipboard.com/bookmarklet/popout?v=2&url=' . rawurlencode($url);
    }

    /**
     * Tests the RSS feed URL and returns a report array or WP_Error.
     */
    public function test_feed($feed_url) {
        $feed_url = esc_url_raw(trim((string) $feed_url));
        if (!$feed_url) {
            return new WP_Error('calliope_sp_flipboard_no_feed', 'Flipboard: RSS feed URL is empty.');
        }

        // Use WP's feed parser.
        if (!function_exists('fetch_feed')) {
            require_once ABSPATH . WPINC . '/feed.php';
        }

        $feed = fetch_feed($feed_url);
        if (is_wp_error($feed)) {
            return $feed;
        }

        $max = 5;
        $qty = (int) $feed->get_item_quantity($max);
        $items = $feed->get_items(0, $qty);

        $latest = null;
        $has_images = false;
        $image_hint = '';

        if (!empty($items)) {
            $latest = $items[0];
            // Try to detect an image via enclosure, media:content, or content HTML.
            $enclosure = $latest->get_enclosure();
            if ($enclosure && $enclosure->get_link()) {
                $link = $enclosure->get_link();
                if ($link && preg_match('~\.(png|jpe?g|gif|webp)(\?|$)~i', $link)) {
                    $has_images = true;
                    $image_hint = $link;
                }
            }

            if (!$has_images) {
                $content = (string) $latest->get_content();
                if ($content && preg_match("~<img[^>]+src=[\"']([^\"']+)[\"']~i", $content, $m)) {
                    $has_images = true;
                    $image_hint = $m[1];
                }
            }
        }

        return [
            'feed_url'     => $feed_url,
            'items_found'  => $qty,
            'latest_title' => $latest ? (string) $latest->get_title() : '',
            'latest_link'  => $latest ? (string) $latest->get_link() : '',
            'has_images'   => $has_images,
            'image_hint'   => $image_hint,
        ];
    }
}
