<?php
/**
  * Ahead WebSoft Technologies Pvt Ltd.
  * @copyright  Copyright 2006-2026 Ahead WebSoft Technologies Pvt Ltd.
  * @license    https://www.socialengine.com/policies
*/

class Core_Api_Languages extends Core_Api_Abstract {

  public function getLanguages($params = array()) {
  
    $table = Engine_Api::_()->getDbTable('languages', 'core');
    $tableName = $table->info('name');
    
    $select = $table->select()
                    ->from($tableName);
    if(!isset($params['admin']) && empty($params['admin'])) {
      $select->where('enabled = ?', 1);
    }
    $select->order('order ASC');
    
    $languages = $table->fetchAll($select);
    $localeMultiOptions = array();
    foreach ($languages as $language) {
      $localeMultiOptions[$language->code] = $language->name;
    }
    return $localeMultiOptions;
  }

	public function batchTranslate($texts = array(), $sourceLanguage = 'en', $targetLanguage = '')
	{

		if (empty($texts) || !is_array($texts)) {
			return array();
		}

		$results = array();
		$apiKey = Engine_Api::_()->getApi('settings', 'core')->getSetting('core.googletranslatorapi', null);

		if (empty($apiKey)) {
			return array();
		}

		$batches = array_chunk($texts, 50, true);

		foreach ($batches as $batch) {
			$batchTexts = array_values($batch);
			$batchIndexes = array_keys($batch);

			$queryString = 'key=' . urlencode($apiKey) . '&source=' . $sourceLanguage . '&target=' . $targetLanguage;
			foreach ($batchTexts as $text) {
				$queryString .= '&q=' . urlencode($text);
			}

			$url = 'https://www.googleapis.com/language/translate/v2?' . $queryString;

			$response = null;
			$httpCode = 0;
			$attempts = 0;
			while ($attempts < 3) {
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_TIMEOUT, 120);
				curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

				$response = curl_exec($ch);
				$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
				curl_close($ch);

				if ($httpCode == 200 && !empty($response)) {
					break;
				}

				$attempts++;
				if ($attempts < 3) {
					usleep(1000000);
				}
			}

			if ($httpCode == 200 && !empty($response)) {
				$decoded = json_decode($response, true);
				if (isset($decoded['data']['translations'])) {
					foreach ($decoded['data']['translations'] as $idx => $translation) {
						if (isset($batchIndexes[$idx])) {
							$results[$batchIndexes[$idx]] = $translation['translatedText'];
						}
					}
				}
			}
		}

		return $results;
	}
}
