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

class Intopenai_IndexController extends Core_Controller_Action_Standard
{
  public function contentAction()
  {
    $text = $this->_getParam("text");
    $length = $this->_getParam("length");
    $settings = Engine_Api::_()->getApi('settings', 'core');
    $availableCount = $this->view->viewer()->wallet_amount > 0 && Engine_Api::_()->authorization()->getPermission($this->view->viewer()->level_id, 'intopenai', 'content_price') > 0 ? floor($this->view->viewer()->wallet_amount/Engine_Api::_()->authorization()->getPermission($this->view->viewer()->level_id, 'intopenai', 'content_price')) : 0;
    
    if(Engine_Api::_()->authorization()->getPermission($this->view->viewer()->level_id, 'intopenai', 'content_price') > 0 && ($availableCount == 0 || $availableCount < $length)){
      echo json_encode([
        'status' => 0,
        'message' => $this->view->translate("You don't have enough balange to generate this post. Please recharge your wallet.")
      ]);die;
    }

    $openAIKey = $settings->getSetting('intopenai_key', "");
    $model = $settings->getSetting('intopenai_model', "gpt-4");
    // Prepare the POST data
    $data = [
      "model" => $model,
      "messages" => [
          [
              "role" => "user",
              "content" => $text
          ]
      ],
      "max_tokens" => (int) $length
  ];

    // Convert data to JSON
    $jsonData = json_encode($data);

    // Set the API URL
    $url = "https://api.openai.com/v1/chat/completions";

    // Initialize cURL session
    $ch = curl_init();

    // Set the necessary cURL options
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

    // Set the headers
    $headers = [
        'Authorization: Bearer ' . $openAIKey,
        'Content-Type: application/json'
    ];
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    // Execute the request
    $response = curl_exec($ch);

    // Handle cURL errors
    if (curl_errno($ch)) {
      curl_close($ch);
      echo json_encode([
          'status' => 0,
          'message' => curl_error($ch)
      ]);die;
  }


    // Close the cURL session
    curl_close($ch);
    try {
      $data = json_decode($response, true);
      // If there's no data or the response is empty
      if (!$data) {
        echo json_encode([
              'status' => 0,
              'message' => 'No data returned or response was invalid.'
        ]);die;
      }

      // Return success with the actual data
      if(isset( $data['choices'])){
        if(Engine_Api::_()->authorization()->getPermission($this->view->viewer()->level_id, 'intopenai', 'content_price') > 0){
          // deduct balance from wallet
          $this->generateOrder(Engine_Api::_()->authorization()->getPermission($this->view->viewer()->level_id, 'intopenai', 'content_price')*$length);
        
        $currentCurrency = Engine_Api::_()->payment()->getCurrentCurrency();
        $currentData = Engine_Api::_()->getDbTable('currencies', 'payment')->getCurrency($currentCurrency);
       $word =  floor(($this->view->viewer()->wallet_amount * $currentData->change_rate)/Engine_Api::_()->authorization()->getPermission($this->view->viewer()->level_id, 'intopenai', 'content_price'));
       $availableCount = $this->view->viewer()->wallet_amount > 0 && Engine_Api::_()->authorization()->getPermission($this->view->viewer()->level_id, 'intopenai', 'content_price') > 0 ? floor(($this->view->viewer()->wallet_amount * $currentData->change_rate)/Engine_Api::_()->authorization()->getPermission($this->view->viewer()->level_id, 'intopenai', 'content_price')) : 0;
        }else{
          $availableCount = 0;
          $word = 0;
        }
        echo json_encode([
            'status' => 1,
            'word' => $word,
            'availableCount' => $availableCount,
            'data' => $data['choices'][0]['message']['content']
        ]);die;
      }else{
        echo json_encode(["status" => 0,"message"=> $this->view->translate("Invalid response from OpenAI API")]);die;
      }
    } catch (Exception $e) {
      throw $e;
        // If there's a problem with parsing JSON or any exception
        echo json_encode([
            'status' => 0,
            'message' => $e->getMessage()
        ]);die;
    }

  }
  function generateOrder($price){
    $user = $this->view->viewer();
    $ordersTable = Engine_Api::_()->getDbtable('orders', 'payment');
    $ordersTable->insert(array(
      'user_id' => $user->getIdentity(),
      'gateway_id' => 3000,
      'state' => 'complete',
      'creation_date' => new Zend_Db_Expr('NOW()'),
      'source_type' => 'user',
      'source_id' => $user->getIdentity(),
    ));
    $order_id = $ordersTable->getAdapter()->lastInsertId();
    $order = Engine_Api::_()->getItem("payment_order",$order_id);
    $transactionsTable = Engine_Api::_()->getDbtable('transactions', 'payment');
    $current_currency = Engine_Api::_()->payment()->getCurrentCurrency();
    $currencyData = Engine_Api::_()->getDbTable('currencies', 'payment')->getCurrency($current_currency);
    $currencyChangeRate = 1;
    $defaultCurrency = Engine_Api::_()->payment()->defaultCurrency();
    if ($current_currency != $defaultCurrency) {
      $currencyChangeRate = $currencyData->change_rate;
    }
    $price = @round(($price ), 2);
    $gateway_transaction_id = crc32(microtime() . $order->order_id);
    $params['gateway_transaction_id'] = $gateway_transaction_id; // Hack
    $params['currency'] = $defaultCurrency;
    $params['state'] = "okay";
    $params['amount'] = $price;
    $params['type'] = "AI Content";
    $params['expiration_date'] = null;
    $params['change_rate'] = $currencyChangeRate;
    $params['current_currency'] = $current_currency;
    // Insert transaction
    $transaction_id = $transactionsTable->createTransaction($order, $subscription, $user, $params);
    $user->wallet_amount = $user->wallet_amount - $price;
    $user->save();
    return $user->wallet_amount;
  }
  public function imageAction()
  {
    
    $text = $this->_getParam("text");
    $aiimage_size = $this->_getParam("aiimage_size");
    $aiimage_count = $this->_getParam("aiimage_count");   
    $openAIKey = Engine_Api::_()->getApi('settings', 'core')->getSetting('intopenai_key', "");
    $settings = Engine_Api::_()->getApi('settings', 'core');
    $availableCount = $this->view->viewer()->wallet_amount > 0 && Engine_Api::_()->authorization()->getPermission($this->view->viewer()->level_id, 'intopenai', 'image_price') > 0 ? floor($this->view->viewer()->wallet_amount/Engine_Api::_()->authorization()->getPermission($this->view->viewer()->level_id, 'intopenai', 'image_price')) : 0;
    
    if(Engine_Api::_()->authorization()->getPermission($this->view->viewer()->level_id, 'intopenai', 'image_price') > 0 && ($availableCount == 0 || $availableCount < $aiimage_count)){
      echo json_encode([
        'status' => 0,
        'message' => $this->view->translate("You don't have enough balange to generate this image. Please recharge your wallet.")
      ]);die;
    }

    // Prepare the POST data
    $data = [
      "n" => min((int)$aiimage_count, 10),
      "prompt" => $text,
      "size" => $aiimage_size
    ];

    // Convert data to JSON
    $jsonData = json_encode($data);

    // Set the API URL
    $url = 'https://api.openai.com/v1/images/generations';

    // Initialize cURL session
    $ch = curl_init();

    // Set the necessary cURL options
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

    // Set the headers
    $headers = [
        'Authorization: Bearer ' . $openAIKey,
        'Content-Type: application/json'
    ];
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    // Execute the request
    $response = curl_exec($ch);

    // Handle cURL errors
    if (curl_errno($ch)) {
      curl_close($ch);
      echo json_encode([
          'status' => 0,
          'message' => curl_error($ch)
      ]);die;
  }
    // Close the cURL session
    curl_close($ch);
    try {
      $data = json_decode($response, true);
      // If there's no data or the response is empty
      if (!$data) {
        echo json_encode([
              'status' => 0,
              'message' => 'No data returned or response was invalid.'
        ]);die;
      }
      // Return success with the actual data
      if(engine_count( $data['data'])){

        if(Engine_Api::_()->authorization()->getPermission($this->view->viewer()->level_id, 'intopenai', 'image_price') > 0){
          // deduct balance from wallet
          $this->generateOrder(Engine_Api::_()->authorization()->getPermission($this->view->viewer()->level_id, 'intopenai', 'image_price')*$aiimage_count);
        
          $currentCurrency = Engine_Api::_()->payment()->getCurrentCurrency();
          $currentData = Engine_Api::_()->getDbTable('currencies', 'payment')->getCurrency($currentCurrency);
          $imageCount = floor(($this->view->viewer()->wallet_amount * $currentData->change_rate)/Engine_Api::_()->authorization()->getPermission($this->view->viewer()->level_id, 'intopenai', 'image_price'));
        }else{
          $imageCount = 0;
        }
        echo json_encode([
            'status' => 1,
            'imageCount' => $imageCount,
            'data' => $data['data']
        ]);die;
      }else{
        echo json_encode(["status" => 0,"message"=> $this->view->translate("No image data found or invalid response from the API")]);die;
      }
    } catch (Exception $e) {
        // If there's a problem with parsing JSON or any exception
        echo json_encode([
            'status' => 0,
            'message' => $e->getMessage()
        ]);die;
    }

  }
}
