<?php
/**
 * Transcriptions Management Class
 *
 * Handles storage and retrieval of speech-to-text transcriptions
 *
 * @package    TTSWP
 * @subpackage Mementor_TTS/includes
 */

// Prevent direct access to this file
if (!defined('ABSPATH')) {
    exit;
}

class Mementor_TTS_Transcriptions {

    /**
     * Single instance of the class
     */
    private static $instance = null;

    /**
     * Table name
     */
    private $table_name;

    /**
     * Get instance
     */
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     */
    private function __construct() {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'mementor_tts_transcriptions';

        // Check if table exists and create if needed
        add_action('admin_init', array($this, 'maybe_create_table'));
    }

    /**
     * Create table if it doesn't exist
     */
    public function maybe_create_table() {
        global $wpdb;

        // Check if table exists
        $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $this->table_name)) === $this->table_name;

        if (!$table_exists) {
            $this->create_table();
        }
    }

    /**
     * Create transcriptions table
     */
    public function create_table() {
        global $wpdb;

        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE {$this->table_name} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            user_id bigint(20) NOT NULL,
            filename varchar(255) NOT NULL,
            original_filename varchar(255) NOT NULL,
            file_size bigint(20) NOT NULL,
            file_type varchar(50) NOT NULL,
            language varchar(10) NOT NULL,
            transcription_text longtext NOT NULL,
            transcription_data longtext,
            tag_events tinyint(1) DEFAULT 0,
            include_timestamps tinyint(1) DEFAULT 0,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id),
            KEY user_id (user_id),
            KEY created_at (created_at)
        ) $charset_collate;";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

    /**
     * Save a new transcription
     */
    public function save_transcription($data) {
        global $wpdb;

        $insert_data = array(
            'user_id' => get_current_user_id(),
            'filename' => sanitize_file_name($data['filename']),
            'original_filename' => sanitize_text_field($data['original_filename']),
            'file_size' => absint($data['file_size']),
            'file_type' => sanitize_text_field($data['file_type']),
            'language' => sanitize_text_field($data['language']),
            'transcription_text' => wp_kses_post($data['transcription_text']),
            'transcription_data' => maybe_serialize($data['transcription_data']),
            'tag_events' => !empty($data['tag_events']) ? 1 : 0,
            'include_timestamps' => !empty($data['include_timestamps']) ? 1 : 0,
        );

        $wpdb->insert(
            $this->table_name,
            $insert_data,
            array('%d', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%d', '%d')
        );

        return $wpdb->insert_id;
    }

    /**
     * Get transcription by ID
     */
    public function get_transcription($id) {
        global $wpdb;

        $transcription = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$this->table_name} WHERE id = %d",
            $id
        ));

        if ($transcription && !empty($transcription->transcription_data)) {
            $transcription->transcription_data = maybe_unserialize($transcription->transcription_data);
        }

        return $transcription;
    }

    /**
     * Get all transcriptions for current user
     */
    public function get_user_transcriptions($user_id = null, $limit = 50, $offset = 0) {
        global $wpdb;

        if ($user_id === null) {
            $user_id = get_current_user_id();
        }

        $transcriptions = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$this->table_name}
            WHERE user_id = %d
            ORDER BY created_at DESC
            LIMIT %d OFFSET %d",
            $user_id,
            $limit,
            $offset
        ));

        foreach ($transcriptions as $transcription) {
            if (!empty($transcription->transcription_data)) {
                $transcription->transcription_data = maybe_unserialize($transcription->transcription_data);
            }
        }

        return $transcriptions;
    }

    /**
     * Delete transcription
     */
    public function delete_transcription($id) {
        global $wpdb;

        // Verify user owns this transcription
        $transcription = $this->get_transcription($id);
        if (!$transcription || $transcription->user_id != get_current_user_id()) {
            return false;
        }

        return $wpdb->delete(
            $this->table_name,
            array('id' => $id),
            array('%d')
        );
    }

    /**
     * Get transcription count for user
     */
    public function get_user_transcription_count($user_id = null) {
        global $wpdb;

        if ($user_id === null) {
            $user_id = get_current_user_id();
        }

        return $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$this->table_name} WHERE user_id = %d",
            $user_id
        ));
    }
}
