<?php
namespace Softech_Addons_for_Elementor\Includes;

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

use Elementor\Widget_Base;

if ( ! class_exists( '\\Elementor\\Widget_Base' ) ) {
    return;
}

abstract class SITS_Single_Post_Widget_Base extends Widget_Base {

    abstract protected function get_style_handle(): string;

    abstract protected function get_style_file(): string;

    abstract protected function get_script_handle(): string;

    abstract protected function get_script_file(): string;

    protected function register_widget_assets(): void {
        $url     = SITS_ELEMENTOR_ADDONS_PLUGIN_URL;
        $version = SITS_ELEMENTOR_ADDONS_VERSION;

        $style_handle = $this->get_style_handle();
        $style_file    = $this->get_style_file();
        $script_handle = $this->get_script_handle();
        $script_file   = $this->get_script_file();

        if ( $style_handle && ! wp_style_is( $style_handle, 'registered' ) ) {
            wp_register_style( $style_handle, $url . ltrim( $style_file, '/' ), [], $version );
        }

        if ( $script_handle && ! wp_script_is( $script_handle, 'registered' ) ) {
            wp_register_script( $script_handle, $url . ltrim( $script_file, '/' ), [ 'jquery' ], $version, true );
        }
    }

    public function get_style_depends() {
        $this->register_widget_assets();
        return [ $this->get_style_handle() ];
    }

    public function get_script_depends() {
        $this->register_widget_assets();
        return [ $this->get_script_handle() ];
    }

    public function get_categories() {
        return [ 'sits-single-post' ];
    }

    protected function get_render_post_id(): int {
    $post_id = absint( get_the_ID() );

    if ( ! $post_id ) {
        $post_id = absint( get_queried_object_id() );
    }

    if ( ! $post_id ) {
        return 0;
    }

    $post_type = get_post_type( $post_id );

    // Always exclude template/library types
    if ( in_array( $post_type, [ 'sits_hf_template', 'elementor_library' ], true ) ) {
        return 0;
    }

    // In the Elementor editor, the "current post" is the page being edited,
    // not a real post being previewed — so return 0 to show placeholder content.
    if ( defined( 'ELEMENTOR_VERSION' ) && \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
        return 0;
    }

    // In Elementor preview mode (front-end preview), same issue applies
    // unless this is actually a single post/page preview
    if ( defined( 'ELEMENTOR_VERSION' ) && \Elementor\Plugin::$instance->preview->is_preview_mode() ) {
        // Only return real ID if this is a single post/page, not a template
        $allowed_types = get_post_types( [ 'public' => true ], 'names' );
        $template_types = [ 'elementor_library', 'sits_hf_template' ];
        if ( in_array( $post_type, $template_types, true ) ) {
            return 0;
        }
    }

    return $post_id;
}

    protected function get_render_post(): ?\WP_Post {
        $post_id = $this->get_render_post_id();
        return $post_id ? get_post( $post_id ) : null;
    }

    protected function get_sample_post_title(): string {
        return esc_html__( 'Sample Post Title', 'softech-addons-for-elementor' );
    }

    protected function get_sample_post_excerpt(): string {
        return esc_html__( 'This is a sample excerpt used when no post is available in the editor preview.', 'softech-addons-for-elementor' );
    }

    protected function get_sample_post_content_html(): string {
        return '<p>' . esc_html__( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', 'softech-addons-for-elementor' ) . '</p><p>' . esc_html__( 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', 'softech-addons-for-elementor' ) . '</p>';
    }

    protected function get_current_post_title( string $fallback = '' ): string {
        $post_id = $this->get_render_post_id();
        $title   = $post_id ? (string) get_the_title( $post_id ) : '';

        if ( '' !== trim( $title ) ) {
            return $title;
        }

        return '' !== $fallback ? $fallback : $this->get_sample_post_title();
    }

    protected function get_current_post_excerpt( int $words = 25, string $fallback = '' ): string {
        $post_id = $this->get_render_post_id();
        $words   = max( 1, $words );

        if ( $post_id ) {
            $excerpt = trim( (string) get_the_excerpt( $post_id ) );
            if ( '' !== $excerpt ) {
                $excerpt = wp_strip_all_tags( strip_shortcodes( html_entity_decode( $excerpt, ENT_QUOTES, get_bloginfo( 'charset' ) ) ) );
                return wp_trim_words( $excerpt, $words, '...' );
            }

            $content = (string) get_post_field( 'post_content', $post_id );
            $content = wp_strip_all_tags( strip_shortcodes( html_entity_decode( $content, ENT_QUOTES, get_bloginfo( 'charset' ) ) ) );
            if ( '' !== trim( $content ) ) {
                return wp_trim_words( $content, $words, '...' );
            }
        }

        return '' !== $fallback ? $fallback : $this->get_sample_post_excerpt();
    }

    protected function get_current_post_content_html(): string {
        $post_id = $this->get_render_post_id();

        if ( $post_id ) {
            $content = (string) get_post_field( 'post_content', $post_id );
            if ( '' !== trim( $content ) ) {
                return (string) apply_filters( 'the_content', $content );
            }
        }

        return $this->get_sample_post_content_html();
    }

    protected function get_featured_image_data( string $size = 'large' ): array {
        $post_id   = $this->get_render_post_id();
        $image_id  = $post_id ? (int) get_post_thumbnail_id( $post_id ) : 0;
        $image_src = $image_id ? wp_get_attachment_image_src( $image_id, $size ) : false;
        $image_url = is_array( $image_src ) && ! empty( $image_src[0] ) ? (string) $image_src[0] : '';
        $image_w   = is_array( $image_src ) ? absint( $image_src[1] ?? 0 ) : 0;
        $image_h   = is_array( $image_src ) ? absint( $image_src[2] ?? 0 ) : 0;

        if ( '' === $image_url ) {
            $image_url = \Elementor\Utils::get_placeholder_image_src();
        }

        $alt      = $image_id ? (string) get_post_meta( $image_id, '_wp_attachment_image_alt', true ) : '';
        $caption  = $image_id ? (string) wp_get_attachment_caption( $image_id ) : '';

        return [
            'id'      => $image_id,
            'url'     => esc_url_raw( $image_url ),
            'width'   => $image_w,
            'height'  => $image_h,
            'alt'     => '' !== $alt ? $alt : $this->get_sample_post_title(),
            'caption'  => $caption,
        ];
    }

    protected function get_author_data(): array {
        $post_id = $this->get_render_post_id();
        $author_id = $post_id ? (int) get_post_field( 'post_author', $post_id ) : 0;
        $author = $author_id ? get_userdata( $author_id ) : null;

        return [
            'id'          => $author_id,
            'name'        => $author ? (string) $author->display_name : esc_html__( 'Author Name', 'softech-addons-for-elementor' ),
            'bio'         => $author ? (string) get_user_meta( $author_id, 'description', true ) : esc_html__( 'Sample author bio description goes here. This is a brief introduction about the author.', 'softech-addons-for-elementor' ),
            'avatar'      => $author_id ? get_avatar_url( $author_id, [ 'size' => 256 ] ) : '',
            'website'     => $author ? (string) $author->user_url : '',
            'post_count'   => $author ? count_user_posts( $author_id ) : 0,
            'social_links' => $this->get_author_social_links( $author_id ),
        ];
    }

    protected function get_author_social_links( int $author_id ): array {
        if ( ! $author_id ) {
            return [];
        }

        $fields = [
            'website'  => get_the_author_meta( 'user_url', $author_id ),
            'facebook' => get_the_author_meta( 'facebook', $author_id ),
            'twitter'  => get_the_author_meta( 'twitter', $author_id ),
            'x'        => get_the_author_meta( 'x', $author_id ),
            'instagram'=> get_the_author_meta( 'instagram', $author_id ),
            'linkedin' => get_the_author_meta( 'linkedin', $author_id ),
            'youtube'  => get_the_author_meta( 'youtube', $author_id ),
        ];

        $links = [];
        foreach ( $fields as $network => $url ) {
            $url = esc_url_raw( (string) $url );
            if ( '' !== $url ) {
                $links[ $network ] = $url;
            }
        }

        return $links;
    }

    protected function get_reading_time( int $post_id = 0 ): string {
        $post_id = $post_id ? $post_id : $this->get_render_post_id();
        if ( ! $post_id ) {
            return '1 min read';
        }

        $content = wp_strip_all_tags( (string) get_post_field( 'post_content', $post_id ) );
        $words   = str_word_count( $content );
        $mins    = max( 1, (int) ceil( $words / 200 ) );

        return sprintf(
            /* translators: %d is the estimated reading time in minutes. */
            esc_html__( '%d min read', 'softech-addons-for-elementor' ),
            $mins
        );
    }

    protected function get_term_list( string $taxonomy, string $separator = ', ' ): string {
        $post_id = $this->get_render_post_id();
        if ( ! $post_id ) {
            return '';
        }

        $terms = get_the_term_list( $post_id, $taxonomy, '', $separator, '' );
        return is_string( $terms ) ? $terms : '';
    }
}
