<?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', 'image')){
  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 $generateImageCount = $this->viewer()->wallet_amount > 0 && Engine_Api::_()->authorization()->getPermission($this->viewer()->level_id, 'intopenai', 'image_price') > 0 ? floor($this->viewer()->wallet_amount/Engine_Api::_()->authorization()->getPermission($this->viewer()->level_id, 'intopenai', 'image_price')) : (Engine_Api::_()->authorization()->getPermission($this->viewer()->level_id, 'intopenai', 'image_price') == 0 ? 1 : 0); ?>
<div id="intopenaiimage_wrap" style="display:none">
  <div class="modal fade modalbox_wrap intopenai_generate_modal" id="intopenaiimage" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="intopenaiimageLabel" 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="intopenaiimageLabel"><?php echo $this->translate("Generate Image"); ?></h2>
          <button type="button" class="modal_close center_item cancelgenerateaiImage" 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_image" style="display:none">
          </div>
          <div class="clear">
            <div class="intopenai_generate_modal_top">
              <p class="mb-4 intopenai_modal_des fw-500"><?php echo $this->translate("You can generate and draw your own images using AI. Describe the image you want below and our AI will generate the images for you. You can select the image size and image count as well from below."); ?></p>
              <?php if(Engine_Api::_()->authorization()->getPermission($this->viewer()->level_id, 'intopenai', 'image_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="ai_image_count" class="font_color_primary"><?php echo floor(($this->viewer()->wallet_amount * $currentData->change_rate)/Engine_Api::_()->authorization()->getPermission($this->viewer()->level_id, 'intopenai', 'image_price'));?></b>
                    <span class="fw-500"><?php echo $this->translate("Images") ?></span>
                    <!--<span>($1254)</span>-->
                  </div>
                  
                  <div class="intopenai_balance_info_btn">
                    <a class="btn btn-primary recharge_ai_image 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/image</p>

                  <div class="intopenai_credit_points">
                    <p class="m-0 d-flex align-items-center gap-1"><b>Or Pay $0.9 +</b> <i class="coin_icon"></i> 1/<span class="font_small">image</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 image prompt below."); ?></label>
                <textarea class="form-control" autocomplete="off" id="ai_textarea" placeholder="<?php echo $this->translate('Enter a prompt to display an image'); ?>"></textarea>
              </div>
                
              <div class="input_field mb-3">
                <label class="form-label"><?php echo $this->translate("Image size"); ?></label>
                <select class="form-control" id="aiimage_size">
                  <option value="256x256">256x256</option>
                  <option value="512x512">512x512</option>
                  <option value="1024x1024" selected >1024x1024</option>
                </select>
                
              </div>
              <div class="input_field mb-3">
                <label class="form-label"><?php echo $this->translate("Images count"); ?></label>
                <select class="form-control" id="aiimage_count">
                  <option value="1">1</option>
                  <option value="2">2</option>
                  <option value="3" >3</option>
                  <option value="4" selected >4</option>
                </select>
                <!-- <div class="_check d-flex mt-2 gap-2">
                  <input type="checkbox" id="applyCredit" class="m-0" />
                  <label for="applyCredit" class="d-flex flex-fill gap-1"><i class="coin_icon"></i> 4 credit points</label>
                </div> -->
              </div>
            </div>
          </div>
          <div class="aiimage_use intopenai_images" style="display:none;">
              
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" id="generateaiImage" class="btn btn-primary" <?php echo !$generateImageCount  ? "disabled" : ""?>><?php echo $this->translate('Generate'); ?></button>
        </div>
        <div class="core_loading_cont_overlay" id="core_loading_cont_overlay" style="display:none;"></div>
      </div>
    </div>
  </div>
</div>
<script type="text/javascript">
  AttachEventListerSE('click', '.recharge_ai_image', function(event) { 
    scriptJquery(".cancelgenerateaiImage").trigger("click");
  })
  en4.core.runonce.add(function () {
    composeInstance.addPlugin(new Composer.Plugin.IntopenaiImage({
      title: '<?php echo $this->string()->escapeJavascript($this->translate('Generate Image')) ?>',
    }));
    scriptJquery(scriptJquery('#intopenaiimage_wrap').html()).appendTo('#append-script-data');
    scriptJquery('#intopenaiimage_wrap').remove();
  });
  AttachEventListerSE('click', '#compose-intopenaiImage-activator', function(event) { 
    scriptJquery(".compose-menu-close").trigger("click");
  })

  AttachEventListerSE('keyup','#ai_textarea',function(){
    if(scriptJquery(this).val()){
      scriptJquery("#ai_textarea").css("border",'');
    }else{
      scriptJquery("#ai_textarea").css("border",'1px solid red');
    }
  })
 
  AttachEventListerSE('click','#generateaiImage',function(){
    scriptJquery(".ai_image").hide();
    if(changeImageSubmitText() > 0){
      // add images
      let files = []
      scriptJquery(".image_ai_cnt.active").map((index,item) => {
        let src = scriptJquery(item).find("img").attr("src");
        let name = (src.split("?")[0]).split('/').pop()
        files.push({name:name,url:src,type:"image/png"});
      })
      if(scriptJquery("#compose-photo-activator").length > 0){
        scriptJquery("#compose-photo-activator").trigger("click");
        handleFileUploadSesalbum(files, scriptJquery('#videodragandrophandler'));
      }else{
        scriptJquery("#compose-albumvideo-activator").trigger("click");
        videohandleFileUpload(files, scriptJquery('#videodragandrophandler'));
      }
      
      scriptJquery(".cancelgenerateaiImage").trigger("click");
      scriptJquery("#ai_textarea").val("");
      scriptJquery(".aiimage_use").html("");
      scriptJquery(".aiimage_use").hide();
     
      changeImageSubmitText();
      return;
    }
    
    if(!scriptJquery("#ai_textarea").val()){
      scriptJquery("#ai_textarea").css("border",'1px solid red');
      return;
    }else{
      scriptJquery("#ai_textarea").css("border",'');
    }
    scriptJquery("#generateaiImage").attr("disabled",true);
    scriptJquery("#generateaiImage").html('<i class="fas fa-circle-notch fa-spin"></i>');
    
    scriptJquery.post(en4.core.baseUrl+"intopenai/index/image",{text:scriptJquery("#ai_textarea").val(),aiimage_size:scriptJquery("#aiimage_size").val(),aiimage_count:scriptJquery("#aiimage_count").val()},function(response){
      var result = JSON.parse(response);
      scriptJquery("#generateaiImage").html('<?php echo $this->translate('Generate'); ?>');
      if(result.status == 0){
        // error
        scriptJquery(".ai_image").show();
        scriptJquery(".ai_image").html(result.message);
      }else{
        scriptJquery(".aiimage_use").show();
        scriptJquery("#ai_image_count").html(result.imageCount);
        // show images
        let html = `<div class="d-flex gap-2 intopenai_images_list">`
        result.data.forEach(item => {
            html += `<div class="image_ai_cnt intopenai_images_item active">
            <div class="intopenai_images_item_inner">
              <img src="${item.url}" />
              <a class="remove_image_ai"></a>
            </div>
            </div>`
        })
        html += `</div>`
        scriptJquery(".aiimage_use").html(html);
      }
      scriptJquery("#generateaiImage").removeAttr("disabled");
      changeImageSubmitText();
    })

  })
  AttachEventListerSE('click','.image_ai_cnt',function(){ 
    if(scriptJquery(this).hasClass("active")){
      scriptJquery(this).removeClass("active");
    }else{
      scriptJquery(this).addClass("active")
    }
  })
  function changeImageSubmitText(){
    if(scriptJquery(".image_ai_cnt").length > 0){
      scriptJquery("#generateaiImage").html("<?php echo $this->translate('Add Images'); ?> ");
    }else{
      scriptJquery("#generateaiImage").html("<?php echo $this->translate('Generate'); ?> ");
    }
    return scriptJquery(".image_ai_cnt").length;
  }
  AttachEventListerSE('click','.remove_image_ai',function(){
    scriptJquery(this).closest(".image_ai_cnt").remove();
    changeImageSubmitText();
  })
  
</script>
