<script data-cfasync="false" type="text/javascript">
    productaddon = {};
    productaddon.id = <?php echo $this->productaddonid; ?>;
    productaddon.grouptype = <?php echo $this->grouptype; ?>;
    productaddon.pluginvar = "<?php echo $this->pluginvar; ?>";
    <?php
        $js_array = json_encode($this->productgroups);
        echo "productaddon.productgroups = ". $js_array . ";\n";
    ?>

    productaddon.filterBy = function(el,filter) {
        $(el).closest('.nav-pills').find('.nav-link').removeClass('active');
        $(el).addClass('active');

        $('.language').hide();
        $('.'+filter).show();
    }

    //Code for prices in different currencies
    function addonPricingFilterBy (el,filter)
    {
        $(el).closest('.nav-pills').find('.nav-link').removeClass('active');
        $(el).addClass('active');

        $('.currencyprice').hide();
        $('.currencyCode'+filter).show();
    }
    //Code for prices in different currencies
</script>
<?php
    //DOMAIN
    $displayClass = 'displayIfDomain';

    //NOT DOMAIN
    if($this->grouptype != PACKAGE_TYPE_DOMAIN){
        $displayClass = 'displayIfOther';
    }
?>

<div class="page-title">
    <h1><?php echo $this->user->lang("Product Addon"); ?></h1>
    <span><?php echo $this->user->lang("Addons are additional services/product addons that can be attached to product orders."); ?></span>
</div>

<div class="cm-holder">
    <div class="form-wrapper">
<div class="fieldwrapper withcolor">
    <form id="addondata">
    <?php $languages = CE_Lib::getEnabledLanguages(true);
    if(count($languages) > 1){
        $active = true; ?>
        <ul class="nav nav-pills">
        <?php foreach($languages as $languageKey => $language){ ?>
            <li class="nav-item">
                <a class="nav-link <?php if($active){echo 'active default-language-tab'; $active=false;} ?>"
                   href="javascript:void(0)"
                   onclick="productaddon.filterBy(this,'<?php echo $languageKey; ?>')">
                   <?php echo $language; ?>
                </a>
            </li>
        <?php } ?>
        </ul>
    <?php } ?>

<div class="mb-3">
  <label for="mainlanguageproduct-addon-name" class="form-label">
    <?php echo $this->user->lang("Name of Addon"); ?>
  </label>
  <?php if(count($languages) > 1){
      $active = true;
      foreach($languages as $languageKey => $language){ ?>
          <span class="language <?php echo $languageKey; ?> text name"
                <?php if(!$active){echo 'style="display: none"';} ?>>
            <input class="required form-control"
                   type="text"
                   name="product-addon-name<?php echo $languageKey; ?>"
                   <?php if($active){$active = false; echo 'id="mainlanguageproduct-addon-name"';} ?>
                   value="<?php echo $this->addonNameLanguages[$languageKey]; ?>" />
          </span>
      <?php }
  }else{ ?>
      <span class="language text name">
        <input class="required form-control"
               type="text"
               name="product-addon-name"
               id="mainlanguageproduct-addon-name"
               value="<?php echo $this->addonName; ?>" />
      </span>
  <?php } ?>
</div>

<div class="mb-3">
  <label for="product-groups" class="form-label">
    <span class="tip-target"
          data-bs-toggle="tooltip"
          data-bs-placement="right"
          title="Select which products groups this addon is available to. Assigning product groups helps in managing addon selection in the product edit screen as it limits only addons that are applicable to your product.">
      <?php echo $this->user->lang("Available To Product Groups"); ?>
    </span>
  </label>
  <select multiple="multiple"
          id="product-groups"
          name="product-groups[]"
          class="form-select multiSelect"
          placeholder="Select product group(s)"
          style="width:100%;display:none;">
      <?php
          foreach ($this->productgroups as $key=>$cat) {
              echo "<optgroup value='0' data-grouptype='".$cat[0]['typeid']."' label='Groups of type: ".$key."'>";
              foreach($cat as $productgroup) {
                  $selected = (in_array($productgroup['id'],$this->productgroup_ids)) ? "selected" : "";
                  echo "<option ".$selected." value='".$productgroup['id']."'>".$productgroup['name']."</option>";
              }
              echo "</optgroup>";
          }
      ?>
  </select>
</div>

    <label class="mt-3">
      <span class='tip-target'
            data-bs-toggle="tooltip"
            data-bs-placement='right'
            title='Visible to clients during the order process.'>
        <?php echo $this->user->lang("Addon description"); ?>
      </span>
    </label>
    <?php if(count($languages) > 1){
        $active = true;
        foreach($languages as $languageKey => $language){ ?>
            <span class="language <?php echo $languageKey; ?> textarea"
                  <?php if(!$active){echo 'style="display: none"';} ?>>
              <textarea class="wysihtml5 form-control"
                        name="product-addon-description<?php echo $languageKey; ?>"
                        <?php if($active){$active = false; echo 'id="mainlanguageproduct-addon-description"';} ?>
                        style='height:70px;'><?php echo $this->descriptionLanguages[$languageKey]; ?></textarea>
            </span>
        <?php }
    }else{ ?>
        <span class="language textarea" >
          <textarea class="wysihtml5 form-control"
                    name="product-addon-description"
                    id="mainlanguageproduct-addon-description"
                    style='height:70px;'><?php echo $this->description; ?></textarea>
        </span>
    <?php } ?>

    <ul class="nav nav-tabs pt-3">
        <li class="nav-item">
          <a class="nav-link active"
             data-bs-toggle="tab"
             data-bs-target="#div-addonoptions"
             href="#"><?php echo $this->user->lang('Addon Options'); ?></a>
        </li>
        <li class="nav-item">
          <a class="nav-link"
             data-bs-toggle="tab"
             data-bs-target="#div-addonpluginsettings"
             href="#"><?php echo $this->user->lang('Advanced Settings'); ?></a>
        </li>
    </ul>

    <div class="tab-content">
        <div class="tab-pane fade show active" id="div-addonoptions">
            <div class="alert alert-warning mt-2">
              <?php echo $this->user->lang('Prices left empty will not be shown as an available option for this addon. Tick the Force checkbox below the billing period price to force showing this option even when the client has selected a non matching billing cycle during signup.'); ?>
            </div>
<?php
    //Code for prices in different currencies
    include_once 'modules/billing/models/CurrencyGateway.php';

    $gateway = new CurrencyGateway($this->user);
    $currencies = $gateway->GetCurrencies();

    if ($currencies['totalcount'] > 1) {
?>
        <ul class="nav nav-pills mt-3">
<?php
        foreach ($currencies['currencies'] as $currencyValues) {
?>
            <li class="nav-item">
                <a class="nav-link <?php if ($currencyValues['isdefault']) { echo 'active default-language-tab'; } ?>"
                   href="javascript:void(0)"
                   onclick="addonPricingFilterBy(this,'<?php echo $currencyValues['abrv']; ?>')">
                   <?php echo $currencyValues['name']; ?>
                </a>
            </li>
<?php
        }
?>
        </ul>
<?php
    }
    //Code for prices in different currencies
?>
            <table id="table-addonoptions" class="table table-hover">
                <thead>
                    <tr class="nodrag nodrop">
                        <th style="width:13px;"></th>
                        <th>
                          &nbsp;<span class='tip-target'
                                      data-bs-html="true"
                                      data-bs-toggle="tooltip"
                                      data-bs-placement='right'
                                      title="<?php echo $this->user->lang("Description of the addon option displayed to client"); ?>">
                                      <?php echo $this->user->lang('Option Label'); ?>
                          </span>
                        </th>
                        <?php foreach ($this->productAddonsPricesExtraData as $cycle => $extraDataValues) {
                            if ($cycle == 0) {
                                continue;
                            } ?>
                                <th class="<?php echo implode(' ', $this->productAddonsPricesExtraData[$cycle]['class']); ?>"
                                    <?php echo (in_array($displayClass, $this->productAddonsPricesExtraData[$cycle]['class']))? '': ' style="display:none;" '; ?>>
                                    &nbsp;<?php echo $this->user->lang($this->productAddonsPricesExtraData[$cycle]['name']); ?>
                                </th>
                        <?php } ?>
                        <th class="<?php echo implode(' ', $this->productAddonsPricesExtraData[0]['class']); ?>"
                            <?php echo (in_array($displayClass, $this->productAddonsPricesExtraData[0]['class']))? '': ' style="display:none;" '; ?>>
                            &nbsp;<?php echo $this->user->lang($this->productAddonsPricesExtraData[0]['name']); ?>
                        </th>
                        <th class="pluginvaluecell">
                          &nbsp;<span class='tip-target'
                                      data-bs-html="true"
                                      data-bs-toggle="tooltip"
                                      title="<?php echo $this->user->lang("The value sent to selected plugin when this option is selected"); ?>">
                                      <?php echo $this->user->lang('Plugin Value'); ?>
                          </span>
                        </th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <tr class="nooption nodrag nodrop"
                        <?php if (count($this->productAddonsPrices) > 0) {?> style="display:none;" <?php } ?>>
                        <td colspan="10" class="nooptionsavailable">
                          <div><?php echo $this->user->lang('No options have been defined for this addon'); ?></div>
                        </td>
                    </tr>
                    <tr class="clone-addon-option" style="display:none;">
                        <td><div class="drag-icon"></div></td>
                        <td>
                            <?php if(count($languages) > 1){
                                $active = true;
                                foreach($languages as $languageKey => $language){ ?>
                                    <span class="language <?php echo $languageKey; ?> text <?php if($active){echo 'mainlanguageoptionname';} ?>"
                                          <?php if(!$active){echo 'style="display: none"';}else{$active = false;} ?>>
                                      <input class="required form-control d-inline-block form-control-sm"
                                             type="text"
                                             name="optionname<?php echo $languageKey; ?>"
                                             style="width:110px;"><br/>
                                    </span>
                                <?php }
                            }else{ ?>
                                <input class="required form-control d-inline-block form-control-sm"
                                       type="text"
                                       name="optionname"
                                       style="width:110px;"><br/>
                            <?php } ?>
                            <div class="form-check form-check-inline">
                              <input class="form-check-input" type="checkbox" name="openticket">
                              <label class="form-check-label">
                                <span data-bs-toggle="tooltip"
                                      title='Open ticket upon selecting this addon'>
                                      <small><?php echo $this->user->lang('Open Ticket'); ?></small>
                                </span>
                              </label>
                            </div>
                        </td>
<!-- CODE FOR PRICES IN DIFFERENT CURRENCIES -->
<?php
    if ($currencies['totalcount'] > 1) {
?>
                        <?php foreach ($this->productAddonsPricesExtraData as $cycle => $extraDataValues) {
                            if ($cycle == 0) {
                                continue 1;
                            } ?>
                                <td class="<?php echo implode(' ', $this->productAddonsPricesExtraData[$cycle]['class']); ?>"
                                    <?php echo (in_array($displayClass, $this->productAddonsPricesExtraData[$cycle]['class']))? '': ' style="display:none;" '; ?>>
<?php
                                    foreach ($currencies['currencies'] as $currencyValues) {
?>
                                        <span class="currencyprice currencyCode<?php echo $currencyValues['abrv']; ?>"
                                              <?php if (!$currencyValues['isdefault']) { echo 'style="display: none"'; } ?> >
                                            <input class="price form-control d-inline-block form-control-sm"
                                                   type="text"
                                                   name='<?php echo $currencyValues['abrv']; ?>_price<?php echo $cycle; ?>'
                                                   <?php if ($currencyValues['isdefault']) { echo 'id="maincurrencyprice'.$cycle.'"'; } ?>
                                                   style="width:55px;text-align:right;" ><br/>
                                            <div class="form-check form-check-inline displayIfOther"
                                                 <?php echo (in_array($displayClass, array('displayIfOther')))? '': ' style="display:none;" '; ?>>
                                              <input class="form-check-input force"
                                                     type="checkbox"
                                                     name="<?php echo $currencyValues['abrv']; ?>_price<?php echo $cycle; ?>_force"
                                                     <?php if ($currencyValues['isdefault']) { echo 'id="maincurrencyprice'.$cycle.'_force"'; } ?>>
                                              <label class="form-check-label">
                                                <span data-bs-toggle="tooltip"
                                                      title='Click checkbox if you want to force showing this period for this option even if the client has not selected this billing cycle as their selected billing period.'>
                                                      <small><?php echo $this->user->lang('Force'); ?></small>
                                                </span>
                                              </label>
                                            </div>
                                        </span>
<?php
                                    }
?>
                                </td>
                        <?php } ?>
                        <td class="<?php echo implode(' ', $this->productAddonsPricesExtraData[0]['class']); ?>"
                            <?php echo (in_array($displayClass, $this->productAddonsPricesExtraData[0]['class']))? '': ' style="display:none;" '; ?>>
<?php
                            foreach ($currencies['currencies'] as $currencyValues) {
?>
                                <span class="currencyprice currencyCode<?php echo $currencyValues['abrv']; ?>"
                                      <?php if (!$currencyValues['isdefault']) { echo 'style="display: none"'; } ?> >
                                    <input class="price form-control d-inline-block form-control-sm"
                                           type="text"
                                           name='<?php echo $currencyValues['abrv']; ?>_price0'
                                           <?php if ($currencyValues['isdefault']) { echo 'id="maincurrencyprice0"'; } ?>
                                           style="width:55px;text-align:right;" ><br/>
                                </span>
<?php
                            }
?>
                        </td>
<?php
    } else {
?>
                        <?php foreach ($this->productAddonsPricesExtraData as $cycle => $extraDataValues) {
                            if ($cycle == 0) {
                                continue;
                            } ?>
                                <td class="<?php echo implode(' ', $this->productAddonsPricesExtraData[$cycle]['class']); ?>"
                                    <?php echo (in_array($displayClass, $this->productAddonsPricesExtraData[$cycle]['class']))? '': ' style="display:none;" '; ?>>
                                    <input class="price form-control d-inline-block form-control-sm"
                                           type="text"
                                           name='price<?php echo $cycle; ?>'
                                           id='maincurrencyprice<?php echo $cycle; ?>'
                                           style="width:55px;text-align:right;" ><br/>
                                    <div class="form-check form-check-inline displayIfOther"
                                         <?php echo (in_array($displayClass, array('displayIfOther')))? '': ' style="display:none;" '; ?>>
                                      <input class="form-check-input force"
                                             type="checkbox"
                                             name="price<?php echo $cycle; ?>_force"
                                             id="maincurrencyprice<?php echo $cycle; ?>_force">
                                      <label class="form-check-label">
                                        <span data-bs-toggle="tooltip"
                                              title='Click checkbox if you want to force showing this period for this option even if the client has not selected this billing cycle as their selected billing period.'>
                                              <small><?php echo $this->user->lang('Force'); ?></small>
                                        </span>
                                      </label>
                                    </div>
                                </td>
                        <?php } ?>
                        <td class="<?php echo implode(' ', $this->productAddonsPricesExtraData[0]['class']); ?>"
                            <?php echo (in_array($displayClass, $this->productAddonsPricesExtraData[0]['class']))? '': ' style="display:none;" '; ?>>
                            <input class="price form-control d-inline-block form-control-sm"
                                   type="text"
                                   name='price0'
                                   id='maincurrencyprice0'
                                   style="width:55px;text-align:right;" ><br/>
                        </td>
<?php
    }
?>
<!-- /CODE FOR PRICES IN DIFFERENT CURRENCIES -->
                        <td class="pluginvaluecell">
                            <input type="text" name='plugin_var_value'
                                   class="form-control d-inline-block"
                                   style="width:50px;text-align:right;">
                        </td>
                        <td>
                            <button type="button"
                                    data-candelete="1"
                                    class="btn-close removeoption"
                                    aria-label="Close"></button>
                        </td>
                    </tr>
<!-- CODE FOR PRICES IN DIFFERENT CURRENCIES -->
<?php
    if ($currencies['totalcount'] > 1) {
?>
                    <?php foreach ($this->productAddonsPrices as $option) { ?>
                        <tr class="addon-option" data-new-id="0" data-addon-id="<?php echo $option['id']; ?>">
                            <td><div class="drag-icon"></div></td>
                            <td>
                                <?php if(count($languages) > 1){
                                    $active = true;
                                    foreach($languages as $languageKey => $language){ ?>
                                        <span class="language <?php echo $languageKey; ?> text <?php if($active){echo 'mainlanguageoptionname';} ?>"
                                              <?php if(!$active){echo 'style="display: none"';}else{$active = false;} ?>>
                                          <input class="required form-control d-inline-block"
                                                 type="text"
                                                 name="optionname<?php echo $languageKey; ?>"
                                                 style="width:110px;"
                                                 value="<?php echo $option['detailLanguages'][$languageKey]; ?>"
                                                 placeholder=""><br/>
                                        </span>
                                    <?php }
                                }else{ ?>
                                    <input class="required form-control d-inline-block"
                                           type="text"
                                           name="optionname"
                                           style="width:110px;"
                                           value="<?php echo $option['detail']; ?>"
                                           placeholder=""><br/>
                                <?php } ?>
                                <div class="form-check form-check-inline">
                                  <input class="form-check-input"
                                         type="checkbox"
                                         name="openticket"
                                         <?php if($option['openticket'] == 1) echo "checked"; ?>>
                                  <label class="form-check-label">
                                    <span data-bs-toggle="tooltip"
                                          title='Open ticket upon selecting this addon'>
                                          <small>Open Ticket</small>
                                    </span>
                                  </label>
                                </div>
                            </td>
                            <?php foreach ($this->productAddonsPricesExtraData as $cycle => $extraDataValues) {
                                if ($cycle == 0) {
                                    continue 1;
                                } ?>
                                <td class="<?php echo implode(' ', $this->productAddonsPricesExtraData[$cycle]['class']); ?>"
                                    <?php echo (in_array($displayClass, $this->productAddonsPricesExtraData[$cycle]['class']))? '': ' style="display:none;" '; ?>>
<?php
                                    foreach ($currencies['currencies'] as $currencyValues) {
?>
                                        <span class="currencyprice currencyCode<?php echo $currencyValues['abrv']; ?>"
                                              <?php if (!$currencyValues['isdefault']) { echo 'style="display: none"'; } ?> >
                                            <input class="price form-control d-inline-block form-control-sm"
                                                   type="text"
                                                   name='<?php echo $currencyValues['abrv']; ?>_price<?php echo $cycle; ?>'
                                                   <?php if ($currencyValues['isdefault']) { echo 'id="maincurrencyprice'.$cycle.'"'; } ?>
                                                   style="width:55px;text-align:right;"
                                                   value="<?php echo $this->productAddonsPricesCurrencies[$currencyValues['abrv']][$option['id']]['price'.$cycle]; ?>"><br/>
                                            <div class="form-check form-check-inline displayIfOther"
                                                 <?php echo (in_array($displayClass, array('displayIfOther')))? '': ' style="display:none;" '; ?>>
                                              <input class="form-check-input force"
                                                     type="checkbox"
                                                     name="<?php echo $currencyValues['abrv']; ?>_price<?php echo $cycle; ?>_force"
                                                     <?php if ($currencyValues['isdefault']) { echo 'id="maincurrencyprice'.$cycle.'_force"'; } ?>
                                                     <?php if($this->productAddonsPricesCurrencies[$currencyValues['abrv']][$option['id']]['price'.$cycle.'_force'] == 1) echo "checked"; ?>>
                                              <label class="form-check-label">
                                                <span data-bs-toggle="tooltip"
                                                      title='Click checkbox if you want to force showing this period for this option even if the client has not selected this billing cycle as their selected billing period.'>
                                                      <small><?php echo $this->user->lang('Force'); ?></small>
                                                </span>
                                              </label>
                                            </div>
                                        </span>
<?php
                                    }
?>
                                </td>
                            <?php } ?>
                            <td class="<?php echo implode(' ', $this->productAddonsPricesExtraData[0]['class']); ?>"
                                <?php echo (in_array($displayClass, $this->productAddonsPricesExtraData[0]['class']))? '': ' style="display:none;" '; ?>>
<?php
                                    foreach ($currencies['currencies'] as $currencyValues) {
?>
                                <span class="currencyprice currencyCode<?php echo $currencyValues['abrv']; ?>"
                                      <?php if (!$currencyValues['isdefault']) { echo 'style="display: none"'; } ?> >
                                    <input class="price form-control d-inline-block form-control-sm"
                                           type="text"
                                           name='<?php echo $currencyValues['abrv']; ?>_price0'
                                           <?php if ($currencyValues['isdefault']) { echo 'id="maincurrencyprice0"'; } ?>
                                           style="width:55px;text-align:right;"
                                           value="<?php echo $this->productAddonsPricesCurrencies[$currencyValues['abrv']][$option['id']]['price0']; ?>"><br/>
                                </span>
<?php
                                    }
?>
                            </td>
                            <td class="pluginvaluecell">
                                <input type="text"
                                       name='plugin_var_value'
                                       class="form-control d-inline-block"
                                       style="width:50px;text-align:right;"
                                       value="<?php echo $option['plugin_var_value']; ?>">
                            </td>
                            <td>
                                <button type="button"
                                        data-candelete="<?php echo $option['delete_ok']; ?>"
                                        class="btn-close removeoption"
                                        aria-label="Close"></button>
                            </td>
                        </tr>
                    <?php } ?>
<?php
    } else {
?>
                    <?php foreach ($this->productAddonsPrices as $option) { ?>
                        <tr class="addon-option" data-new-id="0" data-addon-id="<?php echo $option['id']; ?>">
                            <td><div class="drag-icon"></div></td>
                            <td>
                                <?php if(count($languages) > 1){
                                    $active = true;
                                    foreach($languages as $languageKey => $language){ ?>
                                        <span class="language <?php echo $languageKey; ?> text <?php if($active){echo 'mainlanguageoptionname';} ?>"
                                              <?php if(!$active){echo 'style="display: none"';}else{$active = false;} ?>>
                                          <input class="required form-control d-inline-block"
                                                 type="text"
                                                 name="optionname<?php echo $languageKey; ?>"
                                                 style="width:110px;"
                                                 value="<?php echo $option['detailLanguages'][$languageKey]; ?>"
                                                 placeholder=""><br/>
                                        </span>
                                    <?php }
                                }else{ ?>
                                    <input class="required form-control d-inline-block"
                                           type="text"
                                           name="optionname"
                                           style="width:110px;"
                                           value="<?php echo $option['detail']; ?>"
                                           placeholder=""><br/>
                                <?php } ?>
                                <div class="form-check form-check-inline">
                                  <input class="form-check-input"
                                         type="checkbox"
                                         name="openticket"
                                         <?php if($option['openticket'] == 1) echo "checked"; ?>>
                                  <label class="form-check-label">
                                    <span data-bs-toggle="tooltip"
                                          title='Open ticket upon selecting this addon'>
                                          <small>Open Ticket</small>
                                    </span>
                                  </label>
                                </div>
                            </td>
                            <?php foreach ($this->productAddonsPricesExtraData as $cycle => $extraDataValues) {
                                if ($cycle == 0) {
                                    continue;
                                } ?>
                                <td class="<?php echo implode(' ', $this->productAddonsPricesExtraData[$cycle]['class']); ?>"
                                    <?php echo (in_array($displayClass, $this->productAddonsPricesExtraData[$cycle]['class']))? '': ' style="display:none;" '; ?>>
                                    <input class="price form-control d-inline-block"
                                           type="text"
                                           name='price<?php echo $cycle; ?>'
                                           style="width:55px;text-align:right;"
                                           value="<?php echo $option['price'.$cycle]; ?>"><br/>
                                    <div class="form-check form-check-inline displayIfOther"
                                         <?php echo (in_array($displayClass, array('displayIfOther')))? '': ' style="display:none;" '; ?>>
                                      <input class="form-check-input force"
                                             type="checkbox"
                                             name="price<?php echo $cycle; ?>_force"
                                             <?php if($option['price'.$cycle.'_force'] == 1) echo "checked"; ?>>
                                      <label class="form-check-label">
                                        <span data-bs-toggle="tooltip"
                                              title='Click checkbox if you want to force showing this period for this option even if the client has not selected this billing cycle as their selected billing period.'>
                                              <small><?php echo $this->user->lang('Force'); ?></small>
                                        </span>
                                      </label>
                                    </div>
                                </td>
                            <?php } ?>
                            <td class="<?php echo implode(' ', $this->productAddonsPricesExtraData[0]['class']); ?>"
                                <?php echo (in_array($displayClass, $this->productAddonsPricesExtraData[0]['class']))? '': ' style="display:none;" '; ?>>
                                <input class="price form-control d-inline-block"
                                       type="text"
                                       name='price0'
                                       style="width:55px;text-align:right;"
                                       value="<?php echo $option['price0']; ?>"><br/>
                            </td>
                            <td class="pluginvaluecell">
                                <input type="text"
                                       name='plugin_var_value'
                                       class="form-control d-inline-block"
                                       style="width:50px;text-align:right;"
                                       value="<?php echo $option['plugin_var_value']; ?>">
                            </td>
                            <td>
                                <button type="button"
                                        data-candelete="<?php echo $option['delete_ok']; ?>"
                                        class="btn-close removeoption"
                                        aria-label="Close"></button>
                            </td>
                        </tr>
                    <?php } ?>
<?php
    }
?>

                </tbody>
            </table>

            <button type="button" class="btn btn-secondary add-product-addon">
              <span><?php echo $this->user->lang('Add Option'); ?></span>
            </button>

        </div>
        <div class="tab-pane fade" id="div-addonpluginsettings" style="margin-left:10px;">

            <div class="alert alert-warning mt-2">
                <?php echo $this->user->lang('Integrate this Addon with the Plugin associated to your Product, providing plugins additional instructions when setting up products based on the values selected for this addon.'); ?>
            </div>

            <label class="mt-2"><?php echo $this->user->lang("Plugin Variable"); ?></label>
            <select name="pluginoption" id="pluginoption" class="form-select normalSelect2" style="width:330px;"></select><br/>
            <div id="custompluginvariable" style="display:none;">
                <label class="mt-3">
                  <span data-bs-toggle="tooltip"
                        title='<?php echo $this->user->lang("Name to be passed to any API with the selected option value"); ?>.'>
                        <?php echo $this->user->lang("Variable Name"); ?>
                  </span>
                </label>
                <input type="text" id="custompluginvariable_value" class="form-control" style="width:317px;" />
            </div>
            <div class="mt-3">
                <label id="pluginvar_description"></label>
                <label id="pluginvar_availablein"></label>
            </div>
        </div>
        <div class="form-actions mt-3 text-end">
            <button type="submit" class="submit-addon cm-btns orange">
                <?php echo $this->user->lang("Save Changes"); ?>
            </button>
            <button class="cm-btns dark cancel-go-back" data-url="index.php?fuse=admin&controller=addons&view=productaddons">
                <?php echo $this->user->lang('Cancel'); ?>
            </button>
        </div>
    </div>


    </form>
</div>
    </div>
</div>

<script data-cfasync="false">

productaddon.newidcount = 1;
productaddon.product_type = null;
productaddon.old_product_groups = '';
productaddon.new_product_groups = '';

productaddon.clonenewoption = function ()
{
    var newEl = $('.clone-addon-option').clone();
    newEl.removeClass('clone-addon-option');
    newEl.addClass('addon-option');
    newEl.attr('data-addon-id','0');
    newEl.attr('data-new-id',productaddon.newidcount++);
    newEl.show();

    $("#table-addonoptions").append(newEl);

    $('.removeoption').unbind('click',productaddon.deleteaddonoption);
    $('.removeoption').bind('click',productaddon.deleteaddonoption);
};

productaddon.deleteaddonoption = function (e)
{
    if ($('.addon-option').length === 1) {
        RichHTML.error("You can not delete all the options from an addon. You must have at least one option.");
    } else {
        if ($(this).data('candelete') != "1") {
            RichHTML.error("This option is in use. You can not delete it until you first change the following package to use another option: <br>" + $(this).data('candelete'));
        } else {
            $(this).closest('tr').remove();
        }
    }
};

productaddon.addaddonoption = function (e)
{
    $('.nooption').hide();
    productaddon.clonenewoption();
    productaddon.restrictPriceFormat();
};

productaddon.convertbooltoint = function (val)
{
    return (val) ? 1 : 0;
};

productaddon.load_plugin_variables = function () {
    $.get(
        'index.php?fuse=admin&controller=addons&action=getaddonvariables&productType=' + productaddon.grouptype,
        function (data) {
            var div = 0;
            data = clientexec.parseResponse(data);

            var $pluginoption = $('#pluginoption');
            $pluginoption.empty();

            $(data.addons).each(function (index, obj) {
                // handle custom variable case
                if (productaddon.pluginvar.indexOf("CUSTOM_") !== -1) {
                    $('#custompluginvariable_value').val(productaddon.pluginvar.replace("CUSTOM_", ""));
                    productaddon.pluginvar = "CUSTOM";
                }

                if (obj.name === '---') {
                    div++;
                    $pluginoption.append(
                        $('<option>', {
                            value: 'divider_' + div,
                            text: '---'
                        })
                    );
                } else {
                    $pluginoption.append(
                        $('<option>', {
                            value: obj.plugin_var,
                            text: obj.name,
                            'data-availablein': obj.available_in,
                            'data-description': obj.description
                        })
                    );
                }
            });

            // Set value correctly for Select2 v4
            $pluginoption.val(productaddon.pluginvar).trigger('change');
        }
    );
};


productaddon.reload_options = function (newGroupType)
{
    if (newGroupType == 3) {
        $('.displayIfOther').each(function (a, row)
            {
                $(this).hide();
            }
        );

        $('.displayIfDomain').each(function (a, row)
            {
                $(this).show();
            }
        );
    } else {
        $('.displayIfDomain').each(function (a, row)
            {
                $(this).hide();
            }
        );

        $('.displayIfOther').each(function (a, row)
            {
                $(this).show();
            }
        );
    }
}

productaddon.restrictPriceFormat = function ()
{
    $('.price').each(function ()
        {
            $(this).keydown(function (e)
                {
                    // Allow: delete, backspace, tab, escape, enter, . (110, 190)    Ctrl+A                                     home, end, left, right
                    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || (e.keyCode == 65 && e.ctrlKey === true) || (e.keyCode >= 35 && e.keyCode <= 39)) {
                         // let it happen, don't do anything
                         return;
                    }

                    // Ensure that it is a number and stop the keypress
                    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                        e.preventDefault();
                    }
                }
            );
        }
    );
}

$(document).ready(function () {

    if (productaddon.pluginvar != "NONE") {
        $('.pluginvaluecell').show();
    }


    $('#product-groups').select2({
        width: '100%',
        tokenSeparators: [',']
    });

    var $groups = $('#product-groups');

    // initial values
    productaddon.old_product_groups = $groups.val();
    productaddon.new_product_groups = $groups.val();

    // When selecting a group
    $groups.on('select2:select', function (e) {

        if (!e.params || !e.params.data) return;

        var label = $(e.params.data.element).closest("optgroup").data("grouptype");

        $groups.find('optgroup[data-grouptype!="' + label + '"]').remove();

        // Reload available cycles
        productaddon.reload_options(label);
        productaddon.grouptype = label;

        if ($('#pluginoption').val() == "NONE") {
            productaddon.load_plugin_variables();
        }
    });

    // Handle value changes
    $groups.on('change', function () {

        productaddon.new_product_groups = $(this).val();

        // Detect when everything is unselected
        if ((!productaddon.new_product_groups || productaddon.new_product_groups.length === 0) &&
            $('#pluginoption').val() == "NONE") {

            $groups.find('optgroup').remove();

            $.each(productaddon.productgroups, function (index, value) {

                var groupel = $('<optgroup data-grouptype="' + value[0].typeid + '" label="Groups of type:' + value[0].type + '"></optgroup>');

                $.each(value, function (index2, value2) {
                    groupel.append('<option value="' + value2.id + '">' + value2.name + '</option>');
                });

                $groups.append(groupel);
            });

            productaddon.grouptype = "";
            productaddon.load_plugin_variables();

            // Refresh Select2
            $groups.trigger('change.select2');
        }

        productaddon.old_product_groups = productaddon.new_product_groups;
    });


    productaddon.load_plugin_variables();

    if (productaddon.grouptype !== -1) {
        $('select').find('optgroup[data-grouptype!="' + productaddon.grouptype + '"]').remove();
    }

    $('#pluginoption').on('change', function () {
        $('#custompluginvariable').hide();
        $('#pluginvar_description').hide();
        $('#pluginvar_availablein').hide();

        if ($('#pluginoption').val() == "CUSTOM") {
            $('#custompluginvariable').show();
            $('.pluginvaluecell').show();
        } else if ($('#pluginoption').val() == "NONE") {
            $('.pluginvaluecell').hide();
        } else if ($('#pluginoption').val() && $('#pluginoption').val().indexOf('divider_') != -1) {
            $('#pluginoption').val("NONE").trigger("change");
            $('.pluginvaluecell').hide();
        } else {
            if ($(this).find('option:selected').data('availablein') !== "") {
                $('#pluginvar_description').text($(this).find('option:selected').data('description'));
                $('#pluginvar_availablein').text("Supported Plugins: " + $(this).find('option:selected').data('availablein'));
            } else {
                $('#pluginvar_description').text("");
                $('#pluginvar_availablein').html("<span style='color:red;'>Not integrated with any plugin.</span><br/>It is recommended that at least one option for this addon is set to 'Open Ticket'.</span>");
            }
            $('#pluginvar_description').show();
            $('#pluginvar_availablein').show();
            $('.pluginvaluecell').show();
        }
    });

    $('.add-product-addon').on('click', productaddon.addaddonoption);
    $('.removeoption').on('click', productaddon.deleteaddonoption);

    $('.submit-addon').on('click', function (e) {
        e.preventDefault();
        var pass = true;

        $('#addondata').parsley('validate');



        if (!$(".nav-pills .nav-link:first").hasClass("active")) {
            $(".default-language-tab").trigger("click");
        }

        if (!$('#mainlanguageproduct-addon-name').parsley('isValid')) {
            pass = false;
        }


        $('.addon-option').each(function () {
            var $optionName = $(this).find("input[name='optionname']");
            if ($optionName.length > 0) {
                if (!$optionName.parsley('isValid')) {
                    pass = false;
                }
            } else {
                $(this).find(".language.mainlanguageoptionname input").each(function () {
                    if (!$(this).parsley('isValid')) {
                        pass = false;
                    }
                });
            }
        });



        if (!pass) {
            return false;
        }

        RichHTML.mask();
        e.preventDefault();

        if ($('.addon-option').length === 0) {
            RichHTML.error("You must have at least one addon option before saving.");
            return;
        }

        $('.submit-addon').prop("disabled", true);

        var sortKey = 0;
        var addonpricing = [];
        var addonoption = {};
        $('.addon-option').each(function () {
            addonoption = {};
            addonoption.id = $(this).data('addon-id');

            if (typeof $(this).find("input[name='optionname']").val() !== "undefined") {
                addonoption.detail = $(this).find("input[name='optionname']").val();
            } else {
                $(this).find(".language").each(function () {
                    var fieldName = $(this).find("input").attr("name");
                    var fieldValue = $(this).find("input").val();
                    addonoption[fieldName] = fieldValue;
                });
            }

            $(this).find(".price").each(function () {
                var fieldName = $(this).attr("name");
                var fieldValue = $(this).val();
                addonoption[fieldName] = fieldValue;
            });

            $(this).find(".force").each(function () {
                var fieldName = $(this).attr("name");
                var fieldValue = productaddon.convertbooltoint($(this).is(':checked'));
                addonoption[fieldName] = fieldValue;
            });

            addonoption.pluginVarValue = $(this).find("input[name='plugin_var_value']").val();
            addonoption.sortKey = sortKey++;
            addonoption.openticket = productaddon.convertbooltoint($(this).find("input[name='openticket']").is(':checked'));
            addonoption.newid = $(this).data('new-id');
            addonpricing.push(addonoption);
        });

        var fielddata = {
            id: productaddon.id,
            addonpricing: addonpricing,
            pluginoption: $('#pluginoption').val(),
            custompluginvariable_value: $('#custompluginvariable_value').val(),
            productgroups: $("#product-groups").val()
        };






        $('.language.text.name').each(function () {
            var fieldName = $(this).find("input").attr("name");
            var fieldValue = $(this).find("input").val();
            fielddata[fieldName] = fieldValue;
        });



        $('.language.textarea').each(function () {
            var fieldName = $(this).find("textarea").attr("name");
            var fieldValue = $(this).find("textarea").val();
            if (fieldValue == "<p><br></p>") {
                fieldValue = "";
            }
            fielddata[fieldName] = fieldValue;
        });

        var all_old_are_new_product_groups = true;

        if (productaddon.old_product_groups !== null && productaddon.old_product_groups.length > 0) {
            all_old_are_new_product_groups = productaddon.old_product_groups.every(function (val) {
                if (productaddon.new_product_groups !== null && productaddon.new_product_groups.length > 0) {
                    return productaddon.new_product_groups.indexOf(val) >= 0;
                } else {
                    return false;
                }
            });
        }

        if (!all_old_are_new_product_groups) {
            e.preventDefault();
            RichHTML.msgBox(
                '<b>' + clientexec.lang('NOTICE:') + '</b><br><br>' +
                clientexec.lang('You have modified the availability to some Product Groups.') + '<br>' +
                clientexec.lang('Do you want existing clients to continue being charged this addon?'),
                { type: "confirm" },
                function (result) {
                    if (result.btn === clientexec.lang("Yes")) {
                        fielddata['keeprecurringfees'] = 1;
                    } else if (result.btn === clientexec.lang("No")) {
                        fielddata['keeprecurringfees'] = 0;
                    } else {
                        RichHTML.unMask();
                        $('.submit-addon').prop("disabled", false);
                        return false;
                    }



                    $.post('index.php?fuse=admin&controller=addons&action=saveproductaddon', fielddata, function (data) {
                        data = clientexec.parseResponse(data);
                        if (!data.error) {
                            window.location = 'index.php?fuse=admin&controller=addons&view=productaddons&groupid=' + $("#product-groups").val();
                        }
                        RichHTML.unMask();
                        $('.submit-addon').prop("disabled", false);
                    });
                }
            );
        } else {
            $.post('index.php?fuse=admin&controller=addons&action=saveproductaddon', fielddata, function (data) {
                data = clientexec.parseResponse(data);
                if (!data.error) {
                    window.location = 'index.php?fuse=admin&controller=addons&view=productaddons&groupid=' + $("#product-groups").val();
                }
                RichHTML.unMask();
                $('.submit-addon').prop("disabled", false);
            });
        }
    });

    productaddon.restrictPriceFormat();
});

// Tooltip init for BS5
document.addEventListener("DOMContentLoaded", function() {
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    tooltipTriggerList.map(function (tooltipTriggerEl) {
      return new bootstrap.Tooltip(tooltipTriggerEl)
    });

    clientexec.initTinyMCE('.wysihtml5', {
        images_upload_handler: false
    });
});
</script>
