<?php
if (!defined('ABSPATH')) exit;
/**
 * SSML Generator Class
 * Handles the generation of Speech Synthesis Markup Language (SSML)
 */
class Mementor_TTS_SSML {
    /**
     * Convert text to SSML with proper formatting
     */
    public static function generate_ssml($text, $options = array()) {
        // Strip any existing HTML tags
        $text = wp_strip_all_tags($text);

        // Default options
        $defaults = array(
            'rate' => 1.0,
            'pitch' => 1.0,
            'volume' => 0,
            'emphasis' => 'moderate',
            'break_strength' => 'medium',
            'break_time' => '1s'
        );

        $options = wp_parse_args($options, $defaults);

        // Start SSML document
        $ssml = '<?xml version="1.0"?>' . "\n";
        $ssml .= '<speak version="1.1">' . "\n";

        // Add prosody settings if different from defaults
        if ($options['rate'] !== 1.0 || $options['pitch'] !== 1.0 || $options['volume'] !== 0) {
            $prosody_attrs = array();
            if ($options['rate'] !== 1.0) {
                $prosody_attrs[] = sprintf('rate="%s%%"', $options['rate'] * 100);
            }
            if ($options['pitch'] !== 1.0) {
                $prosody_attrs[] = sprintf('pitch="%s%%"', $options['pitch'] * 100);
            }
            if ($options['volume'] !== 0) {
                $prosody_attrs[] = sprintf('volume="%sdB"', $options['volume']);
            }

            $ssml .= sprintf('<prosody %s>', implode(' ', $prosody_attrs)) . "\n";
        }

        // Process text for better speech synthesis
        $sentences = self::split_into_sentences($text);
        foreach ($sentences as $sentence) {
            $sentence = trim($sentence);
            if (empty($sentence)) continue;

            // Add emphasis to questions and exclamations
            if (self::is_question($sentence)) {
                $ssml .= sprintf('<emphasis level="%s">%s</emphasis>', $options['emphasis'], htmlspecialchars($sentence));
            } else {
                $ssml .= htmlspecialchars($sentence);
            }

            // Add breaks between sentences
            $ssml .= sprintf('<break strength="%s" time="%s"/>', $options['break_strength'], $options['break_time']) . "\n";
        }

        // Close prosody tag if opened
        if ($options['rate'] !== 1.0 || $options['pitch'] !== 1.0 || $options['volume'] !== 0) {
            $ssml .= '</prosody>' . "\n";
        }

        // Close SSML document
        $ssml .= '</speak>';

        return $ssml;
    }

    /**
     * Split text into sentences
     */
    private static function split_into_sentences($text) {
        // Basic sentence splitting (can be improved with more complex rules)
        $sentences = preg_split('/(?<=[.!?])\s+/', $text, -1, PREG_SPLIT_NO_EMPTY);
        return $sentences;
    }

    /**
     * Check if text is a question
     */
    private static function is_question($text) {
        return substr(trim($text), -1) === '?';
    }

    /**
     * Add pause/break
     */
    public static function add_break($strength = 'medium', $time = '1s') {
        return sprintf('<break strength="%s" time="%s"/>', $strength, $time);
    }

    /**
     * Add emphasis
     */
    public static function add_emphasis($text, $level = 'moderate') {
        return sprintf('<emphasis level="%s">%s</emphasis>', $level, htmlspecialchars($text));
    }

    /**
     * Add prosody
     */
    public static function add_prosody($text, $rate = null, $pitch = null, $volume = null) {
        $attrs = array();
        if ($rate !== null) {
            $attrs[] = sprintf('rate="%s%%"', $rate * 100);
        }
        if ($pitch !== null) {
            $attrs[] = sprintf('pitch="%s%%"', $pitch * 100);
        }
        if ($volume !== null) {
            $attrs[] = sprintf('volume="%sdB"', $volume);
        }

        if (empty($attrs)) {
            return $text;
        }

        return sprintf('<prosody %s>%s</prosody>', implode(' ', $attrs), htmlspecialchars($text));
    }

    /**
     * Add phoneme
     */
    public static function add_phoneme($text, $alphabet = 'ipa', $ph = '') {
        return sprintf('<phoneme alphabet="%s" ph="%s">%s</phoneme>', $alphabet, $ph, htmlspecialchars($text));
    }

    /**
     * Add sub (substitution)
     */
    public static function add_sub($alias, $text) {
        return sprintf('<sub alias="%s">%s</sub>', htmlspecialchars($alias), htmlspecialchars($text));
    }

    /**
     * Format numbers for better speech
     */
    public static function format_numbers($text) {
        // Convert numbers to words where appropriate
        $text = preg_replace_callback('/\b(\d+)\b/', function($matches) {
            $number = $matches[1];
            if (strlen($number) <= 4) {
                // Use say-as for small numbers
                return sprintf('<say-as interpret-as="cardinal">%s</say-as>', $number);
            } else {
                // Split larger numbers for better pronunciation
                return sprintf('<say-as interpret-as="number">%s</say-as>',
                    implode(' ', str_split($number, 3)));
            }
        }, $text);

        return $text;
    }

    /**
     * Format dates for better speech
     */
    public static function format_date($date, $format = 'mdy') {
        return sprintf('<say-as interpret-as="date" format="%s">%s</say-as>', $format, $date);
    }

    /**
     * Format time for better speech
     */
    public static function format_time($time) {
        return sprintf('<say-as interpret-as="time">%s</say-as>', $time);
    }
}
