<?php
/** @noinspection UnterminatedStatementJS */
/** @noinspection UnreachableCodeJS */
/** @noinspection BadExpressionStatementJS */
/** @noinspection SqlResolve */
/** @noinspection SqlNoDataSourceInspection */


/**
 * Magic Method Support
 *
 * id_user -> ид текущего юзера
 * id_author -> ид автора записи
 * id_post -> ид записи
 *
 * example like::init()->photo(['id_user' => -1, 'id_author' => -1, 'id_post' => -1]);
 *
 * @method void photo(array $args = ['id_user' => -1, 'id_author' => -1, 'id_post' => -1])
 * @method void arbour(array $args = ['id_user' => -1, 'id_author' => -1, 'id_post' => -1])
 * @method void photocom(array $args = ['id_user' => -1, 'id_author' => -1, 'id_post' => -1])
 */
class like
{
    const PHOTO = 'photo';
    const ARBOUR = 'arbour';
    const PHOTOCOM = 'photocom';
    /**
     * @var like
     */
    private static $static;

    private $likeType = [];
    private $cacheSql = [];

    private function __construct()
    {
        $this->likeType['photo'] = true;
        $this->likeType['arbour'] = true;
        $this->likeType['photocom'] = true;
    }

    private function filterParams(array $args)
    {
        $paramsFilter = [
            'filter' => FILTER_CALLBACK,
            'options' => function ($args) {
                return (int)$args;
            }
        ];

        $args = filter_var_array($args, [
            'id_user' => $paramsFilter,
            'id_author' => $paramsFilter,
            'id_post' => $paramsFilter,
        ], false);

        if (!isset($args['id_user']) ||
            !isset($args['id_author']) ||
            !isset($args['id_post'])) {
            return false;
        }

        return $args;
    }

    /**
     * @return like
     */
    public static function init()
    {
        if ((self::$static instanceof self) === false) {
            self::$static = new static();
        }
        return self::$static;
    }

    public function getLikeType($type)
    {
        if (isset($this->likeType[$type])) {
            return $type;
        }
        return false;
    }

    /**
     * @param $name
     * @param $args
     * @return bool|int
     */
    public function __call($name, $args)
    {
        $args = $this->filterParams(array_shift($args));

        if ($args === false) return false;

        $type = $this->getLikeType($name);
        if ($type === false) return false;

        if ((int)DB::$pdo->querySingle(
                'SELECT COUNT(id) FROM `like` 
                      WHERE `id_post` = :id_post AND `id_user` = :id_user 
                        AND `id_author` = :id_author AND `type` = :type LIMIT 1',
                [
                    ':id_post' => $args['id_post'],
                    ':id_user' => $args['id_user'],
                    ':id_author' => $args['id_author'],
                    ':type' => $type
                ]
            ) > 0) {
            DB::$pdo->query(
                'DELETE FROM `like` 
                      WHERE `id_post` = :id_post AND `id_user` = :id_user 
                        AND `id_author` = :id_author AND `type` = :type',
                [
                    ':id_post' => $args['id_post'],
                    ':id_user' => $args['id_user'],
                    ':id_author' => $args['id_author'],
                    ':type' => $type
                ]);
            notif::init()->deleteNotif('like_' . $type, [
               'id_author' => $args['id_author'],
               'id_user' => $args['id_user'],
               'id_post' => $args['id_post'],
            ]);
            return 0;
        } else {

            DB::$pdo->query(
                'INSERT INTO `like` 
                      (`id_post`, `id_user`, `id_author`, `type`, `time`)
                      VALUES (:id_post, :id_user, :id_author, :type, :time)'
                , [
                ':id_post' => $args['id_post'],
                ':id_user' => $args['id_user'],
                ':id_author' => $args['id_author'],
                ':type' => $type,
                ':time' => time(),
            ]);
            notif::init()->{'like_' . $type}([
                'id_author' => $args['id_author'],
                'id_user' => $args['id_user'],
                'id_post' => $args['id_post'],
            ]);
        }
        return 1;
    }

    public function createButton($type, array $args)
    {
        $args = $this->filterParams($args);

        if ($args === false) return '';

        $type = $this->getLikeType($type);
        if ($type === false) return '';

        $onClick = '';
        $isLike = '';


        if (!isset($this->cacheSql[$type])) {
            $this->cacheSql[$type] = [
                'count' => DB::$pdo->prepare('SELECT COUNT(id) FROM `like` WHERE `id_post` = :p AND `id_author` = :a LIMIT 1'),
                'is_like' => DB::$pdo->prepare('SELECT COUNT(id) FROM `like` WHERE `id_post` = :p AND `id_author` = :a AND `id_user` = :u  LIMIT 1'),
            ];
        }

        /** @var PDOStatement $count */
        $count = $this->cacheSql[$type]['count'];
        $count->execute([
            ':p' => $args['id_post'],
            ':a' => $args['id_author']
        ]);
        $count = $count->fetchColumn(0);

        if ((int)$args['id_user'] > 0 && (int)$args['id_post'] > 0 && (int)$args['id_author'] > 0) {
            if ($count > 0) {
                /** @var PDOStatement $isLike */
                $isLike = $this->cacheSql[$type]['is_like'];
                $isLike->execute([
                    ':p' => $args['id_post'],
                    ':a' => $args['id_author'],
                    ':u' => $args['id_user']
                ]);
                $isLike = $isLike->fetchColumn(0) > 0 ? ' active' : '';
            }

            $onClick = 'onclick="return Like.click(' . $args['id_post'] . ', ' . $args['id_author'] . ', this)"';
        }

        $count = $count > 0 ? $count : '';

        return <<<HTML
<div class="wi-like-button" data-like-post="{$args['id_post']}">
    <span class="like-post$isLike" {$onClick}>
        <span class="like-icon" data-type="$type">
            <div class="heart-animation-1"></div>
            <div class="heart-animation-2"></div>
        </span>
        <b class="like-count">$count</b>
    </span>
</div>
HTML;

    }
}