<?php

/**
 * Created by PhpStorm.
 * User: Valeriy Shikuta aka Str@nnik
 * Date: 26.02.2016
 * Time: 14:46
 * File: likes.php
 * ICQ: 609-745-227
 * E-mail: valera_shikuta@mail.ru
 */

defined('_IN_JOHNCMS') or die('Restricted access');

class Likes
{
    private $likes_table = false;
    private $sub_id = false;
    private $user_id = false;
    private $url;

    function __construct($arg = array())
    {
        $this->likes_table = $arg['likes_table'];
        $this->sub_id = $arg['sub_id'];
        $this->user_id = core::$user_id;
        $this->url = $arg['url'];
        $this->likes_form();
    }

    function likes_form()
    {
        global $do;
        switch ($do) {
            case 'like':
                $is_like = mysql_result(mysql_query("SELECT COUNT(*) FROM $this->likes_table WHERE `sub_id` = $this->sub_id AND `user_id` = '$this->user_id'"), 0);
                if ($is_like) {
                    echo functions::display_error('Вы уже лайкали за данный прогноз', '<a href="' . $this->url . '">Назад</a>');
                }
                else {
                    mysql_query("INSERT INTO $this->likes_table SET
                      `sub_id` = $this->sub_id,
                      `user_id` = $this->user_id,
                      `like` = 1");
                    header('location: ' . $_SERVER['HTTP_REFERER']);
                }
                break;

            case 'dislike':
                $is_like = mysql_result(mysql_query("SELECT COUNT(*) FROM $this->likes_table WHERE `sub_id` = $this->sub_id AND `user_id` = '$this->user_id'"), 0);
                if ($is_like) {
                    echo functions::display_error('Вы уже лайкали за данный прогноз', '<a href="' . $this->url . '">Назад</a>');
                }
                else {
                    mysql_query("INSERT INTO $this->likes_table SET
                      `sub_id` = $this->sub_id,
                      `user_id` = $this->user_id,
                      `dislike` = 1");
                    header('location: ' . $_SERVER['HTTP_REFERER']);
                }
                break;

            default:
                $total_likes = mysql_result(mysql_query("SELECT COUNT(`id`) FROM $this->likes_table WHERE `sub_id` = $this->sub_id AND `like` = '1'"), 0);
                $total_dislikes = mysql_result(mysql_query("SELECT COUNT(`id`) FROM $this->likes_table WHERE `sub_id` = $this->sub_id AND `dislike` = '1'"), 0);
                echo '<div class="gmenu"><a href="' . $this->url . '&amp;do=like">' . functions::image('like.png') . '</a>(' . $total_likes . ')&nbsp;<a href="' . $this->url . '&amp;do=dislike">' . functions::image('dislike.png') . '</a>(' . $total_dislikes . ')</div>';

        }
    }
}