<?php

namespace Kanews\Kai\Audio;

use Kanews\Kai\Manager;
use Kanews\Kai\Support\Credits;
use Kanews\Kai\Support\Options;

class AudioBriefingController
{
    private $manager;
    private $postType    = 'kai_audio_brief';
    private $metaPrefix  = '_kai_audio_';
    private $slotCache   = null;

    public function __construct(Manager $manager)
    {
        $this->manager = $manager;
    }

    public function register(): void
    {
        add_action('init', [$this, 'registerPostType']);
        add_action('init', [$this, 'maybeSchedule']);
        add_action('kanews_kai_audio_briefing_cron', [$this, 'handleCron']);
        add_action('switch_theme', [$this, 'clearSchedule']);
        add_shortcode('kai_audio_briefings', [$this, 'renderShortcode']);
    }

    public function registerPostType(): void
    {
        if (!Options::get('kai-audio-enabled', false)) {
            return;
        }

        if (post_type_exists($this->postType)) {
            $this->registerMeta();
            return;
        }

        register_post_type($this->postType, [
            'labels' => [
                'name'          => __('KAI Ses Özetleri', 'kanews'),
                'singular_name' => __('KAI Ses Özeti', 'kanews'),
                'add_new'       => __('Yeni Özet Ekle', 'kanews'),
                'add_new_item'  => __('Yeni Ses Özeti', 'kanews'),
                'edit_item'     => __('Ses Özetini Düzenle', 'kanews'),
                'new_item'      => __('Yeni Ses Özeti', 'kanews'),
                'view_item'     => __('Ses Özetini Görüntüle', 'kanews'),
                'search_items'  => __('Ses Özeti Ara', 'kanews'),
                'not_found'     => __('Ses özeti bulunamadı', 'kanews'),
                'menu_name'     => __('Ses Özetleri', 'kanews'),
            ],
            'public'             => false,
            'exclude_from_search'=> true,
            'show_ui'            => false,
            'supports'           => ['title', 'editor'],
            'rewrite'            => false,
        ]);

        $this->registerMeta();
    }

    private function registerMeta(): void
    {
        $metaMap = [
            'file_url'   => ['type' => 'string'],
            'file_path'  => ['type' => 'string'],
            'slot'       => ['type' => 'string'],
            'date'       => ['type' => 'string'],
            'transcript' => ['type' => 'string'],
            'articles'   => [
                'type'   => 'array',
                'schema' => [
                    'type'  => 'array',
                    'items' => [
                        'type'       => 'object',
                        'properties' => [
                            'ID'      => ['type' => 'integer'],
                            'title'   => ['type' => 'string'],
                            'summary' => ['type' => 'string'],
                            'link'    => ['type' => 'string', 'format' => 'uri'],
                        ],
                    ],
                ],
            ],
        ];

        foreach ($metaMap as $suffix => $config) {
            $args = [
                'type'          => $config['type'],
                'single'        => true,
                'auth_callback' => '__return_true',
            ];
            
            // Array tipi için show_in_rest şemasını doğru şekilde yapılandır
            if (isset($config['schema']) && $config['type'] === 'array') {
                $args['show_in_rest'] = [
                    'schema' => $config['schema'],
                ];
            } else {
                $args['show_in_rest'] = true;
            }
            
            register_post_meta($this->postType, $this->metaKey($suffix), $args);
        }
    }

    public function maybeSchedule(): void
    {
        if (defined('WP_INSTALLING') && WP_INSTALLING) {
            return;
        }

        if (!Options::get('kai-audio-enabled', false)) {
            $this->clearSchedule();
            return;
        }

        if (!wp_next_scheduled('kanews_kai_audio_briefing_cron')) {
            wp_schedule_event(time() + (5 * MINUTE_IN_SECONDS), 'hourly', 'kanews_kai_audio_briefing_cron');
        }
    }

    public function handleCron(): void
    {
        if (!Options::get('kai-audio-enabled', false)) {
            return;
        }

        if (defined('WP_INSTALLING') && WP_INSTALLING) {
            return;
        }

        $result = $this->generatePendingBriefings();
        if (is_wp_error($result)) {
            error_log('KAI audio briefing cron error: ' . $result->get_error_message());
        }
    }

    public function clearSchedule(): void
    {
        $timestamp = wp_next_scheduled('kanews_kai_audio_briefing_cron');
        if ($timestamp) {
            wp_unschedule_event($timestamp, 'kanews_kai_audio_briefing_cron');
        }
    }

    private function generatePendingBriefings()
    {
        if (!Options::get('kai-audio-enabled', false)) {
            return [];
        }

        $slots = $this->getSlots();
        if (empty($slots)) {
            return [];
        }

        $state = get_option('kanews_kai_audio_briefing_state', []);
        $today = wp_date('Y-m-d');

        if (!is_array($state) || ($state['date'] ?? '') !== $today) {
            $state = ['date' => $today, 'done' => []];
        }

        $done        = $state['done'] ?? [];
        $now         = current_time('timestamp');
        $generated   = [];
        $stateDirty  = false;

        foreach ($slots as $slot) {
            if (in_array($slot['id'], $done, true)) {
                continue;
            }

            $slotTime = $this->slotTimestamp($slot, $today);
            if (!$slotTime || $now < $slotTime) {
                continue;
            }

            $result = $this->generateBriefingForSlot($slot, $today);
            if (is_wp_error($result)) {
                error_log('KAI audio briefing creation failed: ' . $result->get_error_message());
                continue;
            }

            $done[]      = $slot['id'];
            $generated[] = $slot['id'];
            $stateDirty  = true;
        }

        if ($stateDirty) {
            $state['done'] = array_values(array_unique($done));
            update_option('kanews_kai_audio_briefing_state', $state, false);
        }

        return $generated;
    }

    private function slotTimestamp(array $slot, string $dateString)
    {
        try {
            $timezone = wp_timezone();
            $datetime = new \DateTimeImmutable($dateString . ' ' . $slot['time'], $timezone);
            return $datetime->getTimestamp();
        } catch (\Exception $e) {
            return null;
        }
    }

    private function generateBriefingForSlot(array $slot, string $dateString)
    {
        if (!Options::get('kai-audio-enabled', false)) {
            return new \WP_Error('system_disabled', __('Sesli haber bülteni sistemi pasif durumda.', 'kanews'));
        }

        if (Options::get('kai-audio-paused', false)) {
            return new \WP_Error('system_paused', __('Sesli haber bülteni üretimi durduruldu (mevcut dosyalar gösterilmeye devam edecek).', 'kanews'));
        }

        $posts = $this->getPostsForBriefing();
        if (empty($posts)) {
            return new \WP_Error('no_posts', __('Haber bülteni için uygun haber bulunamadı.', 'kanews'));
        }

        $articles = $this->prepareArticles($posts);
        if (empty($articles)) {
            return new \WP_Error('no_articles', __('Seslendirilecek içerik bulunamadı.', 'kanews'));
        }

        if ($this->briefExists($slot['id'], $dateString)) {
            return new \WP_Error('already_exists', __('Bu zaman dilimi için özet oluşturuldu.', 'kanews'));
        }

        $slotTime = $this->slotTimestamp($slot, $dateString) ?: current_time('timestamp');
        $dateText = wp_date('j F Y', $slotTime);

        $transcript = $this->buildTranscript($slot, $articles, $dateText);
        if (!is_string($transcript) || '' === trim($transcript)) {
            return new \WP_Error('empty_transcript', __('Haber bülteni için yeterli kredi yok.', 'kanews'));
        }

        $content = $this->buildContent($slot, $articles, $dateText);
        $creditCost = $this->creditCost($transcript);
        if (!Credits::reduce($creditCost)) {
            return new \WP_Error('insufficient_credits', __('Haber bülteni için yeterli kredi yok.', 'kanews'));
        }

        $audioBinary = $this->manager->ai()->tts($transcript, $slot['voice']);
        if (!is_string($audioBinary) || '' === trim($audioBinary)) {
            return new \WP_Error('tts_failed', __('Ses dosyası oluşturulamadı (boş veri).', 'kanews'));
        }

        $fileInfo = $this->persistAudio($audioBinary, $slot, $dateString);
        if (is_wp_error($fileInfo)) {
            return $fileInfo;
        }

        $postTitle = sprintf('%s %s Haber Bülteni', $dateText, $slot['label']);
        $postId    = wp_insert_post([
            'post_type'    => $this->postType,
            'post_status'  => 'publish',
            'post_title'   => $postTitle,
            'post_content' => $content,
        ], true);

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

        update_post_meta($postId, $this->metaKey('file_url'), $fileInfo['url']);
        update_post_meta($postId, $this->metaKey('file_path'), $fileInfo['path']);
        update_post_meta($postId, $this->metaKey('slot'), $slot['id']);
        update_post_meta($postId, $this->metaKey('date'), $dateString);
        update_post_meta($postId, $this->metaKey('transcript'), $transcript);
        update_post_meta($postId, $this->metaKey('articles'), $articles);

        return $postId;
    }

    private function briefExists(string $slotId, string $dateString): bool
    {
        $existing = get_posts([
            'post_type'      => $this->postType,
            'posts_per_page' => 1,
            'post_status'    => 'any',
            'fields'         => 'ids',
            'meta_query'     => [
                ['key' => $this->metaKey('slot'), 'value' => $slotId],
                ['key' => $this->metaKey('date'), 'value' => $dateString],
            ],
        ]);

        return !empty($existing);
    }

    private function getPostsForBriefing(int $limit = 5): array
    {
        $baseArgs = [
            'post_type'      => 'post',
            'post_status'    => 'publish',
            'posts_per_page' => $limit,
            'orderby'        => 'date',
            'order'          => 'DESC',
        ];

        // Prefer fresh content from the last 24 hours.
        $freshArgs = $baseArgs + [
            'date_query' => [
                [
                    'after'     => '1 day ago',
                    'inclusive' => true,
                ],
            ],
        ];

        $posts = get_posts($freshArgs);
        if (!empty($posts)) {
            return $posts;
        }

        // No new posts: fall back to the most recently published items.
        $recentPosts = get_posts($baseArgs);
        return is_array($recentPosts) ? $recentPosts : [];
    }

    private function prepareArticles(array $posts): array
    {
        $items = [];
        foreach ($posts as $post) {
            $title   = wp_strip_all_tags(get_the_title($post));
            $summary = $this->getPostSummary($post);

            if ('' === trim($summary)) {
                // Fallback so the script is never empty.
                $summary = __('Detayları sitemizde okuyabilirsiniz.', 'kanews');
            }

            if ('' === trim($title)) {
                continue;
            }

            $items[] = [
                'ID'      => $post->ID,
                'title'   => $title,
                'summary' => $summary,
                'link'    => get_permalink($post),
            ];
        }
        return $items;
    }

    private function getPostSummary($post): string
    {
        // 1) Excerpt
        if (!empty($post->post_excerpt)) {
            return wp_strip_all_tags($post->post_excerpt);
        }

        // 2) Stored summary meta
        $stored = get_post_meta($post->ID, 'kanews_post_summary', true);
        if (!empty($stored)) {
            return wp_strip_all_tags($stored);
        }

        // 3) Body fallback
        $content = wp_strip_all_tags(strip_shortcodes($post->post_content));
        return wp_trim_words($content, 40, '...');
    }

    private function buildTranscript(array $slot, array $articles, string $dateText): string
    {
        $lines = $this->introLines($slot, $dateText, count($articles));
        $script = implode("\n\n", $lines) . "\n\n";
        $index  = 1;
        foreach ($articles as $article) {
            $summary = $this->trimSummary($article['summary'], $index === 1);
            $script .= sprintf(
                "%d. %s. %s\n",
                $index++,
                $article['title'],
                $summary
            );
        }
        $script .= "\n" . __('Dinlediğiniz için teşekkürler, bir sonraki özette görüşmek üzere.', 'kanews');
        return $script;
    }

    private function buildContent(array $slot, array $articles, string $dateText): string
    {
        $lines = $this->introLines($slot, $dateText, count($articles));
        $html  = '';

        foreach ($lines as $line) {
            $html .= '<p>' . esc_html($line) . '</p>';
        }

        $html .= '<ol class="kai-audio-briefing-list">';
        foreach ($articles as $article) {
            static $i = 1;
            $summary = $this->trimSummary($article['summary'], $i === 1);
            $html .= sprintf(
                '<li><strong>%s</strong>: %s<br><a href="%s" target="_blank" rel="noopener noreferrer">%s</a></li>',
                esc_html($article['title']),
                esc_html($summary),
                esc_url($article['link']),
                esc_html__('Haberi oku', 'kanews')
            );
            $i++;
        }
        $html .= '</ol>';
        return $html;
    }

    private function introLines(array $slot, string $dateText, int $count): array
    {
        $siteName = get_bloginfo('name');
        return [
            sprintf('%s! %s gününün %s haber bültenine hoş geldiniz!', $slot['greeting'], $dateText, $slot['label']),
            sprintf('%s olarak gündemin öne çıkan başlıklarını sizler için topladık.', $siteName),
            sprintf('Ben KAI, %d başlıkta hızlı bir tur atacağız. Kulaklığınızı kapın, kısa bir molada size eşlik ediyorum.', $count),
            __('İşte başlıyoruz...', 'kanews'),
        ];
    }

    /**
     * Trim summaries to keep narration concise. First item may be slightly longer.
     */
    private function trimSummary(string $summary, bool $isFirst): string
    {
        $limit = $isFirst ? 80 : 60; // roughly 1–1.5 paragraphs for the first item
        return wp_trim_words($summary, $limit, '...');
    }

    private function creditCost(string $text): int
    {
        return Credits::calculateFromContent($text);
    }

    private function persistAudio($audioBinary, array $slot, string $dateString)
    {
        $day   = wp_date('d');
        $month = wp_date('m');
        $year  = wp_date('Y');

        $baseDir   = trailingslashit(ABSPATH . 'kai-audio');
        $targetDir = $baseDir . $year . DIRECTORY_SEPARATOR . $month . DIRECTORY_SEPARATOR . $day . DIRECTORY_SEPARATOR;

        if (!wp_mkdir_p($targetDir)) {
            return new \WP_Error('directory_error', __('Ses dosyası için klasör oluşturulamadı.', 'kanews'));
        }

        $fileName = sprintf('kai-%s-%s.mp3', str_replace('-', '', $dateString), sanitize_file_name($slot['id']));
        $filePath = $targetDir . $fileName;

        if (!file_put_contents($filePath, $audioBinary)) {
            return new \WP_Error('file_write_error', __('Ses dosyası kaydedilemedi.', 'kanews'));
        }

        if (!filesize($filePath)) {
            @unlink($filePath);
            return new \WP_Error('file_write_error', __('Ses dosyası kaydedilemedi (boş).', 'kanews'));
        }

        $relative = ltrim(str_replace(ABSPATH, '', $filePath), '/');
        $relative = str_replace(DIRECTORY_SEPARATOR, '/', $relative);
        $url      = home_url('/' . $relative);

        return [
            'path' => $filePath,
            'url'  => $url,
        ];
    }

    private function metaKey(string $suffix): string
    {
        return $this->metaPrefix . $suffix;
    }

    private function getSlots(): array
    {
        if (null !== $this->slotCache) {
            return $this->slotCache;
        }

        $voice = Options::get('kai-audio-voice', 'alloy');
        $slots = [
            [
                'id'       => 'morning',
                'time'     => '08:00',
                'greeting' => __('Günaydın', 'kanews'),
                'label'    => __('sabah', 'kanews'),
                'voice'    => $voice,
            ],
            [
                'id'       => 'noon',
                'time'     => '14:00',
                'greeting' => __('Merhaba', 'kanews'),
                'label'    => __('öğle', 'kanews'),
                'voice'    => $voice,
            ],
            [
                'id'       => 'evening',
                'time'     => '20:00',
                'greeting' => __('İyi akşamlar', 'kanews'),
                'label'    => __('akşam', 'kanews'),
                'voice'    => $voice,
            ],
        ];

        $dailyCount = max(1, min(count($slots), (int) Options::get('kai-audio-daily-count', 3)));
        $this->slotCache = array_slice($slots, 0, $dailyCount);
        return $this->slotCache;
    }

    public function renderShortcode($atts = []): string
    {
        if (!Options::get('kai-audio-enabled', false)) {
            return '<p>' . esc_html__('Sesli haber bülteni sistemi şu anda pasif durumda.', 'kanews') . '</p>';
        }

        $atts = shortcode_atts(['limit' => 3], $atts, 'kai_audio_briefings');
        $query = new \WP_Query([
            'post_type'      => $this->postType,
            'posts_per_page' => (int) $atts['limit'],
            'post_status'    => 'publish',
            'orderby'        => 'date',
            'order'          => 'DESC',
        ]);

        if (!$query->have_posts()) {
            return '<p>' . esc_html__('Bulunamadı.', 'kanews') . '</p>';
        }

        ob_start();
        echo '<div class="kai-audio-briefings">';
        while ($query->have_posts()) {
            $query->the_post();
            echo $this->renderCard(get_the_ID());
        }
        echo '</div>';
        wp_reset_postdata();
        return ob_get_clean();
    }

    public function renderCard(int $postId): string
    {
        $fileUrl   = get_post_meta($postId, $this->metaKey('file_url'), true);
        $slot      = get_post_meta($postId, $this->metaKey('slot'), true);
        $dateValue = get_post_meta($postId, $this->metaKey('date'), true);
        $transcript= get_post_meta($postId, $this->metaKey('transcript'), true);
        $articles  = get_post_meta($postId, $this->metaKey('articles'), true);

        $dateDisplay = '';
        if (!empty($dateValue)) {
            $timestamp = strtotime($dateValue . ' 00:00:00');
            if ($timestamp) {
                $dateDisplay = wp_date('d F Y', $timestamp);
            }
        }
        if (empty($dateDisplay)) {
            $dateDisplay = get_the_date('', $postId);
        }

        $slotLabel = kanews_kai_get_audio_slot_label($slot);

        $transcriptHtml = '';
        if (!empty($transcript)) {
            $paragraphs = array_filter(array_map('trim', preg_split("/\r\n|\n|\r/", $transcript)));
            if (!empty($paragraphs)) {
                $transcriptHtml .= '<div class="kai-audio-briefing-transcript-body">';
                foreach ($paragraphs as $paragraph) {
                    $transcriptHtml .= '<p>' . esc_html($paragraph) . '</p>';
                }
                $transcriptHtml .= '</div>';
            }
        }

        $linksHtml = '';
        if (is_array($articles) && !empty($articles)) {
            $linksHtml .= '<ul class="kai-audio-briefing-links-list">';
            foreach ($articles as $article) {
                if (empty($article['link']) || empty($article['title'])) {
                    continue;
                }
                $linksHtml .= sprintf(
                    '<li><a href="%s" target="_blank" rel="noopener noreferrer">%s</a></li>',
                    esc_url($article['link']),
                    esc_html($article['title'])
                );
            }
            $linksHtml .= '</ul>';
        }

        ob_start();
        ?>
        <div class="kai-audio-briefing-card">
            <div class="kai-audio-briefing-card-inner">
                <?php if (!empty($fileUrl)) : ?>
                    <div class="kai-audio-briefing-player">
                        <div class="kai-sc-player" data-player-id="<?php echo esc_attr($postId); ?>">
                            <div class="kai-sc-player__wave-bars">
                                <span></span><span></span><span></span><span></span><span></span>
                            </div>
                            <div class="kai-sc-header mb-1 d-flex align-items-start justify-content-between no-gutters gap-10">
                                <div class="col">
                                    <?php if (!empty($slotLabel)) : ?>
                                        <p class="kanews-label"><?php echo esc_html($slotLabel); ?></p>
                                    <?php endif; ?>
                                    <div class="kai-sc-player__track font-size-xl"><?php echo esc_html(get_the_title($postId)); ?></div>
                                </div>
                                <div class="col-auto color-white d-flex flex-wrap align-items-center gap-10">
                                    <?php if (!empty($transcriptHtml)) :
                                        $transcriptTemplateId = 'kanews-modal-audio-transcript-' . $postId;
                                        ?>
                                        <button type="button" class="kai-audio-briefing-modal-trigger color-white"
                                            data-toggle="<?php echo esc_attr($transcriptTemplateId); ?>"
                                            data-title="<?php esc_attr_e('Metni oku', 'kanews'); ?>"
                                            aria-expanded="false">
                                            <span class="kai-audio-briefing-modal-icon">
                                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18"><path fill="currentColor" d="M16,6a1,1,0,0,0-1-1H3A1,1,0,0,0,3,7H8V18a1,1,0,0,0,2,0V7h5A1,1,0,0,0,16,6Zm5,5H15a1,1,0,0,0,0,2h2v5a1,1,0,0,0,2,0V13h2a1,1,0,0,0,0-2Z"></path></svg>
                                            </span>
                                        </button>
                                    <?php endif; ?>
                                    <?php if (!empty($linksHtml)) : ?>
                                        <button type="button" class="kai-audio-briefing-modal-trigger color-white"
                                            data-toggle="kanews-modal-audio-links-<?php echo esc_attr($postId); ?>"
                                            aria-expanded="false">
                                            <span class="kai-audio-briefing-modal-icon">
                                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18"><path fill="currentColor" d="m12.11 15.39-3.88 3.88a2.47 2.47 0 0 1-3.5 0 2.46 2.46 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42Zm-3.28-.22a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42ZM21 18h-1v-1a1 1 0 0 0-2 0v1h-1a1 1 0 0 0 0 2h1v1a1 1 0 0 0 2 0v-1h1a1 1 0 0 0 0-2Zm-4.19-4.47 3.88-3.89a4.48 4.48 0 0 0-6.33-6.33l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.47 2.47 0 0 1 3.5 0 2.46 2.46 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0Z"></path></svg>
                                            </span>
                                        </button>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="kai-sc-player__glow"></div>
                            <div class="kai-sc-player__panel">
                                <div class="kai-sc-player__art">
                                    <button type="button" class="kai-sc-player__play" aria-label="<?php esc_attr_e('Ses özetini oynat', 'kanews'); ?>">
                                        <span class="kai-sc-player__play-icon"></span>
                                    </button>
                                </div>
                                <div class="kai-sc-player__info">
                                    <div class="kai-sc-player__progress-track" role="presentation">
                                        <div class="kai-sc-player__progress-fill"></div>
                                    </div>
                                    <div class="kai-sc-player__time">
                                        <span class="kai-sc-player__time-current">0:00</span>
                                        <span class="kai-sc-player__time-duration">--:--</span>
                                    </div>
                                </div>
                            </div>
                            <audio class="kai-sc-player__audio" preload="none" src="<?php echo esc_url($fileUrl); ?>">
                                <?php esc_html_e('Tarayıcınız ses öğesini desteklemiyor.', 'kanews'); ?>
                            </audio>
                        </div>
                    </div>
                <?php endif; ?>

                <?php if (!empty($transcriptHtml)) :
                    $transcriptTemplateId = 'kanews-modal-audio-transcript-' . $postId;
                    ?>
                    <div id="<?php echo esc_attr($transcriptTemplateId); ?>" class="kanews-modal kanews-modal-audio is-hidden" aria-hidden="true">
                        <div class="kanews-modal-content">
                            <div class="kanews-modal-title"><?php esc_html_e('Metni oku', 'kanews'); ?></div>
                            <div data-toggle="<?php echo esc_attr($transcriptTemplateId); ?>" class="kanews-modal-close-btn"><i class="icon-close"></i></div>
                            <div class="kanews-modal-content-inner"><?php echo $transcriptHtml; ?></div>
                        </div>
                    </div>
                <?php endif; ?>

                <?php if (!empty($linksHtml)) : ?>
                    <div id="kanews-modal-audio-links-<?php echo esc_attr($postId); ?>" class="kanews-modal kanews-modal-audio is-hidden" aria-hidden="true">
                        <div class="kanews-modal-content">
                            <div class="kanews-modal-title"><?php esc_html_e('Kaynak bağlantıları', 'kanews'); ?></div>
                            <div data-toggle="kanews-modal-audio-links-<?php echo esc_attr($postId); ?>" class="kanews-modal-close-btn"><i class="icon-close"></i></div>
                            <div class="kanews-modal-content-inner"><?php echo $linksHtml; ?></div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }
}

