<?php
/**
* 2023 Anvanto
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
*
*  @author    Anvanto <anvantoco@gmail.com>
*  @copyright 2023 Anvanto
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*/

use PrestaShop\PrestaShop\Core\Domain\Product\Query\SearchProducts;

class AdminProducttabsAjaxController 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');

        //$searchPhrase = $request->query->get('search_phrase');
        $searchPhrase = Tools::getValue('q');

        if (!$searchPhrase){
            return [];
        }

        $foundProducts = Product::searchByName((int) $this->context->language->id, pSQL($searchPhrase));

        if (!$foundProducts){
            return [];
        }

        $products = [];
        foreach ($foundProducts as $fProduct){
            $products[] = [
                'id' => $fProduct['id_product'],
                'name' => $fProduct['name']
            ];
        }        

        return $products;
    }

    public function  saveTabsAction()
    {
        $languages = Language::getLanguages(false);

        $id_product = Tools::getValue('id_product');
        $idtab = Tools::getValue('idtab');

        $content_active = (bool)Tools::getValue('content_active');
        $content_combinations = (bool)Tools::getValue('content_combinations');
        $content_contactform = (bool)Tools::getValue('content_contactform');

        $content_name = [];
        $content_content = [];
        foreach ($languages  as $language){
            $content_name[$language['id_lang']] = Tools::getValue('content_name_' . $language['id_lang']);
            $content_content[$language['id_lang']] = trim(Tools::getValue('content_content_' . $language['id_lang']));
        }

        $idContent = anProductTabsTplContent::getIdByProductTemplate($id_product, $idtab);

        $contentObj = new anProductTabsTplContent($idContent);
        $contentObj->content_active = $content_active;
        $contentObj->content_combinations = $content_combinations;
        $contentObj->content_contactform = $content_contactform;
        $contentObj->id_product = $id_product;
        $contentObj->id_template = $idtab;
        $contentObj->content_content = $content_content;
        $contentObj->content_name = $content_name;
        $contentObj->save();

        
        return ['status' => 'success', 'message' => $this->l('Successful')];
    }

    public function  deleteTabAction()
    {
        $idtab = Tools::getValue('idtab');
        if ($idtab){
            $anTab = new anProductTabs($idtab);
            $anTab->delete();
        }
        
        return ['status' => 'success', 'message' => $this->l('Successful deletion')];
    }
    
    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 idtab="'.(int)$pos.'" ';
			Db::getInstance(_PS_USE_SQL_SLAVE_)->execute($sql);
			$position++;
		}

		$status = true;
        
        return ['status' => 'success', 'message' => $this->l('Update successful')];
    }  
    
    public function  updatePositionsLabelsAction()
    {
        $status = false;
		$position = 1;
        $positions = array_map('intval', (array)Tools::getValue('an_productextratabs_labels'));
		
		foreach ($positions as $pos){
			$sql = 'UPDATE `' . _DB_PREFIX_ . 'an_productextratabs_labels` SET position="'.(int)$position.'" WHERE id_label="'.(int)$pos.'" ';
			Db::getInstance(_PS_USE_SQL_SLAVE_)->execute($sql);
			$position++;
		}

		$status = true;
        
        return ['status' => 'success', 'message' => $this->l('Update successful')];
    }  
}
