<?php
/**
* 2007-2020 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@buy-addons.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author    Buy-Addons <contact@buy-addons.com>
*  @copyright 2007-2020 PrestaShop SA
*  @license   http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
* @since 1.6
*/

class AdminGenerateAltTextController extends ModuleAdminController
{
    public function run()
    {
        $id_employee = (int) $this->context->employee->id;
        $ajax_token = Tools::getValue('ajax_token');
        $module_token = $this->module->getAjaxToken();
        if (($ajax_token != $module_token) || empty($id_employee)) {
            echo $this->module->l('You do not have permission to access it.');
            die;
        }
        // process
        $response = array(
                'msg' => array(),
                'finished' => 0,
            );
        $name = $this->module->name;
        $from = (int) Configuration::getGlobalValue($name.'AdminGenerateAltText_Queue');
        $general = new BASmartSeoAltTagsGeneral();
        // start
        $msg = array();
        $products = $general->findProducts($from);

        $count = count($products);
        if ($count == 0) {
            $msg[] = $this->module->l('All of Alt Text of Product Images are done.');
            $response['finished'] = 1;
            Configuration::updateGlobalValue($name.'AdminGenerateAltText_Queue', null);
            Configuration::updateGlobalValue($name.'_regenerateALL', 0);
        } else {
            foreach ($products as $p) {
                $id_product = (int) $p['id_product'];
                $general->regenerateAltTag($id_product);
            }
            $total = $from + $count;
            Configuration::updateGlobalValue($name.'AdminGenerateAltText_Queue', $total);
            $msg[] = $this->module->l('Products are generated: ').number_format($total);
        }
        $response['msg'] = $msg;
        echo json_encode($response);
        die;
    }
}
