<?php
/**
* 2023 Anvanto
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
*
*  @abwhor    Anvanto <anvantoco@gmail.com>
*  @copyright 2023 Anvanto
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*/

class anBlogLikes extends ObjectModel
{
    
    public $id_like;
 
    public $id;

    public $id_customer_guest;

    public $id_post;
    public $id_shop;
    public $date_upd;

    public static $definition = [
        'table' => 'anblog_likes',
        'primary' => 'id_like',
        'multilang' => false,
        'fields' => [
            'id_customer_guest' => ['type' =>self::TYPE_INT ],
            'id_post' => ['type' =>self::TYPE_INT ],
            'id_shop' => ['type' =>self::TYPE_INT ],

            'date_upd' => ['type' => self::TYPE_DATE, 'validate' => 'isDate'],
        ],
    ];

    public static function getIdLike($idCustomerGuest, $idPost)
    {
		
        if (!$idCustomerGuest) {
            return false;
        }
          
        $sql = '            
            SELECT `id_like`
            FROM `' . _DB_PREFIX_ . 'anblog_likes`
            WHERE `id_customer_guest` = ' . (int)$idCustomerGuest . '
            AND `id_post` = ' . $idPost . '
            AND `id_shop` = ' . (int) Context::getContext()->shop->id;
        ;	

        return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql);                    
	}



    public static function addLike($idCustomerGuest, $idPost)
    {
        $objLikes = new anBlogLikes;
            
        $objLikes->id_customer_guest = $idCustomerGuest;
        $objLikes->id_post = $idPost;
        $objLikes->id_shop = (int) Context::getContext()->shop->id;
        $objLikes->save();	

        Db::getInstance(_PS_USE_SQL_SLAVE_)->execute('
            UPDATE '._DB_PREFIX_.'anblog_blog SET likes = likes + 1 WHERE id_anblog_blog = '. $idPost .'
        ');

    }
    public static function deleteLike($idLike, $idPost)
    {
        $objLikes = new anBlogLikes($idLike);
        $objLikes->delete();

        Db::getInstance(_PS_USE_SQL_SLAVE_)->execute('
            UPDATE '._DB_PREFIX_.'anblog_blog SET likes = likes - 1 WHERE id_anblog_blog = '. $idPost .'
        ');
    }
    
    public static function getCountLikes($idPost)
    {
        $objLikes = new AnblogBlog($idPost);
        return $objLikes->likes; 
    }

}
