<?php
/**
 * Handles the Text-to-Speech column shown on post-list screens (edit.php).
 *
 * Registers:
 *   - `manage_{post_type}_posts_columns`        filter (column header)
 *   - `manage_{post_type}_posts_custom_column`  action (column content)
 *   - `admin_head`                              style enqueue (dynamic player CSS variables)
 *   - `admin_enqueue_scripts`                   footer-script enqueue (column tfoot fixup)
 *
 * Extracted from Mementor_TTS_Admin to keep that class focused.
 *
 * @package TTSWP
 */

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

class Mementor_TTS_Admin_Columns {

    /**
     * Slug used as a prefix for style/script handles.
     *
     * @var string
     */
    private $plugin_name;

    /**
     * Plugin version, used as a cache-busting query-string on assets.
     *
     * @var string
     */
    private $version;

    public function __construct( $plugin_name, $version ) {
        $this->plugin_name = $plugin_name;
        $this->version     = $version;
    }

    /**
     * Register all WP hooks owned by this class.
     * Called once from Mementor_TTS_Admin::__construct.
     */
    public function register_hooks() {
        // Late priority — run after other plugins (WPML, WooCommerce) have added their columns.
        add_action( 'admin_init', array( $this, 'add_tts_columns_to_post_types' ), 2000 );
        add_action( 'admin_head', array( $this, 'add_player_columns_styles' ) );
    }

    /**
     * Add styles for players in columns by dynamically updating and enqueueing CSS files
     */
    public function add_player_columns_styles() {
        $bg_color     = get_option('mementor_tts_player_bg_color', '#f5eee9');
        $text_color   = get_option('mementor_tts_player_text_color', '#0e0e0f');
        $accent_color = get_option('mementor_tts_player_accent_color', '#2271b1');

        $dynamic_css_variables = "
/* Mementor TTS - Dynamic Player Variables */
:root {
    --player-bg-color: " . esc_attr($bg_color) . ";
    --player-text-color: " . esc_attr($text_color) . ";
    --player-play-color: " . esc_attr($accent_color) . ";
}";

        wp_enqueue_style(
            $this->plugin_name . '-admin-columns',
            MEMENTOR_TTS_PLUGIN_URL . 'admin/css/mementor-tts-admin-columns.css',
            array(),
            $this->version
        );

        wp_enqueue_style(
            $this->plugin_name . '-player-columns',
            MEMENTOR_TTS_PLUGIN_URL . 'admin/css/mementor-tts-player-columns.css',
            array($this->plugin_name . '-admin-columns'),
            $this->version
        );

        wp_add_inline_style($this->plugin_name . '-player-columns', $dynamic_css_variables);
    }

    /**
     * Add TTS column to post list tables for enabled post types
     */
    public function add_tts_columns_to_post_types() {
        $enabled_post_types = get_option('mementor_tts_post_types', array('post'));

        if (empty($enabled_post_types)) {
            return;
        }

        foreach ($enabled_post_types as $post_type) {
            add_filter('manage_' . $post_type . '_posts_columns', function($columns) {
                // Build the column header — image with screen-reader text for Screen Options label.
                $header_url    = MEMENTOR_TTS_PLUGIN_URL . 'admin/images/icons/tts-header-v5.png';
                $column_header = '<img src="' . esc_url($header_url) . '" alt="TTS" width="66" height="18" style="vertical-align: middle;">';
                $column_header .= '<span class="screen-reader-text">' . __('Text to Speech (TTS)', 'text-to-speech-tts') . '</span>';

                // Insert after 'title' (standard) or 'name' (WooCommerce products).
                $new_columns = array();
                $inserted    = false;

                foreach ($columns as $key => $value) {
                    $new_columns[$key] = $value;

                    if (!$inserted && ($key === 'title' || $key === 'name')) {
                        $new_columns['mementor_tts'] = $column_header;
                        $inserted = true;
                    }
                }

                if (!$inserted) {
                    $new_columns['mementor_tts'] = $column_header;
                }

                return $new_columns;
            }, 99);

            add_action('manage_' . $post_type . '_posts_custom_column', array($this, 'render_tts_column'), 10, 2);
        }

        add_action('admin_enqueue_scripts', array($this, 'enqueue_column_footer_script'));
    }

    /**
     * Enqueue script for TTS column footer styling
     */
    public function enqueue_column_footer_script($hook) {
        if ($hook !== 'edit.php') {
            return;
        }

        $enabled_post_types = get_option('mementor_tts_post_types', array('post'));

        $screen = get_current_screen();
        if (!$screen || !in_array($screen->post_type, $enabled_post_types)) {
            return;
        }

        wp_register_script(
            'mementor-tts-admin-columns-js',
            '',
            array('jquery'),
            $this->version,
            true
        );

        wp_enqueue_script('mementor-tts-admin-columns-js');

        wp_add_inline_script('mementor-tts-admin-columns-js', '
            document.addEventListener("DOMContentLoaded", function() {
                const footerCells = document.querySelectorAll("tfoot td.mementor_tts");
                if (footerCells.length > 0) {
                    footerCells.forEach(function(cell) {
                        if (!cell.querySelector(".mementor-tts-logoicon-text")) {
                            const headerCell = document.querySelector("th#mementor_tts");
                            if (headerCell) {
                                cell.innerHTML = headerCell.innerHTML;
                            }
                        }
                    });
                }
            });
        ');
    }

    /**
     * Render the TTS column content
     *
     * @param string $column_name The name of the column to render
     * @param int    $post_id     The ID of the post being displayed
     */
    public function render_tts_column($column_name, $post_id) {
        if ($column_name !== 'mementor_tts') {
            return;
        }

        $language_code = 'en';
        if (defined('ICL_LANGUAGE_CODE')) {
            $language_code = ICL_LANGUAGE_CODE;
        } else {
            $language_code = get_option('mementor_tts_language', 'en');
        }

        $audio_exists = false;
        $audio_url    = '';

        // First, check post meta for audio URL (handles both local and offloaded files).
        $audio_url_meta = get_post_meta($post_id, '_mementor_tts_audio_url', true);

        if (!empty($audio_url_meta)) {
            $audio_exists = true;
            $audio_url    = $audio_url_meta;
        } else {
            // Fallback: check language-specific meta, then filesystem for legacy files.
            $lang_meta = get_post_meta($post_id, '_mementor_tts_audio_url_' . $language_code, true);
            if (!empty($lang_meta)) {
                $audio_exists = true;
                $audio_url    = $lang_meta;
            } else {
                $upload_dir = wp_upload_dir();
                $audio_dir  = $upload_dir['basedir'] . '/text-to-speech-tts/';

                $possible_files = array(
                    'mementor-' . $post_id . '-' . $language_code . '.mp3',
                    'mementor-' . $post_id . '-en.mp3',
                    'post-' . $post_id . '-' . $language_code . '.mp3',
                    'post-' . $post_id . '.mp3',
                );

                foreach ($possible_files as $filename) {
                    if (file_exists($audio_dir . $filename)) {
                        $audio_exists = true;
                        $audio_url    = $upload_dir['baseurl'] . '/text-to-speech-tts/' . $filename;
                        break;
                    }
                }
            }
        }

        $processing  = get_post_meta($post_id, '_mementor_tts_processing', true);
        $post_status = get_post_status($post_id);

        /**
         * Filter to allow PRO / multi-language integrations to render language-specific audio controls.
         *
         * @param bool   $rendered     Whether the column was rendered by a filter.
         * @param int    $post_id      The post ID.
         * @param bool   $audio_exists Whether audio exists for this post.
         * @param string $audio_url    The audio URL if exists.
         * @param bool   $processing   Whether audio is being processed.
         * @param string $post_status  The post status.
         */
        $rendered_by_filter = apply_filters('mementor_tts_render_column', false, $post_id, $audio_exists, $audio_url, $processing, $post_status);

        if ($rendered_by_filter) {
            return;
        }

        $icon_play     = MEMENTOR_TTS_PLUGIN_URL . 'admin/images/icons/list-play2.svg';
        $icon_redo     = MEMENTOR_TTS_PLUGIN_URL . 'admin/images/icons/list-redo.svg';
        $icon_delete   = MEMENTOR_TTS_PLUGIN_URL . 'admin/images/icons/list-delete.svg';
        $icon_create   = MEMENTOR_TTS_PLUGIN_URL . 'admin/images/icons/list-create.svg';
        $icon_download = MEMENTOR_TTS_PLUGIN_URL . 'admin/images/icons/list-download.svg';

        echo '<div class="mementor-tts-column-controls">';

        if ($audio_exists) {
            $download_filename = 'tts-' . $post_id . '.mp3';
            // Route downloads through the AJAX proxy so `Content-Disposition:
            // attachment` is always respected, including for CDN-hosted files.
            $download_url = add_query_arg(
                array(
                    'action'  => 'mementor_tts_download_audio',
                    'post_id' => $post_id,
                    'nonce'   => wp_create_nonce('mementor_tts_nonce'),
                ),
                admin_url('admin-ajax.php')
            );
            echo '<a href="#" class="mementor-tts-play-button" data-audio-url="' . esc_url($audio_url) . '" data-tooltip="' . esc_attr__('Play audio', 'text-to-speech-tts') . '">';
            echo '<img src="' . esc_url($icon_play) . '" alt="" width="18" height="18">';
            echo '</a>';
            echo '<a href="' . esc_url($download_url) . '" class="mementor-tts-download-button" download="' . esc_attr($download_filename) . '" data-tooltip="' . esc_attr__('Download audio', 'text-to-speech-tts') . '">';
            echo '<img src="' . esc_url($icon_download) . '" alt="" width="18" height="18">';
            echo '</a>';
            echo '<a href="#" class="mementor-tts-generate-button mementor-tts-regenerate" data-post-id="' . esc_attr($post_id) . '" data-tooltip="' . esc_attr__('Regenerate audio', 'text-to-speech-tts') . '">';
            echo '<img src="' . esc_url($icon_redo) . '" alt="" width="18" height="18">';
            echo '</a>';
            echo '<a href="#" class="mementor-tts-delete-button" data-post-id="' . esc_attr($post_id) . '" data-tooltip="' . esc_attr__('Delete audio', 'text-to-speech-tts') . '">';
            echo '<img src="' . esc_url($icon_delete) . '" alt="" width="18" height="18">';
            echo '</a>';
        } elseif ($processing) {
            echo '<span class="mementor-tts-processing">' . esc_html__('Processing...', 'text-to-speech-tts') . '</span>';
            echo '<a href="#" class="mementor-tts-cancel-button" data-post-id="' . esc_attr($post_id) . '" data-tooltip="' . esc_attr__('Cancel processing', 'text-to-speech-tts') . '">';
            echo '<span class="dashicons dashicons-no-alt"></span>';
            echo '</a>';
        } elseif (in_array($post_status, array('publish', 'future', 'draft', 'pending', 'private'))) {
            echo '<a href="#" class="mementor-tts-generate-button" data-post-id="' . esc_attr($post_id) . '" data-tooltip="' . esc_attr__('Generate audio', 'text-to-speech-tts') . '">';
            echo '<img src="' . esc_url($icon_create) . '" alt="" width="18" height="18"> ' . esc_html__('Generate', 'text-to-speech-tts');
            echo '</a>';
        } else {
            echo '<span class="mementor-tts-not-published">' . esc_html__('Save draft to generate audio', 'text-to-speech-tts') . '</span>';
        }

        echo '</div>';
    }
}
