<?xml version="1.0" encoding="utf-8"?>
<modification>
    <name>DearSoft for OpenCart</name>
    <version>1.0.0</version>
    <author>DearSoft</author>
    <link>https://www.dearsoft.com.bd</link>
    <code>dearsoft</code>

    <!--
        Most of this extension's behaviour comes from files placed directly
        into the upload/ directory structure and the catalog/footer/after
        event registered on install — no XML modification needed for those.

        The operations below wire up the "AI Write Assistant" — an "Ask AI"
        helper injected into admin content forms (product, category,
        information, attribute, review, contact). It calls back into the
        existing dearsoft module controller (extension/module/dearsoft) and
        is gated by the "Enable AI Write Assistant" toggle on the AI Write
        Assistant settings tab.
    -->

    <file path="admin/controller/catalog/product.php">
        <operation>
            <search trim="true" index="0"><![CDATA[
                $this->response->setOutput($this->load->view('catalog/product_form'
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                $data['dearsoft_writer'] = $this->load->controller('extension/module/dearsoft/init_form', array('form_type' => 'product'));
                $data['dearsoft_bgremover'] = $this->load->controller('extension/module/dearsoft/init_bgremover');
            ]]></add>
        </operation>
    </file>

    <file path="admin/view/template/catalog/product_form.twig">
        <operation>
            <search trim="true" index="0"><![CDATA[
                {{ footer }}
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                {{ dearsoft_writer }}
            ]]></add>
        </operation>
    </file>

    <!--
        Review Assistant — adds a "Review Assistant" tab to the product edit
        page (enable per product, override the Google/Facebook review URLs,
        get a per-product QR code/link) and persists it alongside the normal
        product save. Anchors confirmed against stock OpenCart 3.0.5.0 core
        source: getForm()'s setOutput() call and editProduct() are unique,
        literal lines in admin/controller/catalog/product.php; the tab-seo
        <li> and pane are stable, unique markers in product_form.twig.
    -->
    <file path="admin/controller/catalog/product.php">
        <operation>
            <search trim="true" index="0"><![CDATA[
                $this->response->setOutput($this->load->view('catalog/product_form'
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                $reviewTab = $this->load->controller('extension/module/dearsoft/init_review_tab', array(
                    'product_id' => isset($this->request->get['product_id']) ? (int)$this->request->get['product_id'] : 0
                ));
                $data['dearsoft_review'] = $reviewTab['html'];
                $data['dearsoft_review_tab_label'] = $reviewTab['label'];
            ]]></add>
        </operation>
        <operation>
            <search trim="true" index="0"><![CDATA[
                $this->model_catalog_product->editProduct($this->request->get['product_id'], $this->request->post);
            ]]></search>
            <add position="after" trim="true" offset="0"><![CDATA[
                $this->load->model('extension/module/dearsoft');
                $this->model_extension_module_dearsoft->saveReviewProductSettings((int)$this->request->get['product_id'], $this->request->post);
            ]]></add>
        </operation>
    </file>

    <file path="admin/view/template/catalog/product_form.twig">
        <operation>
            <search trim="true" index="0"><![CDATA[
                <a href="#tab-seo" data-toggle="tab">{{ tab_seo }}</a></li>
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                <li><a href="#tab-review-assistant" data-toggle="tab">{{ dearsoft_review_tab_label }}</a></li>
            ]]></add>
        </operation>
        <operation>
            <search trim="true" index="0"><![CDATA[
                <div class="tab-pane" id="tab-seo">
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                {{ dearsoft_review|default('')|raw }}
            ]]></add>
        </operation>
    </file>

    <!--
        Key Feature Writer — adds a "Generate Features (AI)" button next to
        the (separate, pre-existing, third-party) "DearSoft Short Description
        Attribute" extension's Featured Text table on the product edit page.

        Deliberately does NOT anchor on that extension's own injected button
        markup: this modification and that extension's are two independent
        ocmod entries (different <code>), and their relative compile order
        isn't guaranteed — anchoring on content ANOTHER modification injects
        is order-dependent and silently no-ops if this one compiles first.
        Instead, keyfeature.js finds the #short-attribute table at runtime
        (a stable DOM id, confirmed on this site's live rendered page) and
        inserts the button client-side, after both extensions' server-
        rendered HTML already exists in the DOM — order-independent by
        construction. The only ocmod anchor here is the always-present,
        stock {{ footer }} line.
    -->
    <file path="admin/controller/catalog/product.php">
        <operation>
            <search trim="true" index="0"><![CDATA[
                $this->response->setOutput($this->load->view('catalog/product_form'
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                $data['dearsoft_keyfeature_enabled'] = $this->config->get('module_dearsoft_keyfeature_enabled') !== '0';
                $data['dearsoft_keyfeature_url'] = $this->url->link('extension/module/dearsoft/keyFeatureGenerate', 'user_token=' . $this->session->data['user_token'], true);
                $data['dearsoft_keyfeature_js_version'] = @filemtime(DIR_APPLICATION . 'view/javascript/dearsoft/keyfeature.js') ?: time();
            ]]></add>
        </operation>
    </file>

    <file path="admin/view/template/catalog/product_form.twig">
        <operation>
            <search trim="true" index="0"><![CDATA[
                {{ footer }}
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                {% if dearsoft_keyfeature_enabled %}
                <script type="text/javascript">
                    var dearsoftKeyfeatureUrl = {{ dearsoft_keyfeature_url|replace({'&amp;': '&'})|json_encode|raw }};
                </script>
                <script type="text/javascript" src="view/javascript/dearsoft/keyfeature.js?v={{ dearsoft_keyfeature_js_version }}"></script>
                {% endif %}
            ]]></add>
        </operation>
    </file>

    <!--
        Review Assistant — storefront "Write a Review" button embedded
        directly into the product page (in addition to the QR/link and the
        optional floating site-wide button). Anchor confirmed against this
        site's actual live theme files (both journal3 — the active theme —
        and default, for portability): {% if minimum > 1 %} is a stable,
        unique marker right after the add-to-cart button in both, outside
        any theme-specific conditional block, in catalog/controller/product/
        product.php's setOutput() call and the two product.twig files.
    -->
    <file path="catalog/controller/product/product.php">
        <operation>
            <search trim="true" index="0"><![CDATA[
                $this->response->setOutput($this->load->view('product/product', $data));
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                $data['dearsoft_review_button'] = $this->load->controller('extension/module/dearsoft_review/productButton', array(
                    'product_id' => (int)$this->request->get['product_id']
                ));
            ]]></add>
        </operation>
    </file>

    <file path="catalog/view/theme/journal3/template/product/product.twig">
        <operation>
            <search trim="true" index="0"><![CDATA[
                {% if minimum > 1 %}
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                {{ dearsoft_review_button|default('')|raw }}
            ]]></add>
        </operation>
    </file>

    <file path="catalog/view/theme/default/template/product/product.twig">
        <operation>
            <search trim="true" index="0"><![CDATA[
                {% if minimum > 1 %}
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                {{ dearsoft_review_button|default('')|raw }}
            ]]></add>
        </operation>
    </file>

    <file path="admin/controller/catalog/category.php">
        <operation>
            <search trim="true" index="0"><![CDATA[
                $this->response->setOutput($this->load->view('catalog/category_form'
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                $data['dearsoft_writer'] = $this->load->controller('extension/module/dearsoft/init_form', array('form_type' => 'category'));
            ]]></add>
        </operation>
    </file>

    <file path="admin/view/template/catalog/category_form.twig">
        <operation>
            <search trim="true" index="0"><![CDATA[
                {{ footer }}
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                {{ dearsoft_writer }}
            ]]></add>
        </operation>
    </file>

    <!--
        Review Assistant — category-wise scope. Same shape as the product-tab
        hook above (init_category_review_tab / saveReviewCategorySettings),
        anchored on category's own editCategory() call and its tab-seo
        <li>/pane — confirmed against the live category.php/category_form.twig
        (same tab set as product: general/data/seo/design).
    -->
    <file path="admin/controller/catalog/category.php">
        <operation>
            <search trim="true" index="0"><![CDATA[
                $this->response->setOutput($this->load->view('catalog/category_form'
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                $categoryReviewTab = $this->load->controller('extension/module/dearsoft/init_category_review_tab', array(
                    'category_id' => isset($this->request->get['category_id']) ? (int)$this->request->get['category_id'] : 0
                ));
                $data['dearsoft_category_review'] = $categoryReviewTab['html'];
                $data['dearsoft_category_review_tab_label'] = $categoryReviewTab['label'];
            ]]></add>
        </operation>
        <operation>
            <search trim="true" index="0"><![CDATA[
                $this->model_catalog_category->editCategory($this->request->get['category_id'], $this->request->post);
            ]]></search>
            <add position="after" trim="true" offset="0"><![CDATA[
                $this->load->model('extension/module/dearsoft');
                $this->model_extension_module_dearsoft->saveReviewCategorySettings((int)$this->request->get['category_id'], $this->request->post);
            ]]></add>
        </operation>
    </file>

    <file path="admin/view/template/catalog/category_form.twig">
        <operation>
            <search trim="true" index="0"><![CDATA[
                <a href="#tab-seo" data-toggle="tab">{{ tab_seo }}</a></li>
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                <li><a href="#tab-review-assistant" data-toggle="tab">{{ dearsoft_category_review_tab_label }}</a></li>
            ]]></add>
        </operation>
        <operation>
            <search trim="true" index="0"><![CDATA[
                <div class="tab-pane" id="tab-seo">
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                {{ dearsoft_category_review|default('')|raw }}
            ]]></add>
        </operation>
    </file>

    <file path="admin/controller/catalog/information.php">
        <operation>
            <search trim="true" index="0"><![CDATA[
                $this->response->setOutput($this->load->view('catalog/information_form'
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                $data['dearsoft_writer'] = $this->load->controller('extension/module/dearsoft/init_form', array('form_type' => 'information'));
            ]]></add>
        </operation>
    </file>

    <file path="admin/view/template/catalog/information_form.twig">
        <operation>
            <search trim="true" index="0"><![CDATA[
                {{ footer }}
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                {{ dearsoft_writer }}
            ]]></add>
        </operation>
    </file>

    <file path="admin/controller/catalog/attribute.php">
        <operation>
            <search trim="true" index="0"><![CDATA[
                $this->response->setOutput($this->load->view('catalog/attribute_form'
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                $data['dearsoft_writer'] = $this->load->controller('extension/module/dearsoft/init_form', array('form_type' => 'attribute'));
            ]]></add>
        </operation>
    </file>

    <file path="admin/view/template/catalog/attribute_form.twig">
        <operation>
            <search trim="true" index="0"><![CDATA[
                {{ footer }}
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                {{ dearsoft_writer }}
            ]]></add>
        </operation>
    </file>

    <file path="admin/controller/catalog/review.php">
        <operation>
            <search trim="true" index="0"><![CDATA[
                $this->response->setOutput($this->load->view('catalog/review_form'
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                $data['dearsoft_writer'] = $this->load->controller('extension/module/dearsoft/init_form', array('form_type' => 'review'));
            ]]></add>
        </operation>
    </file>

    <file path="admin/view/template/catalog/review_form.twig">
        <operation>
            <search trim="true" index="0"><![CDATA[
                {{ footer }}
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                {{ dearsoft_writer }}
            ]]></add>
        </operation>
    </file>

    <file path="admin/controller/marketing/contact.php">
        <operation>
            <search trim="true" index="0"><![CDATA[
                $this->response->setOutput($this->load->view('marketing/contact'
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                $data['dearsoft_writer'] = $this->load->controller('extension/module/dearsoft/init_form', array('form_type' => 'contact'));
            ]]></add>
        </operation>
    </file>

    <file path="admin/view/template/marketing/contact.twig">
        <operation>
            <search trim="true" index="0"><![CDATA[
                {{ footer }}
            ]]></search>
            <add position="before" trim="true" offset="0"><![CDATA[
                {{ dearsoft_writer }}
            ]]></add>
        </operation>
    </file>

    <!-- ============================================================ -->
    <!-- DearSoft Products Image Manager (merged module)               -->
    <!-- ============================================================ -->

<!--for version 3.x view twig modif-->
<file path="admin/view/template/catalog/product_form.twig" error="skip">
  <operation info="view html modif">
  <search regex="true" limit="1"><![CDATA[/(<div[^>]*?id[^>]*?tab-image[^>]*?>).*(<div[^>]*?id[^>]*?tab-reward[^>]*?>)/s]]></search>
  <add position="replace"><![CDATA[
              <div class="tab-pane" id="tab-image">
                <div class="table-responsive">
                <!--DS PRODUCTS IMAGE MANAGER-->
                  <!-- Drop zone -->
                  <div id="drop-files" >
                    <p style="">{{pim_data['lang']['dad_an_image']}}</p>
                    <i>{{pim_data['lang']['select_below']}}</i>
                    <div id="frm" >
                      <input type="file" id="file-input" multiple="multiple" accept="image/jpeg,image/png,image/gif,image/bmp">
                      <label id="byPc" for="file-input" style="">
                        <i class="fa fa-cloud-upload" aria-hidden="true"></i><br>
                        {{pim_data['lang']['upload']}}
                      </label><button type="button" id="bySer">
                        <label>
                          <i class="fa fa-cloud" aria-hidden="true"></i><br>
                          {{pim_data['lang']['server']}}
                        </label>
                      </button><label id="byUrl" for="url-input" >
                        <i class="fa fa-external-link-square" aria-hidden="true"></i><br>
                        {{pim_data['lang']['link']}}
                      </label>
                      <div id="url-input">
                        <span>
                          <input type="text" placeholder ="http://dearsoft.com.bd/image.jpg">
                          <button class="btn btn-info" type="button"  >Ok</button>
                        </span>
                      </div>
                    </div>
                    {% if pim_data['permission'] %}
                    <!-- settings button -->
                    <button id="pim_settings" type="button" class="pim-settings btn btn-default"><i class="fa fa-cog" aria-hidden="true"></i></button>
                    {% endif %}
                  </div>
                  <!-- View zone -->
                  <div id="images" >
                    <div  id="list-view">
                      {% set image_row = 0 %}
                      {% set product_images = [{"image":image,"thumb":thumb,"sort_order": 0}]|merge(product_images) %}
                      {% if image %}
                      {% for key, product_image in product_images %}
                      <div class="image old" {% if (poip_installed ?? false) and ( (poip_global_settings['options_images_edit'] ?? 0) == 1 ) %} data-poip = {{ product_image|json_encode }} {% endif %} >
                        <span class='previewImg'><img src ='{{product_image.thumb}}' /></span>
                        <span class="btm_img">
                          <i class="fa fa-search-plus" data-toggle="tooltip" title="{{pim_data['lang']['zoom']}}" aria-hidden="true"></i><i class="fa fa-times" data-toggle="tooltip" title="{{pim_data['lang']['delete']}}" aria-hidden="true" ></i>
                          <i class="fa fa-del-all fa-flip-horizontal" data-toggle="tooltip" data-original-title="{{pim_data['lang']['delete_all']}}" aria-hidden="true" ></i>
                          <i class="fa fa-magic dearsoft-analyze-img" data-toggle="tooltip" title="Analyze with AI" data-image-url="{{product_image.thumb}}" aria-hidden="true"></i>
                        </span>
                        <input  {% if image_row == 0 %} id="input-image" {% endif %} class = "img-input" value="{{product_image.image}}"  type="hidden" >
                      </div>
                      {% set image_row = key + 1 %}
                      {% endfor %}
                      {% endif %}
                    </div >
                  </div>
                  {{ dearsoft_bgremover|default('')|raw }}
                <!--/DS PRODUCTS IMAGE MANAGER-->
                </div>
              </div>
              $2]]></add>
  </operation>
  <operation info="view scripts">
  <search ><![CDATA[{{ footer }}]]></search>
  <add position="before" ><![CDATA[
   <!--DS PRODUCTS IMAGE MANAGER-->
  {% if poip_global_settings and poip_global_settings['options_images_edit'] %}
  	<script type="text/javascript" src="view/template/extension/ds_products_image_manager/js/poip-support.js"></script>
  {% endif %}
  <script type="text/javascript">pimJson = {{pim_data|json_encode()}}</script>
  <script type="text/javascript" src="view/template/extension/ds_products_image_manager/js/jquery-ui.js"></script>
  <script type="text/javascript" src="view/template/extension/ds_products_image_manager/js/pim.js?v=3.1.2"></script>
   <!--/DS PRODUCTS IMAGE MANAGER-->
  ]]></add>
  </operation>
</file>

<!--for version 2.x view tpl modif-->
<file path="admin/view/template/catalog/product_form.tpl" error="skip">
  <operation info="view html modif">
  <search regex="true" limit="1"><![CDATA[/(<div[^>]*?id[^>]*?tab-image[^>]*?>).*(<div[^>]*?id[^>]*?tab-reward[^>]*?>)/s]]></search>
  <add position="replace"><![CDATA[
              <div class="tab-pane" id="tab-image">
                <div class="table-responsive">
                <!--DS PRODUCTS IMAGE MANAGER-->
                  <!-- Drop zone -->
                  <div id="drop-files" >
                    <p style=""><?php echo $pim_data['lang']['dad_an_image'] ?></p>
                    <i><?php echo $pim_data['lang']['select_below'] ?></i>
                    <div id="frm" >
                      <input type="file" id="file-input" multiple="multiple" accept="image/jpeg,image/png,image/gif,image/bmp">
                      <label id="byPc" for="file-input" style="">
                        <i class="fa fa-cloud-upload" aria-hidden="true"></i><br>
                        <?php echo $pim_data['lang']['upload'] ?>
                      </label><button type="button" id="bySer">
                        <label>
                          <i class="fa fa-cloud" aria-hidden="true"></i><br>
                          <?php echo $pim_data['lang']['server'] ?>
                        </label>
                      </button><label id="byUrl" for="url-input" >
                        <i class="fa fa-external-link-square" aria-hidden="true"></i><br>
                        <?php echo $pim_data['lang']['link'] ?>
                      </label>
                      <div id="url-input">
                        <span>
                          <input type="text" placeholder ="http://dearsoft.com.bd/image.jpg">
                          <button class="btn btn-info" type="button"  >Ok</button>
                        </span>
                      </div>
                    </div>
                    <?php if($pim_data['permission']) : ?>
                    <!-- settings button -->
                    <button id="pim_settings" type="button" class="pim-settings btn btn-default"><i class="fa fa-cog" aria-hidden="true"></i></button>
                    <?php endif; ?>
                  </div>
                  <!-- View zone -->
                  <div id="images" >
                    <div  id="list-view">
                    <?php $image_row = 0; ?>
                    <?php array_unshift($product_images,array("image" =>$image,"thumb" =>$thumb,"sort_order" => 0)); ?>
                    <?php if($image) : ?>
                    <?php foreach ($product_images as $key=> $val) : ?>
                      <div class="image old" <?php if( isset($poip_installed) and $poip_global_settings['options_images_edit'] ) echo 'data-poip ="' . json_encode($product_image) . '"'; ?> >
                        <span class='previewImg'><img src ="<?php echo $val['thumb']; ?>" /></span>
                        <span class="btm_img">
                          <i class="fa fa-search-plus" data-toggle="tooltip" title="<?php echo $pim_data['lang']['zoom'] ?>" aria-hidden="true"></i><i class="fa fa-times" data-toggle="tooltip" title="<?php echo $pim_data['lang']['delete'] ?>" aria-hidden="true" ></i>
                          <i class="fa fa-del-all fa-flip-horizontal" data-toggle="tooltip" data-original-title="<?php echo $pim_data['lang']['delete_all'] ?>" aria-hidden="true" ></i>
                          <i class="fa fa-magic dearsoft-analyze-img" data-toggle="tooltip" title="Analyze with AI" data-image-url="<?php echo $val['thumb']; ?>" aria-hidden="true"></i>
                        </span>
                        <input  <?php echo $image_row == 0 ? 'id="input-image"' : ''; ?> class = "img-input" value="<?php echo $val['image']; ?>"  type="hidden" >
                      </div>
                    <?php $image_row = $key + 1; ?>
                    <?php endforeach; ?>
                    <?php endif; ?>
                    </div >
                  </div>
                  <?php echo isset($dearsoft_bgremover) ? $dearsoft_bgremover : ''; ?>
                <!--/DS PRODUCTS IMAGE MANAGER-->
                </div>
              </div>
              $2]]></add>
   </operation>
  <operation info="view scripts">
  <search ><![CDATA[<?php echo $footer; ?>]]></search>
  <add position="before" ><![CDATA[
  <!--DS PRODUCTS IMAGE MANAGER-->
  	<?php if(isset($poip_global_settings) and $poip_global_settings['options_images_edit']) : ?>
  		<script type="text/javascript" src="view/template/extension/ds_products_image_manager/js/poip-support.js"></script>
	<?php endif ?>
    <script type="text/javascript">pimJson = <?php echo json_encode($pim_data); ?></script>
    <script type="text/javascript" src="view/template/extension/ds_products_image_manager/js/jquery-ui.js"></script>
    <script type="text/javascript" src="view/template/extension/ds_products_image_manager/js/pim.js?v=3.1.2"></script>
  <!--/DS PRODUCTS IMAGE MANAGER-->
   ]]></add>
   </operation>
</file>

<!-- controller php modif -->
<file path="admin/controller/catalog/product.php">
  <operation info="pim main methods" error = "log" >
  <search ><![CDATA[public function add() {]]></search>
  <add position="before" >
     <![CDATA[
    //DS PRODUCTS IMAGE MANAGER->
      public function encodeLinkImage()
      {
        if(!empty($_POST['urls']))
        {
          $url = $_POST['urls'];

          if(@getimagesize($_POST['urls']))
          {
            $prop = preg_replace("#(\.(jpe?g|png|gif|bmp)).*|\W((?<!-|\/))#i", '$1', $url);
            $prop = pathinfo($prop);

            if(isset($prop['extension']))
            {
              $type = $prop['extension'];
              $name = $prop['basename'];
            }
            else
            {
              $type = 'jpeg';
              $name = $prop['basename'] . '.' . $type;
            }

            echo  json_encode(['src'=>'data:image/' . $type . ';base64,'.base64_encode(file_get_contents($url)),'name'=>$name]);
          }
          else
          {
            echo json_encode(['src'=>'','name'=>'']);
          }
        }
      }

      public function productsImageManagerSettings($inner = false, $data = [])
      {

        if(empty($_POST['settings']) && !$inner)
        {
          return false;
        }
        elseif($inner)
        {
          $content = $inner;
        }
        else
        {
          $content = $_POST['settings'];
        }

        $this->load->language('catalog/product');

        $pimLang = (array) $this->language->get('ds_pim');

        $__ = function ($key) use ($pimLang)
        {
          return isset($pimLang[$key]) ? $pimLang[$key] : $key;
        };

        $permission  = $this->user->hasPermission('modify', 'setting/setting');

        $response['content'] = ['max_images'=>20,'image_size'=>2,'image_quality'=>10,'image_name'=>'default','upload_folder'=>'{monufacturer}|products_{year}','remove_images'=>3];

        $dir = rtrim(DIR_APPLICATION . "view/template/extension/ds_products_image_manager/include/");

        // Find image link
        if (!empty($this->request->server['HTTPS']))
        {
          $server = HTTPS_CATALOG;
          $serverAdmin = HTTPS_SERVER;
        }
        else
        {
          $server = HTTP_CATALOG;
          $serverAdmin = HTTP_SERVER;
        }

        //get setting

        if($content === 'modal.html' || $content === 'settings.json')
        {
          if($permission)
          {
            if (is_file($dir . $content))
            {
              $response['content'] = strpos($content, '.json') ? json_decode(file_get_contents($dir . $content),true) : file_get_contents($dir . $content);
              $response['success'] = ' Success: ' .  $__('received_success') . date("Y-m-d - H:i:s");
            }
            else
            {
              $response['error'] = ' Error: ' . $__('file_error') . $dir . $content;
            }
          }
          elseif (!$inner)
          {
            $response['error'] = ' Warning: ' . $__('permission_error');
          }

          if($inner)
          {

            if (is_file($dir . $content))
            {
              $response['content'] = strpos($content, '.json') ? json_decode(file_get_contents($dir . $content),true) : file_get_contents($dir . $content);
            }

            $tokenKey = intval(VERSION) > 2 ? 'user_token' : 'token';

            $response['lang'] = $pimLang;
            $response['permission'] = $permission;
            $response['token'] =  "&$tokenKey=" . $this->session->data[$tokenKey];
            $response['images_path'] =  $server . 'image/';
            $response['wm_bg'] = $serverAdmin . 'view/template/extension/ds_products_image_manager/include/wm_bg.png';
            $response['year']  =  date('Y');
            $response['month'] =  date('m');
            $response['day']   =  date('d');
            $response['product_id']  =  !isset($this->request->get['product_id']) ? 0 : $this->request->get['product_id'];

            return $response;
          }

          echo json_encode($response);
          return;
        }



        //save setting and watermark
        if ($content && !$inner && $permission)
        {
          parse_str(html_entity_decode($content), $set);

          if(isset($set['max_images'],$set['image_size'],$set['image_quality'],$set['image_name'],$set['upload_folder'],$set['remove_images']))
          {
            empty($set['max_images']) ? $set['max_images'] = 1 : null;

            if (!isset($set['watermark'],$set['watermark_status']))
            {
              $set['watermark_status'] = false;
            }
            //watermark image upload
            else if(!strpos($set['watermark']['src'], 'watermark.png'))
            {
              $src = $set['watermark']['src'];

              $watermark = $server . 'image/watermark.png' . '?v=' . time();

              if(strpos($src, 'data:image/png;base64') === 0)
              {
                $src = base64_decode(str_replace('data:image/png;base64,', '', $src));

                file_put_contents(DIR_IMAGE . 'watermark.png', $src);
              }
              elseif(@getimagesize($src))
              {
                file_put_contents(DIR_IMAGE . 'watermark.png', file_get_contents($src));
              }
              else
              {
                $watermark = '';
              }


              $set['watermark']['src'] = $watermark;
            }

            if(is_dir($dir))
            {
              //file write
              $settingsFile = fopen($dir . 'settings.json','w');

              fwrite($settingsFile,json_encode($set));

              fclose($settingsFile);

              $response['content'] = $set;
              $response['success'] = ' Success: ' . $__('save_success') . ' ' . date("Y-m-d - H:i:s");
            }
            else
            {
              $response['error'] = ' Error: ' . $__('nodir_error') . ' (' . $dir . ')';
            }

          }
          else
          {
            $response['error'] = ' Error: ' . $__('save_error');
          }

          echo json_encode($response);

        }
      }


      public function uploadNewImage()
      {
        if(strtolower($_SERVER['REQUEST_METHOD'])=='post')
        {

          if(!empty($_POST["dels"]))
          {
            $this->delProductImage($_POST["dels"]);
          }

          if(!empty($_FILES))
          {
            $dir = rtrim(DIR_IMAGE.$_POST["catalog"]);

            if(!is_dir($dir))
            {
              mkdir($dir,0755,true);
            }

            foreach($_FILES as $file)
            {
              move_uploaded_file($file["tmp_name"],$dir.$file["name"]);
            }
          }
        }
      }

      public function imageExist()
      {
        if(isset($_POST))
        {
          header('Content-Type: application/json');
          $imgpath=rtrim($_POST["name"]);
          $namearr=preg_split('/\.(?=[^.]*$)/i',$imgpath);
          $nIdx=0;

          do
          {
            $filepath=$nIdx!=0 ? $namearr[0].'-'.$nIdx.'.'.$namearr[1] : $imgpath;

            if(!is_file(DIR_IMAGE.$filepath))
            {
              echo json_encode(array("newname"=>preg_replace("/\S*\/(?=\S*$)/i","",$filepath),"status"=>$nIdx));

              break;
            }
          }

          while(++$nIdx);
        }

        die();
      }

      public function delProductImage($delInfo)
      {
        $this->load->model('catalog/product');
        if(!is_array($delInfo))
        {
          $unlikUrls=array();
          $parsedProductImage = $this->model_catalog_product->parseProductImage($delInfo);

          foreach($parsedProductImage as $key=>$value)
          {
            if(isset($value["description"]))
            {
              $search = preg_replace('/\S*(?=(\\\\)\/\S*\/\S*\/$)/i',"",preg_replace("/\\\|\//","\/",DIR_IMAGE));

              preg_match_all("/(?<=".$search.")\S*(?=&quot;)/im",$value["description"],$newUrls);
              $unlikUrls=array_merge($newUrls[0],$unlikUrls);
            }
            else
            {
              $unlikUrls[]=$value["image"];
            }
          }

          $delInfo=array('id'=>$delInfo,'value'=>array_unique($unlikUrls));
        }

        foreach($delInfo["value"] as $value)
        {
          $imgIs=$this->model_catalog_product->getUnlikUrls($delInfo["id"],$value)->rows["0"]["result"];

          if($imgIs==0  &&  $value  &&  file_exists(DIR_IMAGE.$value))
          {
            unlink(DIR_IMAGE.$value);
          }
        }
      }
    //<-DS PRODUCTS IMAGE MANAGER
  ]]>
  </add>
  </operation>

  <operation info="thumb images size modif">
        <search regex="true"  ><![CDATA[/resize\((.*?), 100, 100\)/]]></search>
        <add position="replace" ><![CDATA[resize($1, 200, 200)/*DS PRODUCTS IMAGE MANAGER-> replace 100x100 to 200x200*/]]></add>
  </operation>

  <operation info="on product del remove images status">
   <search ><![CDATA[public function delete() {]]></search>
  <add position="after"><![CDATA[
      //DS PRODUCTS IMAGE MANAGER->
      $settings = $this->productsImageManagerSettings('settings.json');
      //<-DS PRODUCTS IMAGE MANAGER
    ]]></add>
  </operation>

  <operation info="on product del remove images method call">
   <search ><![CDATA[$this->model_catalog_product->deleteProduct($product_id);]]></search>
  <add position="before"><![CDATA[
          //DS PRODUCTS IMAGE MANAGER->
          if($settings['content']['remove_images'] == '1' || $settings['content']['remove_images'] == '3')
          {
            $this->delProductImage($product_id);
          }
          //<-DS PRODUCTS IMAGE MANAGER
    ]]></add>
  </operation>

  <operation info="view datas">
              <search ><![CDATA[protected function getForm() {]]></search>
  <add position="after"><![CDATA[
      //DS PRODUCTS IMAGE MANAGER->
      $this->document->addStyle('view/template/extension/ds_products_image_manager/css/pim.css?v=3.0.8');
      $data['pim_data'] = $this->productsImageManagerSettings('settings.json');
      //<-DS PRODUCTS IMAGE MANAGER
  ]]></add>
  </operation>
</file>

<!-- model.php modif -->
<file path="admin/model/catalog/product.php">
  <operation info="model methods">
  <search><![CDATA[public function deleteProduct($product_id)]]></search>
  <add position="before"><![CDATA[
  //DS PRODUCTS IMAGE MANAGER ->
    public function getUnlikUrls($id,$value)
    {
      $query=$this->db->query("SELECT EXISTS(
      SELECT DISTINCT image FROM ".DB_PREFIX."product_image WHERE image LIKE '%$value%' AND product_id!=$id
      UNION SELECT DISTINCT image FROM ".DB_PREFIX."product WHERE image LIKE '%$value%' AND product_id!=$id
      UNION SELECT DISTINCT image FROM ".DB_PREFIX."manufacturer WHERE image LIKE '%$value%'
      UNION SELECT DISTINCT image FROM ".DB_PREFIX."banner_image WHERE image LIKE '%$value%'
      UNION SELECT DISTINCT image FROM ".DB_PREFIX."category WHERE image LIKE '%$value%'
      UNION SELECT DISTINCT image FROM ".DB_PREFIX."option_value WHERE image LIKE '%$value%'
      UNION SELECT DISTINCT description FROM ".DB_PREFIX."product_description WHERE description LIKE '%$value%' AND product_id!=$id
      UNION SELECT DISTINCT description FROM ".DB_PREFIX."information_description WHERE description LIKE '%$value%'
      UNION SELECT DISTINCT description FROM ".DB_PREFIX."category_description WHERE description LIKE '%$value%') AS result"); return $query;
    }
    public function parseProductImage($id)
    {
      $query=$this->db->query("SELECT DISTINCT image FROM ".DB_PREFIX."product_image WHERE product_id=$id
      UNION SELECT DISTINCT image FROM ".DB_PREFIX."product WHERE product_id=$id");
      $query_d=$this->db->query("SELECT DISTINCT description FROM ".DB_PREFIX."product_description WHERE product_id=$id");
      $query->rows[]=$query_d->rows[0]; return $query->rows;
    }
  //<-DS PRODUCTS IMAGE MANAGER
  ]]></add>
  </operation>
</file>


<!-- language add -->
<file path="admin/language/en*/catalog/product.php">
  <operation info="language">
  <search ><![CDATA[<?php]]></search>
  <add position="after"><![CDATA[
  //DS PRODUCTS IMAGE MANAGER ->
    //pim drop zone lang
    $_['ds_pim']['u_up_max']    = 'Upload a maximum of';
    $_['ds_pim']['images']        = 'images';
    $_['ds_pim']['dad_an_image']  = 'Drag & Drop an image';
    $_['ds_pim']['image_damaged'] = 'This image is damaged!';
    $_['ds_pim']['select_below']  = 'or select an option below';
    $_['ds_pim']['zoom']          = 'Zoom';
    $_['ds_pim']['upload']        = 'Upload';
    $_['ds_pim']['link']          = 'Link';
    $_['ds_pim']['server']        = 'Server';
    $_['ds_pim']['loading']       = 'Loading ';
    $_['ds_pim']['exist']         = 'Image already exists!';
    $_['ds_pim']['keep_old']      = 'Take old';
    $_['ds_pim']['keep_both']     = 'Keep both';
    $_['ds_pim']['replace']       = 'Replace';
    $_['ds_pim']['delete']        = 'Remove';
    $_['ds_pim']['delete_all']    = 'Remove next all';
    $_['ds_pim']['mAdd']          = 'Multiple Add';

    //pim modal lang
    $_['ds_pim']['pim']             = 'Products image manager';
    $_['ds_pim']['settings']        = 'Settings';
    $_['ds_pim']['max_images']      = 'Max images';
    $_['ds_pim']['max_image_size']  = 'Reduce size';
    $_['ds_pim']['resolution']      = 'Resolution';
    $_['ds_pim']['image_quality']   = 'Reduce quality';
    $_['ds_pim']['remove_images']   = 'Remove images';
    $_['ds_pim']['when_should']     = 'When should remove images from the server';
    $_['ds_pim']['do_not']          = 'Do not';
    $_['ds_pim']['when_pro_is_del'] = 'When product is deleted';
    $_['ds_pim']['when_rem_4_pro']  = 'When removed from product';
    $_['ds_pim']['anyway']          = 'Anyway';
    $_['ds_pim']['image_name']      = 'Image name';
    $_['ds_pim']['default']         = 'Default';
    $_['ds_pim']['random']          = 'Random';
    $_['ds_pim']['translit']        = 'Translit';
    $_['ds_pim']['example']         = 'Example';
    $_['ds_pim']['upload_folder']   = 'Upload folder';
    $_['ds_pim']['ask_me']          = 'Ask me';
    $_['ds_pim']['top_left']        = 'Top left';
    $_['ds_pim']['bottom_left']     = 'Bottom left';
    $_['ds_pim']['top_right']       = 'Top right';
    $_['ds_pim']['bottom_right']    = 'Bottom right';
    $_['ds_pim']['center']          = 'Center';
    $_['ds_pim']['multiple']        = 'Multiple';
    $_['ds_pim']['position']        = 'Position';
    $_['ds_pim']['text_or_url']     = 'Insert an image url or a text';
    $_['ds_pim']['size']            = 'Size';
    $_['ds_pim']['opacity']         = 'Opacity';
    $_['ds_pim']['dimensions']      = 'Dimensions';
    $_['ds_pim']['transmittance']   = 'Transmittance';
    $_['ds_pim']['watermark']       = 'Watermark';
    $_['ds_pim']['watermark_not_found']= 'Watermark image not found: Please try another image link or use any text!';

    //text  success
    $_['ds_pim']['save_success']    = 'You have modified settings!';
    $_['ds_pim']['received_success']= 'Content received!';

    //text error
    $_['ds_pim']['nodir_error']     = 'Undefined directory';
    $_['ds_pim']['save_error']      = 'You did not modify the DS PIM settings!';
    $_['ds_pim']['file_error']      = 'Undefined file';
    $_['ds_pim']['permission_error']= 'You do not have permission to modify the DS PIM settings!';
  //<-DS PRODUCTS IMAGE MANAGER
  ]]></add>
  </operation>
</file>

</modification>
