<?php
/**
  * Ahead WebSoft Technologies Pvt Ltd.
  * @copyright  Copyright 2006-2026 Ahead WebSoft Technologies Pvt Ltd.
  * @license    https://www.socialengine.com/policies
*/
?>
<?php
$settings = Engine_Api::_()->getApi('settings', 'core');

if(!Engine_Api::_()->getApi('settings', 'core')->getSetting('intopenai.pluginactivated')) return;

if(!$settings->getSetting('intopenai_key', 0)){
  return;
}
$request = Zend_Controller_Front::getInstance()->getRequest();
$requestParams = $request->getParams();

if(!Engine_Api::_()->authorization()->getPermission($this->viewer()->level_id, 'intopenai', 'content')){
  return;
}

if (($requestParams['action'] == 'compose' || $requestParams['action'] == 'view') && $requestParams['module'] == 'messages' && $requestParams['controller'] == 'messages') {
  return;
}
$currentCurrency = Engine_Api::_()->payment()->getCurrentCurrency();
$currentData = Engine_Api::_()->getDbTable('currencies', 'payment')->getCurrency($currentCurrency);
?>
<?php $generateDescriptionCount = $this->viewer()->wallet_amount > 0 && Engine_Api::_()->authorization()->getPermission($this->viewer()->level_id, 'intopenai', 'content_price') > 0 ? floor($this->viewer()->wallet_amount/Engine_Api::_()->authorization()->getPermission($this->viewer()->level_id, 'intopenai', 'content_price')) : (Engine_Api::_()->authorization()->getPermission($this->viewer()->level_id, 'intopenai', 'content_price') == 0 ? 1 : 0); ?>
<div id="intopenaidescription_wrap" style="display:none">
  <div class="modal fade modalbox_wrap intopenai_generate_modal" id="intopenaidescription" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="intopenaidescriptionLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-md modal-fullscreen-md-down">
      <div class="modal-content">
        <div class="modal-header">
          <h2 class="modal-title fs-5" id="intopenaidescriptionLabel"><?php echo $this->translate("Generate Post"); ?></h2>
          <button type="button" class="modal_close center_item cancelgenerateaiDescription" data-bs-dismiss="modal" aria-label="Close">
            <i><svg xmlns="http://www.w3.org/2000/svg" id="Outline" viewBox="0 0 24 24" width="512" height="512"><path d="M18,6h0a1,1,0,0,0-1.414,0L12,10.586,7.414,6A1,1,0,0,0,6,6H6A1,1,0,0,0,6,7.414L10.586,12,6,16.586A1,1,0,0,0,6,18H6a1,1,0,0,0,1.414,0L12,13.414,16.586,18A1,1,0,0,0,18,18h0a1,1,0,0,0,0-1.414L13.414,12,18,7.414A1,1,0,0,0,18,6Z"/></svg></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="error_msg ai_word" style="display:none">

          </div>
          <div class="clear">
            <div class="intopenai_generate_modal_top">
              <?php if(Engine_Api::_()->authorization()->getPermission($this->viewer()->level_id, 'intopenai', 'content_price') > 0){ ?>
                <div class="intopenai_balance_info d-flex justify-content-between">
                  <p class="fw-500 w-100"><?php echo $this->translate("Available Balance") ?></p>
                  <div class="intopenai_balance_info_count d-flex gap-2 align-items-end">
                    <b id="word_available_ai" class="font_color_primary"><?php echo floor(($this->viewer()->wallet_amount * $currentData->change_rate)/Engine_Api::_()->authorization()->getPermission($this->viewer()->level_id, 'intopenai', 'content_price'));?></b>
                    <span class="fw-500"><?php echo $this->translate("Words") ?></span>
                    <!-- <span>($1254)</span> -->
                  </div>
                  <div class="intopenai_balance_info_btn">
                    <a class="btn btn-primary recharge_ai w-100" href="<?php echo $this->baseUrl().'/payment/settings/wallet';?>"><?php echo $this->translate("Recharge Wallet")?></a>
                  </div>
                  <!-- <p class="font_small w-100 mt-1">$1/word</p>

                  <div class="intopenai_credit_points">
                    <p class="m-0 d-flex align-items-center"><b>Or Pay $0.9 +</b> <i class="coin_icon"></i> 1/<span class="font_small">word</span> </p>
                    <p class="font_small mt-1">Available Coins: 2000</p>
                  </div> -->
                </div>
              <?php } ?>
            </div>
            <div class="intopenai_generate_modal_form">
              <div class="input_field mb-3">
                <label class="form-label"><?php echo $this->translate("Enter your prompt below to generate the post."); ?></label>
                <textarea class="form-control" autocomplete="off" id="ai_descriptiontextarea" placeholder="<?php echo $this->translate("Describe your post, e.g. 'Tell me a joke'."); ?>"></textarea>
              </div>
               
              <div class="input_field mb-3">
                <label class="form-label"><?php echo $this->translate("Max result length"); ?></label>
                <input type="number" min="1" max="<?php echo $generateDescriptionCount; ?>" class="form-control" id="ai_descriptionlength" ></input>

                <!-- <div class="_check d-flex mt-2 gap-2">
                  <input type="checkbox" id="applyCreditwords" class="m-0" />
                  <label for="applyCreditwords" class="d-flex flex-fill gap-1"><i class="coin_icon"></i> 4 credit points</label>
                </div> -->
              </div>
            </div>
          </div>
          <div class="aiimage_use_desc intopenai_modal_des_box" style="display:none;">
            <textarea class="form-control" autocomplete="off" id="ai_contentdescriptiontextarea" placeholder="<?php echo $this->translate("Describe your post, e.g. 'Tell me a joke'."); ?>"></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" id="generateaiDescription" class="btn btn-primary" <?php echo !$generateDescriptionCount  ? "disabled" : ""?>><?php echo $this->translate('Generate'); ?></button>
        </div>
      </div>
    </div>
  </div>
</div>
<script type="text/javascript">
  en4.core.runonce.add(function () {
    composeInstance.addPlugin(new Composer.Plugin.IntopenaiDescription({
      title: '<?php echo $this->string()->escapeJavascript($this->translate('Generate Post')) ?>',
    }));
    scriptJquery(scriptJquery('#intopenaidescription_wrap').html()).appendTo('#append-script-data');
    scriptJquery('#intopenaidescription_wrap').remove();
  });
  AttachEventListerSE('click', '.recharge_ai', function(event) { 
    scriptJquery(".cancelgenerateaiDescription").trigger("click");
  })
  AttachEventListerSE('click', '#compose-intopenaiDescription-activator', function(event) { 
    scriptJquery(".compose-menu-close").trigger("click");
  })
  AttachEventListerSE('keyup','#ai_descriptiontextarea',function(){
    if(scriptJquery(this).val()){
      scriptJquery("#ai_descriptiontextarea").css("border",'');
    }else{
      scriptJquery("#ai_descriptiontextarea").css("border",'1px solid red');
    }
  })
  AttachEventListerSE('keyup','#ai_contentdescriptiontextarea',function(){
    changeDescriptionSubmitText();
  })
  AttachEventListerSE('change','#ai_descriptionlength',function(){
    if(scriptJquery(this).val()){
      scriptJquery("#ai_descriptionlength").css("border",'');
    }else{
      scriptJquery("#ai_descriptionlength").css("border",'1px solid red');
    }
  })
  function changeDescriptionSubmitText(){
    if(scriptJquery("#ai_contentdescriptiontextarea").val()){
      scriptJquery("#generateaiDescription").html("<?php echo $this->translate('Add Content'); ?> ");
    }else{
      scriptJquery("#generateaiDescription").html("<?php echo $this->translate('Generate'); ?> ");
    }
    return scriptJquery("#ai_contentdescriptiontextarea").val().length;
  }
  AttachEventListerSE('click','#generateaiDescription',function(){
    scriptJquery(".ai_word").hide();
    if(changeDescriptionSubmitText() > 0){
      // set content
      composeInstance.setContent(scriptJquery("#ai_contentdescriptiontextarea").val());
      scriptJquery(".cancelgenerateaiDescription").trigger("click");
      scriptJquery("#activity_body").trigger("focus");
      autosize(scriptJquery('#activity_body').removeAttr("class").removeAttr("data-autosize-on"));
      autosize(scriptJquery("#activity_body"));
      
      scriptJquery("#ai_descriptiontextarea").val("");
      scriptJquery("#ai_descriptionlength").val("");
      scriptJquery(".aiimage_use_desc").hide();
      scriptJquery("#ai_contentdescriptiontextarea").val("");
      changeDescriptionSubmitText();
      return;
    }
   
    let isValid = true;
    if(!scriptJquery("#ai_descriptiontextarea").val()){
      scriptJquery("#ai_descriptiontextarea").css("border",'1px solid red');
      isValid = false;
    }else{
      scriptJquery("#ai_descriptiontextarea").css("border",'');
    }
    if(!scriptJquery("#ai_descriptionlength").val()){
      scriptJquery("#ai_descriptionlength").css("border",'1px solid red');
      isValid = false;
    }else{
      scriptJquery("#ai_descriptionlength").css("border",'');
    }
    if(!isValid) return;
    scriptJquery("#generateaiDescription").attr("disabled",true);
    scriptJquery("#generateaiDescription").html('<i class="fas fa-circle-notch fa-spin"></i>');
    scriptJquery.post(en4.core.baseUrl+"intopenai/index/content",{text:scriptJquery("#ai_descriptiontextarea").val(),length:scriptJquery("#ai_descriptionlength").val()},function(response){
      scriptJquery("#generateaiDescription").html('<?php echo $this->translate('Generate'); ?>');
      var result = JSON.parse(response);
      if(result.status == 0){
        // error
        scriptJquery(".ai_word").show();
        scriptJquery(".ai_word").html(result.message);
      }else{
        scriptJquery("#word_available_ai").html(result.word);
        scriptJquery("#ai_descriptionlength").attr('max',result.availableCount);
        scriptJquery(".aiimage_use_desc").show();
        scriptJquery("#ai_contentdescriptiontextarea").val(result.data);
      }
      scriptJquery("#generateaiDescription").removeAttr("disabled");
      changeDescriptionSubmitText();
    })

  })

</script>
