<?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;
}

require_once _PS_MODULE_DIR_ . 'an_homeproducts/classes/anHomeProductsBlocks.php';

class an_homeproductsajaxModuleFrontController extends ModuleFrontController
{
    public function initContent()
    { 
        $this->assignGeneralPurposeVariables();
        
        $result = [];
        if (Tools::isSubmit('action')) {

            if (Tools::getValue('token') != Tools::getToken(false)){
                Tools::redirect('index.php?controller=404');
            }

            $actionName = Tools::getValue('action', '') . 'Action';
            if (method_exists($this, $actionName)) {
                $result = $this->$actionName();
            }
        }

        die(json_encode($result));
    }    
    
    public function getProductsAction()
    {
        $return = [];

        $config = [
            'view_type' => Configuration::get('an_hp_view_type'),
            'show_sort' => Configuration::get('an_hp_show_sort'),
            'slider' => Configuration::get('an_hp_slider'),

            'slider_nav' => Configuration::get('an_hp_slider_nav'),
            'slider_dots' => Configuration::get('an_hp_slider_dots'),
            'slider_loop' => Configuration::get('an_hp_slider_loop'),

            'show_load_more' => Configuration::get(an_homeproducts::PREFIX . 'show_load_more'),
            'title' => Configuration::get('an_hp_title', $this->context->language->id),
            'text' => Configuration::get('an_hp_text', $this->context->language->id),
        ];        

        $blockId = Tools::getValue('blockId');
        $type = Tools::getValue('type');

        $params = [
            'page' => (int) Tools::getValue('page'),
            'sort' => Tools::getValue('sort'),
            'idCategory' => (int) Tools::getValue('idCategory'),
        ];

        $blockObj = new anHomeProductsBlocks($blockId, $this->context->language->id);
        $blockObj->getData($params);
        $block = (array)$blockObj;

        $templateFile = 'ajax-products.tpl';
        if ($type == 'tab'){
            $templateFile = 'content.tpl'; 
            $this->context->smarty->assign('block', $block);
        }

        $this->context->smarty->assign('widget', [
            'banners' => anHomeProductsBanners::getBanners(),
            'config' => $config
        ]);
        $this->context->smarty->assign('products', $block['products']);


        $return['productsNextPage'] = $block['productsNextPage'];
        $return['products'] = $this->module->display($this->module->name, $templateFile);

        die(json_encode($return));
    }    

}