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

class TMNL_Adapter_X_Embed extends TMNL_Source_Adapter {

    private $cache_prefix = 'tmnl_x_embed_';
    private $cache_expiry;

    public function __construct() {
        $this->cache_expiry = 30 * DAY_IN_SECONDS;
    }

    public function get_id() {
        return 'x_embed';
    }

    public function get_label() {
        return __( 'X (Twitter)', 'elplan-kuchikomi-wall' );
    }

    public function get_icon() {
        return 'dashicons-twitter';
    }

    /**
     * Fetch oEmbed HTML for a single tweet URL
     */
    public function fetch_single( $tweet_url ) {
        $oembed_url = 'https://publish.x.com/oembed?' . http_build_query( array(
            'url'      => $tweet_url,
            'lang'     => 'ja',
            'omit_script' => 'true',
        ));

        $response = wp_remote_get( $oembed_url, array( 'timeout' => 10 ) );

        if ( is_wp_error( $response ) ) {
            return $response;
        }

        $code = wp_remote_retrieve_response_code( $response );
        if ( $code !== 200 ) {
            /* translators: %d: HTTP status code */
            return new WP_Error( 'oembed_error', sprintf( __( 'oEmbed error (HTTP %d)', 'elplan-kuchikomi-wall' ), $code ) );
        }

        $body = wp_remote_retrieve_body( $response );
        $data = json_decode( $body, true );

        if ( empty( $data['html'] ) ) {
            return new WP_Error( 'oembed_empty', __( 'oEmbed response was empty.', 'elplan-kuchikomi-wall' ) );
        }

        // Cache the embed HTML
        $cache_key = $this->cache_prefix . md5( $tweet_url );
        set_transient( $cache_key, $data, $this->cache_expiry );

        return $data;
    }

    /**
     * Fetch all registered tweet embeds
     */
    public function fetch( $force = false ) {
        $embeds = TMNL_DB::get_x_embeds();
        $results = array();

        foreach ( $embeds as $embed ) {
            $cache_key = $this->cache_prefix . md5( $embed->tweet_url );

            if ( ! $force ) {
                $cached = get_transient( $cache_key );
                if ( false !== $cached ) {
                    $results[] = $cached;
                    continue;
                }
            }

            $result = $this->fetch_single( $embed->tweet_url );
            if ( ! is_wp_error( $result ) ) {
                $results[] = $result;

                // Update author name in DB if empty
                if ( empty( $embed->author ) && ! empty( $result['author_name'] ) ) {
                    global $wpdb;
                    $wpdb->update(
                        TMNL_DB::x_embeds_table(),
                        array( 'author' => sanitize_text_field( $result['author_name'] ) ),
                        array( 'id' => $embed->id ),
                        array( '%s' ),
                        array( '%d' )
                    );
                }
            }
        }

        return $results;
    }

    /**
     * Add a new tweet URL
     */
    public function add_tweet( $tweet_url ) {
        $tweet_url = esc_url_raw( trim( $tweet_url ) );

        // Validate URL format
        if ( ! preg_match( '#https?://(twitter\.com|x\.com)/[^/]+/status/\d+#i', $tweet_url ) ) {
            return new WP_Error( 'invalid_url', __( 'Please enter a valid X (Twitter) tweet URL.', 'elplan-kuchikomi-wall' ) );
        }

        // Fetch oEmbed data
        $oembed = $this->fetch_single( $tweet_url );
        if ( is_wp_error( $oembed ) ) {
            return $oembed;
        }

        // Save to DB
        $id = TMNL_DB::insert_x_embed( array(
            'tweet_url' => $tweet_url,
            'author'    => $oembed['author_name'] ?? '',
        ));

        return $id ? $id : new WP_Error( 'db_error', __( 'Failed to save.', 'elplan-kuchikomi-wall' ) );
    }

    public function get_cached() {
        $embeds = TMNL_DB::get_x_embeds( array( 'visible_only' => true ) );
        $results = array();

        foreach ( $embeds as $embed ) {
            $cache_key = $this->cache_prefix . md5( $embed->tweet_url );
            $cached = get_transient( $cache_key );
            if ( false !== $cached ) {
                $cached['_db_id'] = $embed->id;
                $cached['_tweet_url'] = $embed->tweet_url;
                $cached['_sort_order'] = $embed->sort_order;
                $results[] = $cached;
            }
        }

        return $results;
    }

    public function clear_cache() {
        $embeds = TMNL_DB::get_x_embeds();
        foreach ( $embeds as $embed ) {
            delete_transient( $this->cache_prefix . md5( $embed->tweet_url ) );
        }
    }

    public function get_status() {
        $src    = self::get_source_settings( 'x_embed' );
        $embeds = TMNL_DB::get_x_embeds();
        return array(
            'is_enabled' => ! empty( $src['is_enabled'] ),
            'count'      => count( $embeds ),
            'updated_at' => $src['updated_at'],
            'error'      => null,
        );
    }

    public function render_settings() {
        $embeds = TMNL_DB::get_x_embeds();
        ?>
        <h3><?php esc_html_e( 'Registered Tweets', 'elplan-kuchikomi-wall' ); ?></h3>
        <?php if ( empty( $embeds ) ) : ?>
            <p><?php esc_html_e( 'No tweets registered yet.', 'elplan-kuchikomi-wall' ); ?></p>
        <?php else : ?>
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th>URL</th>
                        <th><?php esc_html_e( 'Author', 'elplan-kuchikomi-wall' ); ?></th>
                        <th style="width:80px"><?php esc_html_e( 'Status', 'elplan-kuchikomi-wall' ); ?></th>
                        <th style="width:120px"><?php esc_html_e( 'Actions', 'elplan-kuchikomi-wall' ); ?></th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ( $embeds as $embed ) : ?>
                    <tr class="<?php echo $embed->is_visible ? '' : 'tmnl-hidden-row'; ?>">
                        <td><a href="<?php echo esc_url( $embed->tweet_url ); ?>" target="_blank"><?php echo esc_html( $embed->tweet_url ); ?></a></td>
                        <td><?php echo esc_html( $embed->author ); ?></td>
                        <td>
                            <?php if ( $embed->is_visible ) : ?>
                                <span class="tmnl-badge tmnl-badge-visible"><?php esc_html_e( 'Visible', 'elplan-kuchikomi-wall' ); ?></span>
                            <?php else : ?>
                                <span class="tmnl-badge tmnl-badge-hidden"><?php esc_html_e( 'Hidden', 'elplan-kuchikomi-wall' ); ?></span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=tmnl-source-x_embed&tmnl_x_action=toggle&tmnl_x_id=' . $embed->id ), 'tmnl_x_toggle_' . $embed->id, '_tmnl_nonce' ) ); ?>">
                                <?php echo $embed->is_visible ? esc_html__( 'Hide', 'elplan-kuchikomi-wall' ) : esc_html__( 'Show', 'elplan-kuchikomi-wall' ); ?>
                            </a> |
                            <a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=tmnl-source-x_embed&tmnl_x_action=delete&tmnl_x_id=' . $embed->id ), 'tmnl_x_delete_' . $embed->id, '_tmnl_nonce' ) ); ?>"
                               onclick="return confirm('<?php echo esc_js( __( 'Are you sure you want to delete this?', 'elplan-kuchikomi-wall' ) ); ?>')" style="color:#a00;"><?php esc_html_e( 'Delete', 'elplan-kuchikomi-wall' ); ?></a>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>

        <h3><?php esc_html_e( 'Add Tweet', 'elplan-kuchikomi-wall' ); ?></h3>
        <form method="post">
            <?php wp_nonce_field( 'tmnl_add_x_embed', '_tmnl_nonce' ); ?>
            <p>
                <input type="url" name="tweet_url" class="regular-text" placeholder="https://x.com/username/status/123456789" required>
                <?php submit_button( __( 'Add', 'elplan-kuchikomi-wall' ), 'secondary', 'tmnl_add_x_embed', false ); ?>
            </p>
            <p class="description"><?php esc_html_e( 'Enter an X (Twitter) tweet URL. It will be displayed via oEmbed.', 'elplan-kuchikomi-wall' ); ?></p>
        </form>
        <?php
    }

    public function save_settings( $post_data ) {
        // X embed has no config settings, managed via URL list
    }

    public function get_normalized_reviews( $min_rating = 1 ) {
        $cached = $this->get_cached();
        $normalized = array();

        foreach ( $cached as $item ) {
            $normalized[] = array(
                'author_name'  => $item['author_name'] ?? '',
                'rating'       => null, // X posts don't have ratings
                'text'         => '',   // Text is in embed HTML
                'date'         => '',
                'source_type'  => 'x_embed',
                'source_label' => 'X',
                'external_id'  => $item['_tweet_url'] ?? null,
                'author_icon'  => null,
                'embed_html'   => $item['html'] ?? '',
                'url'          => $item['_tweet_url'] ?? '',
                'sort_order'   => $item['_sort_order'] ?? 999,
            );
        }

        return $normalized;
    }
}
