<?php
/**
 * 2022 Anvanto
 *
 * NOTICE OF LICENSE
 *
 * This file is not open source! Each license that you purchased is only available for 1 wesite only.
 * If you want to use this file on more websites (or projects), you need to purchase additional licenses. 
 * You are not allowed to redistribute, resell, lease, license, sub-license or offer our resources to any third party.
 *
 *  @author Anvanto <anvantoco@gmail.com>
 *  @copyright  2022 Anvanto
 *  @license    Valid for 1 website (or project) for each purchase of license
 *  International Registered Trademark & Property of Anvanto
 */

include_once _PS_MODULE_DIR_.'anblog/loader.php';

class anbloglikesModuleFrontController extends ModuleFrontController
{    
    public function initContent()
    {
        $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 toggleLikeAction()
    {
        $return = [
            'status' => '',
            'countLikes' => '',
        ];  

        $idPost = (int) Tools::getValue('id_post');

        if (Context::getContext()->customer->isLogged()) {
            $idCustomerGuest = (int) Context::getContext()->customer->id;
        } else {
            $idCustomerGuest = $this->module->getIdGuest();
        }
		

		$idLike = anBlogLikes::getIdLike($idCustomerGuest, $idPost);
		

		
		if (!$idLike) {
            anBlogLikes::addLike($idCustomerGuest, $idPost);
            $return['status'] = 1; 
		} else {
            anBlogLikes::deleteLike($idLike, $idPost);
            $return['status'] = 0; 
		}

        $return['countLikes'] = anBlogLikes::getCountLikes($idPost);
		
        $this->ajaxDie(json_encode($return));
    }    
}