<?php
namespace Commentics;

class ManageUsersModel extends Model
{
    public function getUsers($data, $count = false)
    {
        if ($count) {
            $sql = "SELECT COUNT(`u`.`id`)";
        } else {
            $sql = "SELECT `u`.*,";

            $sql .= " (SELECT COUNT(`id`) FROM `" . CMTX_DB_PREFIX . "subscriptions` `s` WHERE `s`.`user_id` = `u`.`id`) AS `subscriptions`,";

            $sql .= " (SELECT COUNT(`id`) FROM `" . CMTX_DB_PREFIX . "comments` `c` WHERE `c`.`user_id` = `u`.`id`) AS `comments`";
        }

        $sql .= " FROM `" . CMTX_DB_PREFIX . "users` `u`";

        $sql .= " WHERE 1 = 1";

        if ($data['filter_id']) {
            $sql .= " AND `u`.`id` = '" . (int) $data['filter_id'] . "'";
        }

        if ($data['filter_name']) {
            $sql .= " AND `u`.`name` LIKE '%" . $this->db->escape($data['filter_name']) . "%'";
        }

        if ($data['filter_email']) {
            $sql .= " AND `u`.`email` LIKE '%" . $this->db->escape($data['filter_email']) . "%'";
        }

        if ($data['filter_avatar_approved'] == '1') {
            $sql .= " AND `u`.`avatar_pending_id` = '0'";
        } else if ($data['filter_avatar_approved'] == '0') {
            $sql .= " AND `u`.`avatar_pending_id` > '0'";
        }

        if ($data['filter_moderate']) {
            $sql .= " AND `u`.`moderate` = '" . $this->db->escape($data['filter_moderate']) . "'";
        }

        if ($data['filter_date']) {
            $sql .= " AND `u`.`date_added` LIKE '%" . $this->db->escape($data['filter_date']) . "%'";
        }

        if ($data['group_by']) {
            $sql .= " GROUP BY " . $this->db->backticks($data['group_by']);
        } else {
            $sql .= " GROUP BY `u`.`id`";
        }

        if (!$count) {
            if ($data['sort'] == 'avatar_approved') {
                $data['sort'] = 'avatar_pending_id';
            }

            $sql .= " ORDER BY " . $this->db->backticks($data['sort']);

            if ($data['order'] == 'asc') {
                $sql .= " ASC";
            } else {
                $sql .= " DESC";
            }

            $sql .= " LIMIT " . (int) $data['start'] . ", " . (int) $data['limit'];
        }

        $query = $this->db->query($sql);

        if ($count) {
            return $this->db->numRows($query);
        } else {
            return $this->db->rows($query);
        }
    }

    public function sortUrl()
    {
        $url = '';

        if (isset($this->request->get['page'])) {
            $url .= '&page=' . $this->request->get['page'];
        }

        if (isset($this->request->get['filter_name'])) {
            $url .= '&filter_name=' . $this->url->encode($this->security->decode($this->request->get['filter_name']));
        }

        if (isset($this->request->get['filter_email'])) {
            $url .= '&filter_email=' . $this->url->encode($this->security->decode($this->request->get['filter_email']));
        }

        if (isset($this->request->get['filter_avatar_approved'])) {
            $url .= '&filter_avatar_approved=' . $this->url->encode($this->security->decode($this->request->get['filter_avatar_approved']));
        }

        if (isset($this->request->get['filter_moderate'])) {
            $url .= '&filter_moderate=' . $this->url->encode($this->security->decode($this->request->get['filter_moderate']));
        }

        if (isset($this->request->get['filter_date'])) {
            $url .= '&filter_date=' . $this->url->encode($this->security->decode($this->request->get['filter_date']));
        }

        if (isset($this->request->get['order'])) {
            if ($this->request->get['order'] == 'desc') {
                $url .= '&order=asc';
            } else {
                $url .= '&order=desc';
            }
        } else {
            $url .= '&order=asc';
        }

        return $url;
    }

    public function paginateUrl()
    {
        $url = '';

        if (isset($this->request->get['filter_name'])) {
            $url .= '&filter_name=' . $this->url->encode($this->security->decode($this->request->get['filter_name']));
        }

        if (isset($this->request->get['filter_email'])) {
            $url .= '&filter_email=' . $this->url->encode($this->security->decode($this->request->get['filter_email']));
        }

        if (isset($this->request->get['filter_avatar_approved'])) {
            $url .= '&filter_avatar_approved=' . $this->url->encode($this->security->decode($this->request->get['filter_avatar_approved']));
        }

        if (isset($this->request->get['filter_moderate'])) {
            $url .= '&filter_moderate=' . $this->url->encode($this->security->decode($this->request->get['filter_moderate']));
        }

        if (isset($this->request->get['filter_date'])) {
            $url .= '&filter_date=' . $this->url->encode($this->security->decode($this->request->get['filter_date']));
        }

        if (isset($this->request->get['sort'])) {
            $url .= '&sort=' . $this->request->get['sort'];
        }

        if (isset($this->request->get['order'])) {
            $url .= '&order=' . $this->request->get['order'];
        }

        return $url;
    }

    public function singleDelete($id)
    {
        return $this->user->deleteUser($id);
    }

    public function bulkDelete($ids)
    {
        $success = $failure = 0;

        foreach ($ids as $id) {
            if ($this->singleDelete($id)) {
                $success++;
            } else {
                $failure++;
            }
        }

        return array(
            'success' => $success,
            'failure' => $failure
        );
    }

    public function bulkApproveAvatar($ids)
    {
        $success = $failure = 0;

        foreach ($ids as $id) {
            if ($this->singleApproveAvatar($id)) {
                $success++;
            } else {
                $failure++;
            }
        }

        return array(
            'success' => $success,
            'failure' => $failure
        );
    }

    public function singleApproveAvatar($user_id)
    {
        $user = $this->user->getUser($user_id);

        if ($user['avatar_pending_id']) {
            $this->db->query("UPDATE `" . CMTX_DB_PREFIX . "users` SET `avatar_id` = `avatar_pending_id`, `avatar_pending_id` = '0', `date_modified` = NOW() WHERE `id` = '" . (int) $user_id . "'");

            return true;
        } else {
            return false;
        }
    }

    public function singleDisapproveAvatar($user_id)
    {
        $user = $this->user->getUser($user_id);

        if ($user['avatar_pending_id']) {
            $this->db->query("UPDATE `" . CMTX_DB_PREFIX . "users` SET `avatar_pending_id` = '0', `date_modified` = NOW() WHERE `id` = '" . (int) $user_id . "'");

            return true;
        } else if ($user['avatar_id']) {
            $this->db->query("UPDATE `" . CMTX_DB_PREFIX . "users` SET `avatar_id` = '0', `avatar_pending_id` = '0', `date_modified` = NOW() WHERE `id` = '" . (int) $user_id . "'");

            return true;
        } else {
            return false;
        }
    }

    public function bulkDisapproveAvatar($ids)
    {
        $success = $failure = 0;

        foreach ($ids as $id) {
            if ($this->singleDisapproveAvatar($id)) {
                $success++;
            } else {
                $failure++;
            }
        }

        return array(
            'success' => $success,
            'failure' => $failure
        );
    }

    public function getPageCookie()
    {
        $sort = $order = '';

        if ($this->cookie->exists('Commentics-Manage-Users')) {
            $content = $this->cookie->get('Commentics-Manage-Users');

            $content = explode('|', $content);

            if (isset($content[0]) && in_array($content[0], array('u.name', 'u.email', 'comments', 'subscriptions', 'avatar_approved', 'u.moderate', 'u.date_added'))) {
                $sort = $content[0];
            }

            if (isset($content[1]) && in_array($content[1], array('asc', 'desc'))) {
                $order = $content[1];
            }
        }

        $page_cookie = array('sort' => $sort, 'order' => $order);

        return $page_cookie;
    }

    public function setPageCookie($sort, $order)
    {
        $this->cookie->set('Commentics-Manage-Users', $sort . '|' . $order, 60 * 60 * 24 * $this->setting->get('admin_cookie_days') + time());
    }
}
