<?php
/**
 * Speech to Text - Transcribe Files Admin Page
 *
 * @package    TTSWP
 * @subpackage Mementor_TTS/admin/partials
 */

// Check if this file is called directly
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

// Verify user capabilities
if (!current_user_can('manage_options')) {
    wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'text-to-speech-tts'));
}

// Make sure plugin functions are available
if (!function_exists('is_plugin_active')) {
    include_once(ABSPATH . 'wp-admin/includes/plugin.php');
}

// Check if user has a paid plan via SaaS
$is_pro_active = ttswp_has_paid_plan();

// Get transcriptions
require_once MEMENTOR_TTS_PLUGIN_DIR . 'includes/class-mementor-tts-transcriptions.php';
$transcriptions_manager = Mementor_TTS_Transcriptions::get_instance();
$transcriptions = $transcriptions_manager->get_user_transcriptions();

// Supported languages for transcription
$supported_languages = array(
    'auto' => __('Auto Detect', 'text-to-speech-tts'),
    'en' => __('English', 'text-to-speech-tts'),
    'es' => __('Spanish', 'text-to-speech-tts'),
    'fr' => __('French', 'text-to-speech-tts'),
    'de' => __('German', 'text-to-speech-tts'),
    'it' => __('Italian', 'text-to-speech-tts'),
    'pt' => __('Portuguese', 'text-to-speech-tts'),
    'pl' => __('Polish', 'text-to-speech-tts'),
    'tr' => __('Turkish', 'text-to-speech-tts'),
    'ru' => __('Russian', 'text-to-speech-tts'),
    'nl' => __('Dutch', 'text-to-speech-tts'),
    'cs' => __('Czech', 'text-to-speech-tts'),
    'ar' => __('Arabic', 'text-to-speech-tts'),
    'zh' => __('Chinese', 'text-to-speech-tts'),
    'ja' => __('Japanese', 'text-to-speech-tts'),
    'ko' => __('Korean', 'text-to-speech-tts'),
    'hi' => __('Hindi', 'text-to-speech-tts'),
);
?>

<?php
$tts_page_title = __('Speech to Text', 'text-to-speech-tts');
$tts_topbar_actions = '';
if (!$is_pro_active) {
    $tts_topbar_actions = '<a href="' . esc_url(admin_url('admin.php?page=text-to-speech-tts-upgrade')) . '" class="tts-btn tts-btn-primary">' . esc_html__('Upgrade to PRO', 'text-to-speech-tts') . '</a>';
}
$tts_requires_connection = true; // gate page behind SaaS connection

include MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/layout-open.php';
?>
<?php include(MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/navigation.php'); ?>

            <?php if (!$is_pro_active): ?>
                <!-- PRO Feature Notice -->
                <div class="mementor-tts-pro-upsell" style="text-align: center; padding: 40px;">
                    <span class="dashicons dashicons-microphone" style="font-size: 48px; color: #7854E4; margin-bottom: 20px; display: block;"></span>
                    <h3 style="padding-left: 35px;"><?php esc_html_e('Speech to Text Transcription is a PRO Feature', 'text-to-speech-tts'); ?></h3>
                    <p style="max-width: 600px; margin: 0 auto 20px; font-size: 16px;">
                        <?php esc_html_e('Upgrade to PRO to transcribe audio and video files to text with support for multiple formats, automatic language detection, audio event tagging, precise timestamps, and export to TXT, DOCX, or JSON formats.', 'text-to-speech-tts'); ?>
                    </p>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-upgrade')); ?>" class="button button-primary button-hero">
                        <span class="dashicons dashicons-star-filled" style="margin-top: 12px; margin-right: 5px;"></span>
                        <?php esc_html_e('See what\'s included in PRO', 'text-to-speech-tts'); ?>
                    </a>
                </div>
            <?php endif; ?>

            <div class="mementor-stt-content-wrapper" <?php echo (!$is_pro_active) ? 'style="pointer-events: none; opacity: 0.6;"' : ''; ?>>

            <div id="mementor-stt-messages"></div>

            <!-- Upload Section Card -->
            <div class="tts-card">
                <div class="tts-card-header">
                    <h3 class="tts-card-title"><?php esc_html_e('Upload Audio or Video File', 'text-to-speech-tts'); ?></h3>
                </div>

                <div class="mementor-stt-upload-area" id="mementor-stt-upload-area">
                    <div class="mementor-stt-upload-icon">
                        <span class="dashicons dashicons-cloud-upload"></span>
                    </div>
                    <h3><?php esc_html_e('Drag & Drop your file here', 'text-to-speech-tts'); ?></h3>
                    <p><?php esc_html_e('or', 'text-to-speech-tts'); ?></p>
                    <button type="button" class="button button-primary" id="mementor-stt-select-file">
                        <?php esc_html_e('Select File', 'text-to-speech-tts'); ?>
                    </button>
                    <input type="file" id="mementor-stt-file-input" accept="audio/*,video/*" style="display: none;">
                    <p class="mementor-stt-upload-info">
                        <?php esc_html_e('Supported formats: MP3, WAV, MP4, AVI, MOV, and more', 'text-to-speech-tts'); ?>
                    </p>
                </div>

                <div class="mementor-stt-file-preview" id="mementor-stt-file-preview" style="display: none;">
                    <div class="mementor-stt-file-info">
                        <span class="dashicons dashicons-media-audio"></span>
                        <div class="mementor-stt-file-details">
                            <strong id="mementor-stt-file-name"></strong>
                            <span id="mementor-stt-file-size"></span>
                        </div>
                        <button type="button" class="button" id="mementor-stt-remove-file">
                            <span class="dashicons dashicons-no"></span>
                        </button>
                    </div>
                </div>

                <!-- Transcription Options -->
                <div class="mementor-stt-options">
                    <h3><?php esc_html_e('Transcription Options', 'text-to-speech-tts'); ?></h3>

                    <div class="mementor-stt-options-grid">
                        <div class="mementor-stt-option-row">
                            <label for="mementor-stt-language">
                                <strong><?php esc_html_e('Primary Language', 'text-to-speech-tts'); ?></strong>
                            </label>
                            <select id="mementor-stt-language" class="mementor-stt-select">
                                <?php foreach ($supported_languages as $code => $name): ?>
                                    <option value="<?php echo esc_attr($code); ?>"><?php echo esc_html($name); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="mementor-stt-option-row">
                            <label>
                                <input type="checkbox" id="mementor-stt-tag-events" checked>
                                <div>
                                    <strong><?php esc_html_e('Tag Audio Events', 'text-to-speech-tts'); ?></strong>
                                    <span class="description"><?php esc_html_e('Identify laughter, applause, music, etc.', 'text-to-speech-tts'); ?></span>
                                </div>
                            </label>
                        </div>

                        <div class="mementor-stt-option-row">
                            <label>
                                <input type="checkbox" id="mementor-stt-include-timestamps" checked>
                                <div>
                                    <strong><?php esc_html_e('Include Subtitles/Timestamps', 'text-to-speech-tts'); ?></strong>
                                    <span class="description"><?php esc_html_e('Add timing information for each segment', 'text-to-speech-tts'); ?></span>
                                </div>
                            </label>
                        </div>
                    </div>
                </div>

                <div class="mementor-stt-actions">
                    <button type="button" class="tts-btn tts-btn-primary" id="mementor-stt-transcribe" disabled>
                        <span class="dashicons dashicons-media-text"></span>
                        <?php esc_html_e('Transcribe', 'text-to-speech-tts'); ?>
                    </button>
                    <div class="mementor-stt-credits">
                        <span class="dashicons dashicons-universal-access-alt"></span>
                        <?php esc_html_e('Included. No extra charge!', 'text-to-speech-tts'); ?>
                    </div>
                </div>

                <div class="mementor-stt-progress" id="mementor-stt-progress" style="display: none;">
                    <div class="mementor-stt-progress-bar">
                        <div class="mementor-stt-progress-fill" id="mementor-stt-progress-fill"></div>
                    </div>
                    <p id="mementor-stt-progress-text"><?php esc_html_e('Processing...', 'text-to-speech-tts'); ?></p>
                </div>
            </div>

            <!-- Results Section Card -->
            <div class="tts-card" id="mementor-stt-results-section" style="display: none;">
                <div class="tts-card-header">
                    <h3 class="tts-card-title"><?php esc_html_e('Transcription Results', 'text-to-speech-tts'); ?></h3>
                    <div class="mementor-stt-export-buttons" style="display: flex; gap: 6px;">
                        <button type="button" class="tts-btn tts-btn-secondary" id="mementor-stt-export-txt">
                            <span class="dashicons dashicons-media-text"></span>
                            <?php esc_html_e('TXT', 'text-to-speech-tts'); ?>
                        </button>
                        <button type="button" class="tts-btn tts-btn-secondary" id="mementor-stt-export-docx">
                            <span class="dashicons dashicons-media-document"></span>
                            <?php esc_html_e('DOCX', 'text-to-speech-tts'); ?>
                        </button>
                        <button type="button" class="tts-btn tts-btn-secondary" id="mementor-stt-export-json">
                            <span class="dashicons dashicons-media-code"></span>
                            <?php esc_html_e('JSON', 'text-to-speech-tts'); ?>
                        </button>
                    </div>
                </div>

                <div class="mementor-stt-results-content">
                    <div id="mementor-stt-transcription-text" class="mementor-stt-transcription-text"></div>
                </div>

                <div class="mementor-stt-results-footer" style="display: flex; gap: 8px; margin-top: 12px;">
                    <button type="button" class="tts-btn tts-btn-secondary" id="mementor-stt-copy-text">
                        <span class="dashicons dashicons-clipboard"></span>
                        <?php esc_html_e('Copy to Clipboard', 'text-to-speech-tts'); ?>
                    </button>
                    <button type="button" class="tts-btn tts-btn-secondary" id="mementor-stt-new-transcription">
                        <span class="dashicons dashicons-plus"></span>
                        <?php esc_html_e('New Transcription', 'text-to-speech-tts'); ?>
                    </button>
                </div>
            </div>

            <!-- Transcription History -->
            <?php if (!empty($transcriptions)): ?>
            <div class="tts-card tts-word-replacement-card">
                <div class="tts-card-header">
                    <h3 class="tts-card-title"><?php esc_html_e('Transcription History', 'text-to-speech-tts'); ?></h3>
                </div>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th style="width: 20%;"><?php esc_html_e('Date', 'text-to-speech-tts'); ?></th>
                            <th style="width: 30%;"><?php esc_html_e('Filename', 'text-to-speech-tts'); ?></th>
                            <th style="width: 15%;"><?php esc_html_e('Language', 'text-to-speech-tts'); ?></th>
                            <th style="width: 35%;"><?php esc_html_e('Actions', 'text-to-speech-tts'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($transcriptions as $transcription): ?>
                        <tr>
                            <td><?php echo esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($transcription->created_at))); ?></td>
                            <td>
                                <strong><?php echo esc_html($transcription->original_filename); ?></strong>
                                <br>
                                <span style="font-size: 12px; color: var(--tts-text-hint);">
                                    <?php echo esc_html(size_format($transcription->file_size)); ?> &middot;
                                    <?php echo esc_html($transcription->file_type); ?>
                                </span>
                            </td>
                            <td>
                                <?php
                                $lang_name = isset($supported_languages[$transcription->language])
                                    ? $supported_languages[$transcription->language]
                                    : $transcription->language;
                                echo esc_html($lang_name);
                                ?>
                            </td>
                            <td>
                                <div style="display: flex; gap: 6px;">
                                    <button type="button" class="tts-btn tts-btn-secondary mementor-stt-view-transcript"
                                            data-id="<?php echo esc_attr($transcription->id); ?>"
                                            data-text="<?php echo esc_attr($transcription->transcription_text); ?>">
                                        <span class="dashicons dashicons-visibility"></span>
                                        <?php esc_html_e('View / Export', 'text-to-speech-tts'); ?>
                                    </button>
                                    <button type="button" class="tts-btn tts-btn-danger mementor-stt-delete-transcript"
                                            data-id="<?php echo esc_attr($transcription->id); ?>">
                                        <span class="dashicons dashicons-trash"></span>
                                        <?php esc_html_e('Delete', 'text-to-speech-tts'); ?>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>

            </div><!-- .mementor-stt-content-wrapper -->

<?php include MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/layout-close.php'; ?>

<script type="text/javascript">
jQuery(document).ready(function($) {
    var selectedFile = null;
    var transcriptionData = null;

    // File upload handling
    $('#mementor-stt-select-file').on('click', function() {
        $('#mementor-stt-file-input').click();
    });

    $('#mementor-stt-file-input').on('change', function(e) {
        var file = e.target.files[0];
        if (file) {
            handleFileSelect(file);
        }
    });

    // Drag and drop
    var $uploadArea = $('#mementor-stt-upload-area');

    $uploadArea.on('dragover', function(e) {
        e.preventDefault();
        e.stopPropagation();
        $(this).addClass('mementor-stt-drag-over');
    });

    $uploadArea.on('dragleave', function(e) {
        e.preventDefault();
        e.stopPropagation();
        $(this).removeClass('mementor-stt-drag-over');
    });

    $uploadArea.on('drop', function(e) {
        e.preventDefault();
        e.stopPropagation();
        $(this).removeClass('mementor-stt-drag-over');

        var files = e.originalEvent.dataTransfer.files;
        if (files.length > 0) {
            handleFileSelect(files[0]);
        }
    });

    function handleFileSelect(file) {
        selectedFile = file;

        // Show file preview
        $('#mementor-stt-file-name').text(file.name);
        $('#mementor-stt-file-size').text(formatFileSize(file.size));
        $('#mementor-stt-upload-area').hide();
        $('#mementor-stt-file-preview').show();
        $('#mementor-stt-transcribe').prop('disabled', false);
    }

    $('#mementor-stt-remove-file').on('click', function() {
        selectedFile = null;
        $('#mementor-stt-file-input').val('');
        $('#mementor-stt-file-preview').hide();
        $('#mementor-stt-upload-area').show();
        $('#mementor-stt-transcribe').prop('disabled', true);
    });

    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        var k = 1024;
        var sizes = ['Bytes', 'KB', 'MB', 'GB'];
        var i = Math.floor(Math.log(bytes) / Math.log(k));
        return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
    }

    // Transcribe button
    $('#mementor-stt-transcribe').on('click', function() {
        if (!selectedFile) return;

        var formData = new FormData();
        formData.append('action', 'mementor_stt_transcribe');
        formData.append('nonce', '<?php echo wp_create_nonce('mementor_stt_nonce'); ?>');
        formData.append('file', selectedFile);
        formData.append('language', $('#mementor-stt-language').val());
        formData.append('tag_events', $('#mementor-stt-tag-events').is(':checked') ? '1' : '0');
        formData.append('include_timestamps', $('#mementor-stt-include-timestamps').is(':checked') ? '1' : '0');

        // Show progress
        $('#mementor-stt-progress').show();
        $('#mementor-stt-transcribe').prop('disabled', true);

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            xhr: function() {
                var xhr = new window.XMLHttpRequest();
                xhr.upload.addEventListener('progress', function(e) {
                    if (e.lengthComputable) {
                        var percentComplete = (e.loaded / e.total) * 100;
                        $('#mementor-stt-progress-fill').css('width', percentComplete + '%');
                    }
                }, false);
                return xhr;
            },
            success: function(response) {
                $('#mementor-stt-progress').hide();

                if (response.success) {
                    transcriptionData = response.data;
                    displayTranscription(response.data);
                    $('#mementor-stt-results-section').show();
                } else {
                    // Check if it's a permission error
                    if (response.data.permission_error) {
                        showMessage('error', response.data.message, true);
                    } else {
                        showMessage('error', response.data.message || '<?php esc_html_e('Transcription failed. Please try again.', 'text-to-speech-tts'); ?>');
                    }
                    $('#mementor-stt-transcribe').prop('disabled', false);
                }
            },
            error: function() {
                $('#mementor-stt-progress').hide();
                showMessage('error', '<?php esc_html_e('An error occurred. Please try again.', 'text-to-speech-tts'); ?>');
                $('#mementor-stt-transcribe').prop('disabled', false);
            }
        });
    });

    function displayTranscription(data) {
        var $content = $('#mementor-stt-transcription-text');
        $content.empty();

        if (data.text) {
            $content.text(data.text);
        }
    }

    function showMessage(type, message, isPermissionError) {
        var className = type === 'error' ? 'notice-error' : 'notice-success';

        // For permission errors, make it more prominent and don't auto-hide
        if (isPermissionError) {
            var $message = $('<div class="notice notice-warning" style="border-left: 4px solid #f56e28; padding: 15px; margin: 20px 0;">' +
                '<p style="margin: 0 0 10px 0; font-weight: 600; font-size: 14px;">' +
                '<span class="dashicons dashicons-warning" style="color: #f56e28;"></span> ' +
                '<?php esc_html_e('API Permission Required', 'text-to-speech-tts'); ?>' +
                '</p>' +
                '<p style="margin: 0;">' + message + '</p>' +
                '<p style="margin: 10px 0 0 0;"><a href="https://elevenlabs.io/app/settings/api-keys" target="_blank" class="button button-primary">' +
                '<?php esc_html_e('Update API Key Permissions', 'text-to-speech-tts'); ?> <span class="dashicons dashicons-external" style="margin-top: 3px;"></span></a></p>' +
                '</div>');
        } else {
            var $message = $('<div class="notice ' + className + ' is-dismissible"><p>' + message + '</p></div>');
        }

        $('#mementor-stt-messages').html($message);

        // Only auto-hide non-permission errors
        if (!isPermissionError) {
            setTimeout(function() {
                $message.fadeOut(function() {
                    $(this).remove();
                });
            }, 5000);
        }
    }

    // Export functions
    $('#mementor-stt-export-txt').on('click', function() {
        if (!transcriptionData) return;
        exportAs('txt');
    });

    $('#mementor-stt-export-docx').on('click', function() {
        if (!transcriptionData) return;
        exportAs('docx');
    });

    $('#mementor-stt-export-json').on('click', function() {
        if (!transcriptionData) return;
        exportAs('json');
    });

    $('#mementor-stt-copy-text').on('click', function() {
        var text = $('#mementor-stt-transcription-text').text();
        navigator.clipboard.writeText(text).then(function() {
            showMessage('success', '<?php esc_html_e('Copied to clipboard!', 'text-to-speech-tts'); ?>');
        });
    });

    $('#mementor-stt-new-transcription').on('click', function() {
        location.reload();
    });

    // View transcript from history
    $('.mementor-stt-view-transcript').on('click', function() {
        var text = $(this).data('text');
        transcriptionData = { text: text };
        displayTranscription(transcriptionData);
        $('#mementor-stt-results-section').show();
        $('html, body').animate({
            scrollTop: $('#mementor-stt-results-section').offset().top - 100
        }, 500);
    });

    // Delete transcript
    $('.mementor-stt-delete-transcript').on('click', function() {
        if (!confirm('<?php esc_html_e('Are you sure you want to delete this transcription?', 'text-to-speech-tts'); ?>')) {
            return;
        }

        var $button = $(this);
        var id = $button.data('id');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'mementor_stt_delete_transcription',
                nonce: '<?php echo wp_create_nonce('mementor_stt_nonce'); ?>',
                id: id
            },
            success: function(response) {
                if (response.success) {
                    $button.closest('tr').fadeOut(function() {
                        $(this).remove();
                        if ($('.mementor-stt-history-table tbody tr').length === 0) {
                            location.reload();
                        }
                    });
                    showMessage('success', '<?php esc_html_e('Transcription deleted successfully.', 'text-to-speech-tts'); ?>');
                } else {
                    showMessage('error', response.data.message || '<?php esc_html_e('Failed to delete transcription.', 'text-to-speech-tts'); ?>');
                }
            },
            error: function() {
                showMessage('error', '<?php esc_html_e('An error occurred. Please try again.', 'text-to-speech-tts'); ?>');
            }
        });
    });

    function exportAs(format) {
        var link = document.createElement('a');
        var content, filename, type;

        switch(format) {
            case 'txt':
                content = transcriptionData.text;
                filename = 'transcription.txt';
                type = 'text/plain';
                break;
            case 'docx':
                // Generate RTF format (compatible with Word)
                var rtfContent = generateDocx(transcriptionData.text);
                var blob = new Blob([rtfContent], { type: 'application/rtf' });
                link.href = URL.createObjectURL(blob);
                link.download = 'transcription.rtf';
                link.click();
                return;
            case 'json':
                content = JSON.stringify(transcriptionData, null, 2);
                filename = 'transcription.json';
                type = 'application/json';
                break;
        }

        var blob = new Blob([content], { type: type });
        link.href = URL.createObjectURL(blob);
        link.download = filename;
        link.click();
    }

    function generateDocx(text) {
        // For now, use RTF format which is more compatible and simpler
        // RTF can be opened by Word and most document editors
        var rtfContent = '{\\rtf1\\ansi\\deff0\n';

        // Escape special RTF characters
        var escapedText = text.replace(/\\/g, '\\\\')
                              .replace(/{/g, '\\{')
                              .replace(/}/g, '\\}');

        // Convert newlines to RTF paragraph breaks
        var paragraphs = escapedText.split('\n').map(function(para) {
            return para + '\\par\n';
        }).join('');

        rtfContent += paragraphs + '}';

        return rtfContent;
    }
});
</script>
