<?php
namespace TeknoTok\AiTranslator\Database;

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

/**
 * Handles creation and upgrades of custom database tables and default options.
 */
class Schema {
	/**
	 * Create translation memory and queue tables.
	 *
	 * @return void
	 */
	public static function create_tables() {
		global $wpdb;

		require_once ABSPATH . 'wp-admin/includes/upgrade.php';

		$charset_collate = $wpdb->get_charset_collate();
		$translations_table = $wpdb->prefix . 'teknotok_translations';
		$jobs_table = $wpdb->prefix . 'teknotok_jobs';

		// Create translation memory table
		dbDelta(
			"CREATE TABLE {$translations_table} (
				id bigint(20) NOT NULL AUTO_INCREMENT,
				source_hash varchar(32) NOT NULL,
				source_text longtext NOT NULL,
				translated_text longtext NOT NULL,
				source_lang varchar(10) NOT NULL,
				target_lang varchar(10) NOT NULL,
				last_used datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
				PRIMARY KEY  (id),
				UNIQUE KEY source_hash_lang (source_hash, target_lang)
			) {$charset_collate};"
		);

		// Create background jobs table
		dbDelta(
			"CREATE TABLE {$jobs_table} (
				id bigint(20) NOT NULL AUTO_INCREMENT,
				object_type varchar(50) NOT NULL,
				object_id bigint(20) NOT NULL,
				source_hash varchar(32) DEFAULT NULL,
				source_text longtext DEFAULT NULL,
				target_lang varchar(10) NOT NULL,
				status varchar(20) NOT NULL DEFAULT 'pending',
				retry_count int(11) DEFAULT 0,
				error_message text DEFAULT NULL,
				created_at datetime DEFAULT CURRENT_TIMESTAMP,
				updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
				PRIMARY KEY  (id),
				KEY status (status),
				KEY source_hash_lang (source_hash, target_lang)
			) {$charset_collate};"
		);
	}

	/**
	 * Check whether the jobs table has string payload columns.
	 *
	 * @return bool True when supported.
	 */
	public static function jobs_support_string_payloads() {
		global $wpdb;

		$jobs_table = $wpdb->prefix . 'teknotok_jobs';
		$wpdb->last_error = '';
		$wpdb->get_results( "SELECT source_text FROM {$jobs_table} LIMIT 1" );
		if ( empty( $wpdb->last_error ) ) {
			return true;
		}

		$column = $wpdb->get_var( $wpdb->prepare( 'SHOW COLUMNS FROM ' . $jobs_table . ' LIKE %s', 'source_text' ) );

		return ! empty( $column );
	}

	/**
	 * Seed default options.
	 *
	 * @return void
	 */
	public static function seed_defaults() {
		if ( false === get_option( 'teknotok_ait_settings', false ) ) {
			$default_settings = array(
				'api_provider'    => 'openai',
				'openai_api_key'  => '',
				'openai_model'    => 'gpt-4o-mini',
				'source_language' => substr( get_locale(), 0, 2 ),
				'target_languages'=> array(),
				'switcher_position'=> 'floating-bottom-right',
				'detect_browser'  => '1',
				'auto_translate'  => '1',
				'gateway_base_url'=> 'https://soft.teknotok.com',
			);
			add_option( 'teknotok_ait_settings', $default_settings, '', false );
		}

		if ( false === get_option( 'teknotok_ait_license_status', false ) ) {
			add_option( 'teknotok_ait_license_status', array(
				'license_key' => '',
				'status'      => 'free',
				'expires_at'  => '',
				'last_check'  => 0,
				'error_count' => 0
			), '', false );
		}
	}
}
