<?php
/**
* 2024 Anvanto
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
*
*  @author    Anvanto <anvantoco@gmail.com>
*  @copyright 2024 Anvanto
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*/

if (!defined('_PS_VERSION_')) {
    exit;
}

use PrestaShop\PrestaShop\Core\Domain\Product\Query\SearchProducts;

class AdminAnsizeguideAjaxController extends ModuleAdminController
{
    public function initContent()
    {
        $result = [];
        if (Tools::isSubmit('action')) {
            $actionName = Tools::getValue('action', '') . 'Action';
            if (method_exists($this, $actionName)) {
                $result = $this->$actionName();
            }
        }

        die(json_encode($result));
    }    
    
    public function searchProductsAction()
    {    
        //    $defaultCurrencyId = (int) $this->get('prestashop.adapter.legacy.configuration')->get('PS_CURRENCY_DEFAULT');
        $defaultCurrencyId = Configuration::get('PS_CURRENCY_DEFAULT');

        //$searchPhrase = $request->query->get('search_phrase');
        $searchPhrase = Tools::getValue('q');

        if (!$searchPhrase){
            return [];
        }

        $foundProducts = Product::searchByName((int) $this->context->language->id, pSQL($searchPhrase));


        $products = [];
        if (is_array($foundProducts)){
            foreach ($foundProducts as $fProduct){

                $productObj = new Product($fProduct['id_product'], false, $this->context->language->id);
                $coverId = Product::getCover($fProduct['id_product']);
                
                $coverPhoto = '';
                if (isset($coverId['id_image'])){
                    $coverPhoto = Context::getContext()->link->getImageLink(
                        $productObj->link_rewrite, 
                        $coverId['id_image'], 
                        ImageType::getFormattedName('cart')
                    );
                }

                $products[] = [
                    'id' => $fProduct['id_product'],
                    'name' => $fProduct['name'],
                    'reference' => $fProduct['reference'],
                    'cover' => $coverPhoto
                ];
            }     
        }   

        return $products;
    }
    
    public function  updatePositionsTabsAction()
    {
        $status = false;
        $position = 1;
        $positions = array_map('intval', (array)Tools::getValue('an_productextratabs'));
        
        foreach ($positions as $pos){
            $sql = 'UPDATE `' . _DB_PREFIX_ . 'an_productextratabs` SET position="'.(int)$position.'" WHERE id_tab="'.(int)$pos.'" ';
            Db::getInstance(_PS_USE_SQL_SLAVE_)->execute($sql);
            $position++;
        }

        $status = true;
        
        return ['status' => 'success', 'message' => $this->l('Update successful')];
    }    
}
