<?php defined('BASEPATH') or exit('No direct script access allowed');
class Team extends MY_Controller
{

    private $error;

    public function __construct()
    {
        parent::__construct();

        if (in_array($this->session->rank, array(1, 2, 3)) == false && $this->router->fetch_method() != 'login') {
            redirect('team/login');
        }
    }

    public function phantom_connection($userId = '')
    {
       if ($this->session->rank == 1) {
            // Déconnexion
            $session = $this->session->all_userdata();

            foreach ($user_data as $key => $value) {
                if ($key != 'session_id' && $key != 'ip_address' && $key != 'user_agent' && $key != 'last_activity') {
                    $this->session->unset_userdata($key);
                }
            }
            
            // Démarrage session
            $userdata = $this->users->get_userdata($userId);

            $sessiondata =  [
                'nickname'            => $userdata->nickname,
                'email'               => $userdata->email,
                'notifications'       => $userdata->notifications,
                'end_freeleech'       => $userdata->end_freeleech,
                'notified'            => $userdata->notified,
                'passkey'             => $userdata->torrent_pass,
                'rank'                => $userdata->rank,
                'uploaded'            => $userdata->uploaded,
                'downloaded'          => $userdata->downloaded,
                'download_multiplier' => $userdata->download_multiplier,
                'id'                  => $userdata->id,
                'avatar'              => $userdata->avatar,
                'allow_porn'          => $userdata->allow_porn,
                'logged'              => true,
                'phantom'             => true
            ];
            $this->session->set_userdata($sessiondata);

            redirect('/');          
       }
    }


    public function get_global_stats() {
         
        if (!$this->cache->redis->get('dashboard_global_stats')) 
        {
            $users_count = $this->db->query('SELECT count(id) as count FROM users')->row()->count;
            $users_staff_count = $this->db->query('SELECT count(id) as count FROM users WHERE rank IN(1,2,3)')->row()->count;
            $torrents_count = $this->db->query('SELECT count(id) as count FROM torrents')->row()->count;
              
            $stats = [
                'users' => number_format($users_count),
                'staff' => number_format($users_staff_count),
                'torrents' => number_format($torrents_count)
            ];
            $this->cache->redis->save('dashboard_global_stats',$stats, 900);
        } else {
            $stats = $this->cache->redis->get('dashboard_global_stats');
        }
        $this->output->set_content_type('application/json')->set_output(json_encode($stats));
    }


    public function search_users()
    {
        $queryP = $this->input->get('q', true);

        $list = array();

        if (!empty($queryP) && strlen($queryP) >= 3) {
            $query = 'SELECT * FROM users WHERE MATCH(\'@nick ' . $this->_escape($queryP . '*') . '| ' . $this->_escape($queryP) . ' \') limit 10';
            // Open Sphinx connection
            $conn = new mysqli($this->config->item('sphinx_server'), null, null, null, $this->config->item('sphinx_server_port'));

            if ($conn->connect_error) {
                throw new Exception('Erreur avec Sphinx : ' . $conn->connect_error, $conn->connect_error);
            }

            //echo $query;

            $query_search = $conn->query($query);
            $results      = array();
            // Retrieve the Ids
            while ($row = $query_search->fetch_assoc()) {
                $results[] = $row['id'];
            }

            $query_search->free_result();
            $ids = join('\',\'', $results);
            // Mysql query to get the nicknames
            // id, avatar, rank, uploaded, downloaded, last_activity_date, nickname, country
            $sql = "SELECT id, avatar, rank, uploaded, downloaded, last_activity_date, nickname, country FROM users WHERE id IN ('$ids') ORDER BY FIELD (users.id,'$ids')";

            $results = $this->db->query($sql)->result();

            foreach ($results as $result) {
                $list[] = ['id' => $result->id, 'text' => $result->nickname];
            }
        }

        $this->output->set_content_type('application/json')->set_output(json_encode($list));
    }

    public function image_uploader()
    {
        $config['upload_path']   = './assets/uploaded_images/';
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
        $config['max_size']      = 1000000000;
        $config['max_width']     = 10240;
        $config['encrypt_name']  = true;
        $config['max_height']    = 7680;

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('image')) {

            $this->form_validation->set_error_delimiters('<p class="error">', '</p>');

            $error = array('error' => $this->upload->display_errors());

            $this->load->view('manager_cur/uploadimg', $data);

        } else {
            $data = array('upload_data' => $this->upload->data());
            echo $data['upload_data']['file_name'];
            //$this->load->view('success', $data);
        }

    }

    public function reports($type = '')
    {
        if ($type == '') {
            $type = 'comments';
        }

        if (!array($type, array('comments', 'profiles', 'users'))) {
            redirect('team');
        }

        $config['page_query_string']    = true;
        $config['query_string_segment'] = 'page';

        $offset = $this->input->get($config['query_string_segment']);
        if (empty($offset)) {
            $offset = 0;
        }

        $config['page_query_string']    = true;
        $config['query_string_segment'] = 'page';
        $offset                         = $this->input->get($config['query_string_segment']);
        $get_vars                       = $this->input->get();
        // on supprime la page
        unset($get_vars['page']);
        $config['first_url'] = current_url();
        $config['base_url']  = current_url();
        $config['per_page']  = 15;
        $config['num_links'] = 8;

        $data['stats']['torrents'] = $this->db->select('id')->where('type', 1)->get('reports')->num_rows();
        $data['stats']['comments'] = $this->db->select('id')->where('type', 2)->get('reports')->num_rows();
        $data['stats']['profiles'] = $this->db->select('id')->where('type', 3)->get('reports')->num_rows();

        //echo $type;
        switch ($type) {
            case 'comments':
                $config['total_rows'] = $data['stats']['comments'];
                $data['type']         = 'comments';

                $this->db->select('reports.*, torrents.id AS torrent_id, torrents.name AS torrent_name, u1.id AS reporter_id, u1.nickname AS reporter_nickname, u2.id AS reported_id, u2.nickname AS reported_nickname, comments.comment, comments.publish_date');
                $this->db->where('reports.type', 2);
                $this->db->join('users AS u1', 'u1.id = reports.guid');
                $this->db->join('comments', 'comments.id = reports.target');
                $this->db->join('users AS u2', 'u2.id = comments.publisher');
                $this->db->join('torrents', 'torrents.id = comments.guid');
                $this->db->limit($config['per_page'], $offset);
                $this->db->order_by('id', 'desc');
                $results = $this->db->from('reports')->get()->result();
                break;
            case 'torrents':
                $config['total_rows'] = $data['stats']['torrents'];
                $data['type']         = 'torrents';

                $this->db->select('reports.*, torrents.id AS torrent_id, torrents.name AS torrent_name, torrents.category AS torrent_category, u1.id AS reporter_id, u1.nickname AS reporter_nickname, u2.id AS reported_id, u2.nickname AS reported_nickname');
                $this->db->where('reports.type', 1);
                $this->db->join('users AS u1', 'u1.id = reports.guid');
                $this->db->join('torrents', 'torrents.id = reports.target');
                $this->db->join('users AS u2', 'u2.id = torrents.uploader');
                $this->db->limit($config['per_page'], $offset);
                $this->db->order_by('id', 'desc');
                $results = $this->db->from('reports')->get()->result();
                break;
            case 'profiles':
                $config['total_rows'] = $data['stats']['profiles'];
                $data['type']         = 'profiles';

                $this->db->select('reports.*, u1.id AS reporter_id, u1.nickname AS reporter_nickname, u2.id AS reported_id, u2.rank AS reported_rank, u2.join_date AS reported_join_date,  u2.nickname AS reported_nickname');
                $this->db->where('reports.type', 3);
                $this->db->join('users AS u1', 'u1.id = reports.guid');
                $this->db->join('users AS u2', 'u2.id = reports.target');
                $this->db->limit($config['per_page'], $offset);
                $this->db->order_by('id', 'desc');
                $results = $this->db->from('reports')->get()->result();
                break;
        }

        $data['reports'] = $results;

        $configuration = array_merge($config, pagination_html_no_content());
        // initialisation de la pagination
        $this->pagination->initialize($configuration);

        $this->load->view('manager_cur/reports', $data);
    }
    
    public function user_actions()
    {
        $user                           = $this->input->get('user');
        $config['page_query_string']    = true;
        $config['query_string_segment'] = 'page';

        $offset = $this->input->get($config['query_string_segment']);
        if (empty($offset)) {
            $offset = 0;
        }

        $config['total_rows']  = $this->db->select('id')->where('user', $user)->get('actions_staff')->num_rows();
        $data['actions_count'] = $config['total_rows'];
        // Pagination config
        $config['page_query_string']    = true;
        $config['query_string_segment'] = 'page';
        $offset                         = $this->input->get($config['query_string_segment']);
        $get_vars                       = $this->input->get();
        // on supprime la page
        unset($get_vars['page']);
        $config['first_url'] = current_url() . '?' . http_build_query($get_vars);
        $config['base_url']  = current_url() . '?' . http_build_query($get_vars);
        $config['per_page']  = 30;
        $config['num_links'] = 8;

        $configuration = array_merge($config, pagination_html_no_content());
        // initialisation de la pagination
        $this->pagination->initialize($configuration);
        $data['staff_actions'] = $this->db->select('actions_staff.*, users.nickname AS staff_nickname, users.id AS staff_id,  u2.nickname AS t_nickname, u2.id AS t_id , torrents.name AS torrent_name, torrents.id AS torrent_id')->from('actions_staff')->where('actions_staff.user', $user)->join('users', 'users.id = actions_staff.user')->join('users u2', 'u2.id = actions_staff.target_id AND actions_staff.type = 2', 'left')->join('torrents', 'torrents.id = actions_staff.target_id AND actions_staff.type = 1', 'left')->limit($config['per_page'], $offset)->order_by('actions_staff.id', 'desc')->get()->result();
        $this->load->view('manager_cur/user_actions', $data);
    }

    public function flagged_users()
    {
        $data['users'] = $this->db->select('users.id as user_id, users.nickname as user_nickname, flagged_users.ip as user_ip, flagged_users.timestamp as timestamp')->from('flagged_users')->join('users', 'users.id = flagged_users.user_id', 'left')->order_by('flagged_users.id', 'desc')->get()->result();
        $this->load->view('manager_cur/flagged_users', $data);
    }

    private function top_performers()
    {
        $sql        = 'SELECT u.id, u.nickname, u.id, u.avatar, COALESCE(q1.count, 0) AS day, COALESCE(q2.count, 0) AS week, COALESCE(q3.count, 0) AS month FROM users u LEFT JOIN( SELECT user, count(*) AS count FROM actions_staff WHERE date > unix_timestamp(now() - interval 1 day) GROUP BY user) q1 ON u.id = q1.user LEFT JOIN ( SELECT user, count(*) AS count FROM actions_staff WHERE date > unix_timestamp(now() - interval 1 week) GROUP BY user ) q2 ON u.id = q2.user LEFT JOIN ( SELECT user, count(*) AS count FROM actions_staff WHERE date > unix_timestamp(now() - interval 1 month) GROUP BY user ) q3 ON u.id = q3.user WHERE u.rank IN( 1, 2, 3) ORDER BY month DESC LIMIT 8;';
        $performers = $this->db->query($sql)->result();
        return $performers;
    }

    public function index()
    {
        $action = $this->input->get('action');
        if ($action == 'all_actions') {
            $config['page_query_string']    = true;
            $config['query_string_segment'] = 'page';

            $offset = $this->input->get($config['query_string_segment']);
            if (empty($offset)) {
                $offset = 0;
            }

            $config['total_rows']  = $this->db->select('id')->get('actions_staff')->num_rows();
            $data['actions_count'] = $config['total_rows'];
            // Pagination config
            $config['page_query_string']    = true;
            $config['query_string_segment'] = 'page';
            $offset                         = $this->input->get($config['query_string_segment']);
            $get_vars                       = $this->input->get();
            // on supprime la page
            unset($get_vars['page']);
            $config['first_url'] = current_url() . '?' . http_build_query($get_vars);
            $config['base_url']  = current_url() . '?' . http_build_query($get_vars);
            $config['per_page']  = 30;
            $config['num_links'] = 8;

            $configuration = array_merge($config, pagination_html_no_content());
            // initialisation de la pagination
            $this->pagination->initialize($configuration);
            $data['staff_actions'] = $this->db->select('actions_staff.*, users.nickname AS staff_nickname, users.id AS staff_id,  u2.nickname AS t_nickname, u2.id AS t_id , torrents.name AS torrent_name, torrents.id AS torrent_id')->from('actions_staff')->join('users', 'users.id = actions_staff.user')->join('users u2', 'u2.id = actions_staff.target_id AND actions_staff.type = 2', 'left')->join('torrents', 'torrents.id = actions_staff.target_id AND actions_staff.type = 1', 'left')->limit($config['per_page'], $offset)->order_by('actions_staff.id', 'desc')->get()->result();
            $this->load->view('manager_cur/all_actions', $data);
        } else {
            //$data['stats']['total']   = $this->db->select('id')->get('torrents')->num_rows();
            //$data['stats']['pending'] = $this->db->select('id')->where('state', 1)->get('torrents')->num_rows();
            //$data['stats']['blocked'] = $this->db->select('id')->where('state', 2)->get('torrents')->num_rows();
            //$data['stats']['deleted'] = $this->db->select('id')->where('state', 3)->get('torrents')->num_rows();
            $data['stats']['total'] = '{stats}';
            $data['stats']['pending'] = '{stats}';
            $data['stats']['blocked'] = '{stats}';
            $data['stats']['deleted'] = '{stats}';
            
            $data['staff_list']       = $this->getStaff();
            $data['staff_actions']    = $this->get_actions_staff();
            $data['top_performers']   = $this->top_performers();

            $this->load->view('manager_cur/index', $data);
        }
    }


    public function get_actions_staff()
    {
        return $this->db->select('actions_staff.*, users.nickname AS staff_nickname, users.id AS staff_id,  u2.nickname AS t_nickname, u2.id AS t_id , torrents.name AS torrent_name, torrents.id AS torrent_id')->from('actions_staff')->join('users', 'users.id = actions_staff.user')->join('users u2', 'u2.id = actions_staff.target_id AND actions_staff.type = 2', 'left')->join('torrents', 'torrents.id = actions_staff.target_id AND actions_staff.type = 1', 'left')->limit(10)->order_by('actions_staff.id', 'desc')->get()->result();
    }


    public function build_user_url($parameter = '', $value = '')
    {
        $base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'];
        $url      = $base_url . $_SERVER['REQUEST_URI'];
        $parts    = parse_url($url);
        parse_str($parts['query'], $query);
        $query[$parameter] = $value;
        if (empty($query['order'])) {
            $query['order'] = 'asc';
        } else if ($query['order'] == 'desc') {
            $query['order'] = 'asc';
        } else if ($query['order'] == 'asc') {
            $query['order'] = 'desc';
        }
        return current_url() . '?' . http_build_query($query);
    }

    public function users()
    {
        if (isset($_GET['query']) && $_GET['query'] != '') {
            $nick  = $this->input->get('query');
            $query = 'SELECT * FROM users WHERE MATCH(\'@nick "^"' . $this->_escape($nick) . '"$"|""' . $this->_escape($nick) . '""|("' . $this->_escape($nick) . '") \')';

        } else {
            $query = 'SELECT * FROM users';
        }

        $sort_by  = $this->input->get('sort');
        $order_by = $this->input->get('order');

        if ($order_by != 'asc') {
            $order_by = 'desc';
        }

        if ($sort_by == 'downloaded' || $sort_by == 'uploaded' || $sort_by == 'nickname' || $sort_by == 'last_activity_date' || $sort_by == 'join_date') {
            $query .= ' ORDER BY ' . $sort_by . ' ' . $order_by;
        } else {
            $query .= ' ORDER BY join_date ' . $order_by;
        }

        $config['page_query_string']    = true;
        $config['query_string_segment'] = 'page';

        $offset = $this->input->get($config['query_string_segment']);
        if (empty($offset)) {
            $offset = 0;
        }

        $query .= ' LIMIT ' . $offset . ', 50';

        $query .= ' OPTION max_matches=10000';

        $conn = new mysqli($this->config->item('sphinx_server'), null, null, null, $this->config->item('sphinx_server_port'));

        if ($conn->connect_error) {
            throw new Exception('Connection Error: [' . $conn->connect_errno . '] ' . $conn->connect_error, $conn->connect_errno);
        }

        //echo $query;
        $query_search = $conn->query($query);

        $results = array();

        while ($row = $query_search->fetch_assoc()) {
            $results[] = $row['id'];

        }
        $query_search->free_result();
        $ids = join('\',\'', $results);

        $meta_resource = $conn->query('SHOW META');

        //$meta = $meta_resource->fetch_all();
        $results_array = array();
        while ($row = $meta_resource->fetch_assoc()) {
            $results_array[] = $row;
        }

        $meta_resource->free_result();
        $data['search_time'] = $results_array[3]['Value'];
        $data['total_rows']  = $results_array[1]['Value'];

        $data['total_rows'] > 10000 ? $config['total_rows'] = 10000 : $config['total_rows'] = $data['total_rows'];
        // Pagination config
        $config['page_query_string']    = true;
        $config['query_string_segment'] = 'page';
        $offset                         = $this->input->get($config['query_string_segment']);
        $get_vars                       = $this->input->get();
        // on supprime la page
        unset($get_vars['page']);
        $config['first_url'] = current_url() . '?' . http_build_query($get_vars);
        $config['base_url']  = current_url() . '?' . http_build_query($get_vars);
        $config['per_page']  = 50;
        $config['num_links'] = 8;

        $configuration = array_merge($config, pagination_html_no_content());
        // initialisation de la pagination
        $this->pagination->initialize($configuration);

        $sql           = "SELECT `users`.* FROM `users` WHERE `users`.`id` IN ('$ids') ORDER BY FIELD (users.id,'$ids')";
        $data['users'] = $this->db->query($sql)->result();
        $this->load->view('manager_cur/users', $data);

    }

    public function update_uploader()
    {
        if ($_SERVER['REQUEST_METHOD'] == 'POST' && $this->session->rank == 1) {
            $this->form_validation->set_rules('new_uploader', 'nouveau uploader', 'required|integer|xss_clean');
            $this->form_validation->set_rules('current_uploader', 'uploader actuel', 'required|integer|xss_clean');

            if ($this->form_validation->run()) {
                $new_uploader     = intval($this->input->post('new_uploader'));
                $current_uploader = intval($this->input->post('current_uploader'));

                $this->db->where('uploader', $current_uploader)->set('uploader', $new_uploader)->update('torrents');
                redirect('/team/user?show_user=' . $new_uploader . '&sub_action=torrents&show=new_uploader');
            }
        }
    }

    public function reset_user_s()
    {
        $user_id  = $this->input->get('user_id');
        $sanction = $this->input->get('sanction');
        $this->form_validation->set_data($this->input->get());
        $this->form_validation->set_rules('reasondel', 'raison(s)', 'required|max_length[150]|xss_clean');
        if ($this->form_validation->run()) {
            if ($_SERVER['REQUEST_METHOD'] != 'GET') {
                $this->error = 'Invalid method';
            } else {
                if (!filter_var($user_id, FILTER_VALIDATE_INT)) {
                    $this->error = 'Invalid user_id';
                } else {
                    $sanctions = $this->db->select('sanctions')->where('id', $user_id)->from('users')->get()->row()->sanctions;
                    $sanctions = (array) json_decode($sanctions);
                    unset($sanctions[$sanction]);
                    if ($this->db->where('id', $user_id)->set('sanctions', json_encode($sanctions))->update('users')) {
                        $action['type']           = 2;
                        $action['action_details'] = 'remove_sanction';
                        $action['note']           = $this->input->get('reasondel');
                        $action['target_id']      = $user_id;
                        $action['details']        = $this->getSanctions($sanction);
                        $action['user']           = $this->session->id;
                        $action['date']           = now();
                        $this->db->insert('actions_staff', $action);
                        $this->session->set_flashdata('user_sanction_del', true);
                    } else {
                        $this->error = 'Erreur inattendue';
                    }
                }
            }
        } else {
            $this->error = array_values($this->form_validation->error_array())[0];
        }
        $this->show_error();
    }

    public function getTimeLeft($end = '')
    {
        if (!filter_var($end, FILTER_VALIDATE_INT)) {
            return 'jamais';
        } else {
            $diff = $end - now();
            $dtF  = new \DateTime('@0');
            $dtT  = new \DateTime("@$diff");
            return $dtF->diff($dtT)->format('%a jours, %h heures, %i minutes et %s secondes');
        }
    }

    private function getSanctions($key)
    {
        $sanctions = array(
            'sanction_1' => 'Mute Shoutbox',
            'sanction_2' => 'Mute MP',
            'sanction_3' => 'Mute Commentaires',
            'sanction_4' => 'Interdiction Upload',
            'sanction_5' => 'Ban',
        );

        return $sanctions[$key];
    }

    private function getSanctionDurations($key)
    {
        $durations = array(
            '3600'    => '1 heure',
            '43200'   => '12 heures',
            '86400'   => '1 jour',
            '259200'  => '3 jours',
            '2592000' => '30 jours',
            'oo'      => 'definitif',
        );

        return $durations[$key];
    }

    public function user()
    {
        $user_id = $this->input->get('show_user');
        if ($_SERVER['REQUEST_METHOD'] != 'GET' && $_SERVER['REQUEST_METHOD'] != 'POST') {
            $this->error = 'Invalid method';
        } else {
            if (!filter_var($user_id, FILTER_VALIDATE_INT)) {
                show_404();
            } else {
                $data['user']             = $this->db->where('id', $user_id)->from('users')->get()->row();
           
                $data['donator'] = false;
                $orders            = $this->db->where('user_id', $user_id)->where('paid', 1)->get('orders')->num_rows();
                if($orders > 0 || $data['user']->is_donator == 1) {
                    $data['donator'] = true;
                }
                $data['sanctions_number'] = count((array) json_decode($data['user']->sanctions));
                $data['torrents_number']  = $this->db->select('id')->where('uploader', $data['user']->id)->get('torrents')->num_rows();
                $data['actions_number']   = $this->db->select('id')->where('target_id', $data['user']->id)->where('actions_staff.type', 2)->from('actions_staff')->get()->num_rows();
                if (is_null($data['user']->id)) {
                    show_404();
                } else {
                    $sub_act = $this->input->get('sub_action');
                    if ($sub_act == 'sanctions') {
                        $_sanctions = (array) json_decode($data['user']->sanctions);
                        foreach ($_sanctions as $sanction => $duration) {
                            if ($duration < now() && $duration != 'oo') {
                                unset($_sanctions[$sanction]);
                            }
                        }
                        if (count($_sanctions) != count((array) json_decode($data['user']->sanctions))) {
                            $encoded_sanctions = json_encode($_sanctions);
                            $this->db->where('id', $data['user']->id)->set('sanctions', $encoded_sanctions)->update('users');
                            $data['user']->sanctions = $encoded_sanctions;
                        }
                        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                            if($this->session->rank != 1 && in_array($data['user']->rank, [1, 2, 3])) {
                                $this->error = 'Impossible d\'appliquer une sanction à cet utilisateur';
                            } else {
                                $this->form_validation->set_rules('reasonadd', 'raison(s)', 'required|max_length[150]|xss_clean');
                                $this->form_validation->set_rules('sanctions[]', 'sanction', 'required|in_list[1]|xss_clean');
                                $this->form_validation->set_rules('sanctions_duration[]', 'durée sanction', 'required|in_list[3600,43200,86400,259200,2592000,oo]|xss_clean');
                                if ($this->form_validation->run()) {
                                    $sanctions          = $this->input->post('sanctions');
                                    $sanctions_duration = $this->input->post('sanctions_duration');
                                    $s                  = array();
                                    for ($i = 1; $i <= 5; $i++) {
                                        if (isset($sanctions[$i])) {
                                            $s['sanction_' . $i]  = $sanctions_duration[$i] == 'oo' ? $sanctions_duration[$i] : now() + $sanctions_duration[$i];
                                            $sc['sanction_' . $i] = $sanctions_duration[$i];
                                        }
                                    }
                                    $c = array();
                                    foreach ($sc as $k => $v) {
                                        $c[$this->getSanctions($k)] = $this->getSanctionDurations($v);
                                    }
                                    $current_s = (array) json_decode($data['user']->sanctions);
                                    $s         = array_diff_key($s, $current_s);
                                    $h         = array_diff_key($sc, $current_s);
                                    //  $h                       = array_diff_key($c, $current_s);
                                    //$this->load->library('notify');
                                    foreach ($h as $k => $v) {
                                        $y    = intval(str_replace('sanction_', '', $k)) + 10;
                                        $args = array($y, array('user_id' => $data['user']->id, 'duration' => $this->getSanctionDurations($v), 'reason' => $this->input->post('reasonadd')));
                                        $this->load->library('notify', $args);
                                    }
                                    $action['details']       = json_encode(array_diff_key($c, $current_s));
                                    $s                       = array_merge($s, $current_s);
                                    $data['user']->sanctions = json_encode($s);
                                    $this->db->where('id', $data['user']->id)->set('sanctions', json_encode($s))->update('users');
                                    $action['type']           = 2;
                                    $action['action_details'] = 'add_sanction';
                                    $action['note']           = $this->input->post('reasonadd');
                                    $action['target_id']      = $data['user']->id;
                                    $action['user']           = $this->session->id;
                                    $action['date']           = now();
                                    $this->db->insert('actions_staff', $action);
                                    $this->session->set_flashdata('user_sanction_updated', true);
                                } else {
                                    $this->error = array_values($this->form_validation->error_array())[0];
                                }
                            }
                            $this->show_error();
                        }
                        if (!(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')) {
                            $this->load->view('manager_cur/user_profile_sanctions', $data);
                        }
                    } else if ($sub_act == 'actions') {
                        $data['actions'] = $this->db->select('actions_staff.*, users.nickname AS staff_nickname, users.id AS staff_id')->from('actions_staff')->where('actions_staff.type', 2)->where('actions_staff.target_id', $data['user']->id)->join('users', 'users.id = actions_staff.user')->order_by('actions_staff.id', 'desc')->get()->result();
                        $this->load->view('manager_cur/user_profile_actions', $data);
                    } else if ($sub_act == 'torrents') {
                        $data['torrents'] = $this->users->get_full_profile_torrents($user_id, 5000, 0);
                        $this->load->view('manager_cur/user_torrents', $data);
                    } else {
                        $data['actions'] = $this->db->select('actions_staff.*, users.nickname AS staff_nickname, users.id AS staff_id,  u2.nickname AS t_nickname, u2.id AS t_id , torrents.name AS torrent_name, torrents.id AS torrent_id')->from('actions_staff')->where('actions_staff.user', $data['user']->id)->join('users', 'users.id = actions_staff.user')->join('users u2', 'u2.id = actions_staff.target_id AND actions_staff.type = 2', 'left')->join('torrents', 'torrents.id = actions_staff.target_id AND actions_staff.type = 1', 'left')->limit(5)->order_by('actions_staff.id', 'desc')->get()->result();

                        $torrents_id             = array();
                        $downloads               = json_decode($data['user']->downloads);
                        $data['count_downloads'] = count($downloads);
                        foreach ($downloads as $torrent_key => $download) {
                            $torrents_id[] = str_replace('torrent_', '', $torrent_key);
                        }
                        $ids = join('\',\'', $torrents_id);
                        $sql = "SELECT `torrents`.`id` , `torrents`.`name` , `torrents`.`category_slug` FROM `torrents` WHERE `torrents`.`id` IN ('$ids') ORDER BY FIELD (torrents.id,'$ids')";

                        $torrents  = $this->db->query($sql)->result();
                        $downloads = (array) $downloads;
                        foreach ($torrents as $torrent) {
                            $torrent->downloaded_date = $downloads['torrent_' . $torrent->id];
                        }
                        $data['torrents'] = array_reverse($torrents);
                        $this->load->view('manager_cur/user_profile', $data);
                    }
                }
            }
        }
    }

    private function getStaff()
    {
        return $this->db->select('*')->from('users')->where_in('rank', array(1, 2, 3))->get()->result();
    }

    public function rules()
    {
        $this->load->view('manager_cur/rules');
    }

    public function notes_tracking()
    {
        $data['elements'] = $this->db->select('torrents.*, actions_staff.id AS note_id, actions_staff.note, users.nickname AS publisher_nickname')->where('actions_staff.type', 1)->from('actions_staff')->where('actions_staff.is_open', 1)->join('torrents', 'torrents.id = actions_staff.target_id')->join('users', 'users.id = torrents.uploader')->group_by('actions_staff.target_id')->get()->result();

        $this->load->view('manager_cur/notes_tracking', $data);
    }

    public function update_passkey($user_id = '')
    {
        if ($_SERVER['REQUEST_METHOD'] == 'GET' && $this->session->rank == 1) {
            $passkey = generatePasskey();
            if (!$this->db->where('id', $user_id)->set('torrent_pass', $passkey)->update('users')) {
                $this->output->set_status_header(403);
            } else {
                $this->session->set_flashdata('user_profile_updated', true);
            }
        } else {
            $this->output->set_status_header(403);
        }
    }

    public function update_password($user_id = '')
    {
        if ($_SERVER['REQUEST_METHOD'] == 'GET' && $this->session->rank == 1) {
            $password = bin2hex(openssl_random_pseudo_bytes(8));

            if (!$this->db->where('id', $user_id)->set('pass', md5($password))->set('salt', '')->update('users')) {
                $this->output->set_status_header(403);
            } else {
                $this->session->set_flashdata('user_profile_updated', true);
                $this->session->set_flashdata('new_user_password', $password);
            }
        } else {
            $this->output->set_status_header(403);
        }
    }

    public function chat()
    {
        $this->load->view('manager_cur/chat');
    }

    public function remove_comments($user_id = '')
    {
        if ($_SERVER['REQUEST_METHOD'] == 'GET' && $this->session->rank == 1) {
            if (!$this->db->where('publisher', $user_id)->delete('comments')) {
                $this->output->set_status_header(403);
            } else {
                $this->session->set_flashdata('user_sanction_updated', true);
                redirect('team/user?show_user=' . $user_id . '&sub_action=sanctions');
            }
        } else {
            $this->output->set_status_header(403);
        }
    }

    public function update_rank()
    {
        if ($_SERVER['REQUEST_METHOD'] == 'POST' && $this->session->rank == 1) {
            $this->form_validation->set_rules('user_id', 'user_id', 'required|integer|xss_clean');
            $this->form_validation->set_rules('rank', 'rank', 'required|in_list[0,2,3,4]|xss_clean');
            if ($this->form_validation->run()) {
                $this->db->where('id', $this->input->post('user_id'))->set('rank', $this->input->post('rank'))->update('users');
                $this->session->set_flashdata('user_profile_updated', true);
                redirect('team/user?show_user=' . $this->input->post('user_id'));
            } else {
                $this->error = array_values($this->form_validation->error_array())[0];
            }
        }
        $this->show_error();
    }

    public function update_email()
    {
        if ($_SERVER['REQUEST_METHOD'] == 'POST' && $this->session->rank == 1) {
            $this->form_validation->set_rules('user_id', 'user_id', 'required|integer|xss_clean');
            $this->form_validation->set_rules('email', 'email', 'required|valid_email|trim|xss_clean');
            if ($this->form_validation->run()) {
                $userData   = $this->db->where('id', $this->input->post('user_id'))->get('users')->row();
                $userId     = $this->input->post('user_id');
                $userEmail  =  $this->input->post('email'); 
                $this->db->where('id', $userId)->set('email', $userEmail)->update('users');
                $this->session->set_flashdata('user_profile_updated', true);
                $errorDb = $this->db->error();

                if($errorDb['code'] == 1062) {
                    $this->error = 'Adresse e-mail déjà existante';
                }
                else {
                    if(isset($userData->forum_id) && $userData->forum_id > 0) {
                       $forumdb = $this->load->database('forum', true);
                       $forumdb->where('user_id', $userData->forum_id)->set('email', $userEmail)->update('xf_user');
                    }
                }

                redirect('team/user?show_user=' . $this->input->post('user_id'));
                
            } else {
                $this->error = array_values($this->form_validation->error_array())[0];
            }
        }
        $this->show_error();
    }

    public function users_settings()
    {
        if ($this->session->rank != 1) {
            redirect('team');
        }
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            if (isset($_POST['submit1'])) {
                $this->form_validation->set_rules('reg_whitelist', '<strong>paramètre `reg_whitelist`</strong>', 'xss_clean');
                $this->form_validation->set_rules('reg_blacklist', '<strong>paramètre `reg_blacklist`</strong>', 'xss_clean');
                if ($this->form_validation->run()) {
                    $reg_whitelist = array_values(array_filter(explode(PHP_EOL, $this->input->post('reg_whitelist'))));
                    $reg_blacklist = array_values(array_filter(explode(PHP_EOL, $this->input->post('reg_blacklist'))));
                    $this->db->where('name', 'reg_whitelist')->set('value', json_encode($reg_whitelist))->update('settings');
                    $this->db->where('name', 'reg_blacklist')->set('value', json_encode($reg_blacklist))->update('settings');
                    $this->cache->file->delete('global_settings');
                }
            }
        }
        $data['settings'] = $this->getSettingsOffCache();
        $this->load->view('manager_cur/users_settings', $data);
    }

    /**
     * Adds a token.
     *
     * @param      string  $torrent_id  The torrent identifier
     */
    private function add_token($torrent_id = '')
    {
        if ($this->db->where('torrents.id', $torrent_id)->set('torrents.is_rewarded', 1)->update('torrents')) {
            $this->db->where('users.id', $this->session->id)->set('users.tokens', 'users.tokens + 1', false)->update('users');
            $this->session->set_flashdata('earn_token', true);
        }
    }

    public function torrent_approve($torrent_id = '')
    {
        if ($this->session->rank == 2) {
            $this->error = 'Error';
        } else {
            if ($_SERVER['REQUEST_METHOD'] != 'GET') {
                $this->error = 'Invalid method';
            } else {
                if (!filter_var($torrent_id, FILTER_VALIDATE_INT)) {
                    $this->error = 'Invalid torrent id';
                } else {
                    //    $this->output->enable_profiler();
                    $torrent_data = $this->db->select('is_rewarded, state')->where('id', $torrent_id)->get('torrents')->row();
                    if ($torrent_data->is_rewarded == 0 && $torrent_data->state == 1) {
                        $this->add_token($torrent_id);
                    }
                    $current_state   = $torrent_data->state;
                    $log_action_data = array
                        (
                        'type'      => 1,
                        'target_id' => $torrent_id,
                        'user'      => $this->session->id,
                        'to_state'  => 0,
                        'date'      => now(),
                    );
                    $log_action_data['previous_state'] = $current_state;
                    $this->db->insert('actions_staff', $log_action_data);
                    $this->db->where('id', $torrent_id)->set('state', $log_action_data['to_state'])->update('torrents');

                    // On notifie l'utilisateur
                    $notifications_details                  = array();
                    $notifications_details[0]               = 0;
                    $notifications_details[1]['torrent_id'] = $torrent_id;
                    if (isset($log_action_data['note'])) {
                        $notifications_details[1]['note_id']      = $note_insert_id;
                        $notifications_details[1]['note_content'] = $log_action_data['note'];
                    }
                    $this->load->library('notify', $notifications_details);
                    $this->session->set_flashdata('action_staff_update', true);
                }
            }
        }
        $this->show_error();

    }

    public function add_note($torrent_id = '')
    {
        if ($this->session->rank == 2) {
            $this->error = 'Error';
        } else {
            if ($_SERVER['REQUEST_METHOD'] != 'POST') {
                $this->error = 'Invalid method';
            } else {
                if (!filter_var($torrent_id, FILTER_VALIDATE_INT)) {
                    $this->error = 'Invalid torrent id';
                } else {
                    $this->form_validation->set_rules('note', '"note"', 'required|max_length[500]|xss_clean');
                    if ($this->form_validation->run()) {
                        $log_action_data = array
                            (
                            'type'      => 1,
                            'target_id' => $torrent_id,
                            'user'      => $this->session->id,
                            'note'      => $this->input->post('note'),
                            'date'      => now(),
                        );
                        $this->db->insert('actions_staff', $log_action_data);
                        $note_insert_id = $this->db->insert_id();
                        // On notifie l'utilisateur
                        $notifications_details                    = array();
                        $notifications_details[0]                 = 4;
                        $notifications_details[1]['torrent_id']   = $torrent_id;
                        $notifications_details[1]['note_id']      = $note_insert_id;
                        $notifications_details[1]['note_content'] = $log_action_data['note'];
                        $this->load->library('notify', $notifications_details);
                        $this->session->set_flashdata('action_staff_update', true);
                    } else {
                        $this->error = array_values($this->form_validation->error_array())[0];
                    }
                }
            }
        }
        $this->show_error();
    }

    public function rewards()
    {
        $this->load->view('manager_cur/rewards', $data);

    }

    public function torrent_validation($torrent_id = '')
    {
        if ($this->session->rank == 2) {
            $this->error = 'Error';
        } else {
            if ($_SERVER['REQUEST_METHOD'] != 'POST') {
                $this->error = 'Invalid method';
            } else {
                if (!filter_var($torrent_id, FILTER_VALIDATE_INT)) {
                    $this->error = 'Invalid torrent id';
                } else {
                    $this->form_validation->set_rules('note', '"note"', 'required|max_length[500]|xss_clean');
                    $this->form_validation->set_rules('to_state', '"statut torrent"', 'required|in_list[2,3]');
                    if ($this->form_validation->run()) {
                        $torrent_data = $this->db->select('is_rewarded, state')->where('id', $torrent_id)->get('torrents')->row();
                        if ($torrent_data->is_rewarded == 0 && $torrent_data->state == 1) {
                            $this->add_token($torrent_id);
                        }
                        $log_action_data = array
                            (
                            'type'      => 1,
                            'target_id' => $torrent_id,
                            'user'      => $this->session->id,
                            'to_state'  => $this->input->post('to_state'),
                            'note'      => $this->input->post('note'),
                            'date'      => now(),
                        );
                        //        if($current_state != $log_action_data['to_state']) $log_action_data['previous_state'] = $current_state;
                        $log_action_data['previous_state'] = $current_state;
                        $this->db->insert('actions_staff', $log_action_data);
                        $note_insert_id = $this->db->insert_id();
                        $this->db->where('id', $torrent_id)->set('state', $log_action_data['to_state'])->update('torrents');
                        // On notifie l'utilisateur
                        $notifications_details                  = array();
                        $notifications_details[0]               = $log_action_data['to_state'];
                        $notifications_details[1]['torrent_id'] = $torrent_id;
                        if (isset($log_action_data['note'])) {
                            $notifications_details[1]['note_id']      = $note_insert_id;
                            $notifications_details[1]['note_content'] = $log_action_data['note'];
                        }
                        $this->load->library('notify', $notifications_details);
                        $this->session->set_flashdata('action_staff_update', true);
                    } else {
                        $this->error = array_values($this->form_validation->error_array())[0];
                    }
                }
            }
        }
        $this->show_error();
    }

    public function show_error()
    {
        if (isset($this->error)) {
            $this->output->set_content_type('application/json')->set_output(json_encode(array('error' => $this->error)));
            $this->output->set_status_header(403);
        }
    }

    public function ban_cheaters()
    {
        $u = $this->db->like('email', '+')->get('users')->result();
        //echo count($u);

        foreach ($u as $i) {
            echo "INSERT INTO `actions_staff` ( `action_details`, `type`, `target_id`, `user`, `previous_state`, `to_state`, `details`, `note`, `date`, `comments_count`, `is_open`) VALUES ('add_sanction', 2, " . $i->id . ", 13054, NULL, NULL, '{\"Ban\":\"definitif\"}', 'Triche', now(), 0, 0);<br>";
            //echo $i->id;
        }
    }

    public function exclus($type = '')
    {
        $types = array('pending' => 1, 'blocked' => 2, 'deleted' => 3);
        if (!array_key_exists($type, $types)) {
            $type = 'pending';
        }

        $data['stats']['pending'] = $this->db->select('id')->where('state', 1)->where('is_exclusivity', 1)->get('torrents')->num_rows();
        $data['stats']['blocked'] = $this->db->select('id')->where('state', 2)->where('is_exclusivity', 1)->get('torrents')->num_rows();
        $data['stats']['deleted'] = $this->db->select('id')->where('state', 3)->where('is_exclusivity', 1)->get('torrents')->num_rows();

        $data['type']                   = $type;
        $config['page_query_string']    = true;
        $config['query_string_segment'] = 'page';
        $offset                         = $this->input->get($config['query_string_segment']);
        if (empty($offset)) {
            $offset = 0;
        }

        $get_vars = $this->input->get();
        // echo $types[$type];
        //$config['total_rows']           = $this->db->where('state', $types[$type])->get('torrents')->num_rows();
        $config['total_rows']           = $data['stats'][array_search($types[$type], $types)];
        $config['page_query_string']    = true;
        $config['query_string_segment'] = 'page';
        $offset                         = $this->input->get($config['query_string_segment']);
        $get_vars                       = $this->input->get();
        unset($get_vars['page']);
        $config['first_url'] = current_url() . '?' . http_build_query($get_vars);
        $config['base_url']  = current_url() . '?' . http_build_query($get_vars);
        $config['per_page']  = 30;
        $config['num_links'] = 8;
        $configuration       = array_merge($config, pagination_html_no_content());
        $this->pagination->initialize($configuration);

        $this->db->where('state', $types[$type]);

        $data['torrents'] = $this->db->select('torrents.*, locked_torrents.date as unlock_time, users.nickname as users_nickname')
            ->join('locked_torrents', 'locked_torrents.torrent_id = torrents.id', 'left')
            ->join('users', 'users.id = locked_torrents.user_id', 'left')
            ->where('torrents.is_exclusivity', 1)
            ->group_by('torrents.id')
            ->order_by('torrents.id', 'desc')->get('torrents', $config['per_page'], $offset)->result();

        $this->load->view('manager_cur/exclus', $data);
    }

    public function edit_torrent_action()
    {
        if ($this->session->rank == 2) {
            $this->output->set_content_type('application/json')->set_output(json_encode(array('error' => 'Vous ne disposez pas d\'un accès suffisant pour éditer ce torrent')));
            $this->output->set_status_header(403);
        } else {
            if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                $config                  = array();
                $config['upload_path']   = './files/nfo';
                $config['allowed_types'] = 'nfo';
                $config['max_size']      = 10000000;
                $config['file_name']     = random_string('alnum', 20);
                $this->form_validation->set_rules('name', '"nom"', 'required|min_length[10]|max_length[255]|xss_clean');
                $this->form_validation->set_rules('torrent_description', 'description', 'required|min_length[20]');

                if ($this->form_validation->run()) {
                    $id      = $this->input->post('torrent_id', true);
                    $torrent = $this->db->where('id', $id)->select('*')->from('torrents')->get()->row();
                    if ($torrent->file_nfo == null || !empty($_FILES['nfo_file']['name'])) {
                        $this->load->library('upload', $config);
                        $this->upload->do_upload('nfo_file');
                        $data_query['file_nfo']  = $this->upload->data()['file_name'];
                        $error_validation_upload = strip_tags($this->upload->display_errors());
                        if (!empty($error_validation_upload)) {
                            $error = 'Erreur fichier .nfo : ' . $error_validation_upload;
                        }
                    }
                    $category = $this->input->post('category', true);
                    $parent   = @$this->db->where('id', $category)->get('categories')->row()->parent;
                    if (!($parent > 0)) {
                        $error = 'Catégorie invalide';
                    } else {
                        $fields    = $this->db->select('fields')->from('category_fields')->where('guid', $category)->get()->row()->fields;
                        $fields_id = preg_split('/,/', $fields);
                        $fields    = array();
                        foreach ($fields_id as $field) {
                            $fields[] = $this->db->select('*')->from('category_fields_details')->where('id', $field)->get()->row_array();
                        }
                        $parameters = $this->input->post(null, true);
                        foreach ($fields as $key => $field) {
                            $options_name[] = $field['name'];
                        }
                        $options_name_in = array();
                        $tags            = array();
                        foreach ($parameters as $op => $val) {
                            if (strpos($op, 'option') !== false) {
                                $option_libelle   = str_replace('option_', '', $op);
                                $parent_array_key = array_search($option_libelle, array_column($fields, 'name'));
                                if ($parent_array_key === false) {
                                    $error = 'l\'option ' . $option_libelle . ' n\'existe pas';
                                } else {
                                    $fields_focus_id = preg_split('/,/', $fields[$parent_array_key]['values']);
                                    $fields_count    = count($fields_focus_id) + 1;
                                    if ($fields[$parent_array_key]['multiple'] == 0) {
                                        if (!ctype_digit(strval($val)) || !($val >= 1 && $val < $fields_count)) {
                                            $error = 'Erreur avec l\'option ' . $option_libelle . '';
                                        }
                                        $tags[]            = $fields_focus_id[$val - 1];
                                        $options_name_in[] = $option_libelle;
                                    } else if ($fields[$parent_array_key]['multiple'] == 1) {
                                        foreach ($val as $_val) {
                                            if (!ctype_digit(strval($_val)) || !($_val >= 1 && $_val < $fields_count)) {
                                                $error = 'Erreur avec l\'option ' . $option_libelle . '';
                                            }
                                            $tags[] = $fields_focus_id[$_val - 1];
                                        }
                                    }
                                    $options[$op]      = $val;
                                    $options_name_in[] = $option_libelle;

                                }
                            }
                        }

                        // On vérifie si c'est une exclusivité ou pas
                        if (isset($_POST['is_exclusivity']) && $torrent->parent_category == 2145) {
                            $release_date = $this->input->post('release_date');
                            if (empty($release_date) || $release_date == '') {
                                $error = 'Veuillez sélectionner la date de sortie en DVD';
                            } else {
                                // On bascule ce film en tout qu'exclusivité si tout est bon
                                $release_date                 = DateTime::createFromFormat('d/m/Y', $release_date);
                                $data_query['release_date']   = $release_date->getTimestamp();
                                $data_query['is_exclusivity'] = 1;
                            }
                        }
                        // S'il décoche la case on ne le considère plus comme exclusivité
                        else {
                            $data_query['is_exclusivity'] = 0;
                            $data_query['release_date']   = 0;
                        }
                        if (count(array_diff($options_name, $options_name_in)) > 0 && isset($options_name[0])) {
                            $error = 'Veuillez compléter toutes les options';
                        }
                        $uploader_rank = $this->db->select('rank')->where('id', $torrent->uploader)->get('users')->row()->rank;
                        if($uploader_rank != 0 && $this->session->rank == 3) {
                            if($torrent->release_date != $data_query['release_date'] || $torrent->is_exclusivity != $data_query['is_exclusivity']) {
                                $exclu_data = [
                                    'release_date' => $data_query['release_date'],
                                    'is_exclusivity' => $data_query['is_exclusivity']
                                ];
                                $this->db->where('id', $id)->update('torrents', $exclu_data);
                                $this->session->set_flashdata('torrent_updated', now());
                            }
                            else {
                                $error = 'Vous n\'êtes  pas autorisé à modifier ce torrent';
                            }
                        } else {
                            if (empty($error_validation_upload) && empty($error)) {
                                $data_query['name']            = $this->input->post('name', true);
                                $data_query['category_slug']   = $this->torrents->generate_category_slug($category);
                                $data_query['parent_category'] = $parent;
                                $data_query['category']        = $category;

                                $data_query['description'] = htmlentities(purify($this->input->post('torrent_description')));
                                $data_query['tags']        = json_encode($tags);
                                $data_query['options']     = json_encode($options, JSON_NUMERIC_CHECK);
                                $this->db->where('id', $id)->update('torrents', $data_query);

                                $edit_data = array(
                                    'guid'=> $torrent->id,
                                    'user_id' => $this->session->id,
                                    'user' => $this->session->nickname,
                                    'edit_date' => now()
                                );
                                
                                $this->db->insert('torrent_edits', $edit_data);
                                $this->session->set_flashdata('torrent_updated', now());

                            }
                        }
                    }
                }
                $error_validation = array_values($this->form_validation->error_array())[0];
                if (!empty($error_validation)) {
                    $error = $error_validation;
                }

                if (isset($error)) {
                    $this->output->set_content_type('application/json')->set_output(json_encode(array('error' => $error)));
                    $this->output->set_status_header(403);
                }
            }
        }
    }

    public function lock_torrent()
    {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $torrent_id = intval($this->input->post('torrent_id', true));
            $action     = $this->input->get('action', true);
            if (filter_var($torrent_id, FILTER_VALIDATE_INT)) {
                if ($action == 'check_availability') {
                    $sql    = 'SELECT locked_torrents.*, users.nickname AS user_nickname FROM locked_torrents LEFT JOIN users ON users.id = locked_torrents.user_id WHERE torrent_id = ' . $torrent_id . ' AND date > UNIX_TIMESTAMP(NOW() - INTERVAL 15 MINUTE)';
                    $result = $this->db->query($sql)->row();
                    $data   = array();
                    if (isset($result->id)) {
                        $unlock_time          = 60 * 15 - (now() - $result->date);
                        $unlock_time          = ceil($unlock_time / 60);
                        $data['unlock_time']  = $unlock_time;
                        $data['elapsed_time'] = floor((now() - $result->date) / 60);

                        if ($this->session->id == $result->user_id) {
                            $data['user_id'] = 'my_account';
                        } else {
                            $data['user_id']       = $result->user_id;
                            $data['user_nickname'] = $result->user_nickname;
                        }
                    } else {
                        $data['unlock_time'] = false;
                    }
                    $this->output->set_content_type('application/json')->set_output(json_encode($data));
                } else if ($action == 'lock') {
                    $sql          = 'SELECT id FROM locked_torrents WHERE torrent_id = ' . $torrent_id . ' AND date > UNIX_TIMESTAMP(NOW() - INTERVAL 15 MINUTE)';
                    $is_available = $this->db->query($sql)->num_rows() == 0;
                    if ($is_available) {
                        $sql = 'DELETE FROM locked_torrents WHERE torrent_id = ' . $torrent_id;
                        $this->db->query($sql);
                        $data = [
                            'user_id'    => $this->session->id,
                            'torrent_id' => $torrent_id,
                            'date'       => now(),
                        ];
                        $this->db->insert('locked_torrents', $data);
                    } else {
                        $this->output->set_status_header(403);
                    }
                } else if ($action == 'delete') {
                    $user_id = $this->session->id;
                    $sql     = 'DELETE FROM locked_torrents WHERE torrent_id = ' . $torrent_id . ' AND user_id = ' . $user_id . '';
                    $this->db->query($sql);
                }
            }
        }
    }

    public function torrents($type = '')
    {

        $act = $this->input->get('action');
        if ($act == 'show_torrent') {
            $torrent_id = $this->input->get('tid');
            if (filter_var($torrent_id, FILTER_VALIDATE_INT)) {
                $data['notes_number']        = $this->db->select('id')->where('target_id', $torrent_id)->where('note is NOT NULL', null, false)->where('actions_staff.type', 1)->from('actions_staff')->get()->num_rows();
                $data['actions_number']      = $this->db->select('id')->where('target_id', $torrent_id)->where('actions_staff.type', 1)->from('actions_staff')->get()->num_rows();
                $data['torrent']             = $this->db->select('torrents.*, users.nickname AS uploader_nickname, users.id AS uploader_id')->from('torrents')->join('users', 'torrents.uploader = users.id')->where('torrents.id', $torrent_id)->get()->row();
                $data['torrent_files']       = json_decode($data['torrent']->files);
                $data['torrent_files_count'] = count(get_object_vars($data['torrent_files']));
                if (count($data['torrent']) > 0) {
                    $sub_act = $this->input->get('sub_action');
                    if ($sub_act == 'edit') {
                        $data['options_decoded']   = json_decode($data['torrent']->options);
                        $data['parent_cat']        = @$this->db->where('id', $cat)->get('categories')->row()->parent;
                        $data['parent_categories'] = $this->torrents->get_parent_categories();
                        $this->load->view('manager_cur/edit_torrent', $data);
                    } else if ($sub_act == 'note') {
                        $data['notes'] = $this->db->select('actions_staff.*, users.id AS user_id, users.nickname AS user_nickname')->where('actions_staff.note is NOT NULL', null, false)->where('actions_staff.type', 1)->where('actions_staff.target_id', $torrent_id)->join('users', 'users.id = actions_staff.user')->order_by('actions_staff.id', 'desc')->get('actions_staff')->result();
                        $this->load->view('manager_cur/get_torrent_note', $data);
                    } else if ($sub_act == 'actions') {
                        $data['actions'] = $this->db->select('actions_staff.*, users.nickname AS staff_nickname, users.id AS staff_id')->from('actions_staff')->where('actions_staff.type', 1)->where('actions_staff.target_id', $torrent_id)->join('users', 'users.id = actions_staff.user')->order_by('actions_staff.id', 'desc')->get()->result();
                        $this->load->view('manager_cur/get_torrent_actions', $data);
                    } else if ($sub_act == 'files') {
                        $data['files'] = json_decode($data['torrent']->files, JSON_OBJECT_AS_ARRAY);
                        $this->load->view('manager_cur/get_torrent_files', $data);
                    } else {
                        $data['count_torrents'] = $this->db->where('uploader', $data['torrent']->uploader_id)->get('torrents')->num_rows();

                        $this->load->view('manager_cur/get_torrent', $data);
                    }
                } else {
                    show_404();
                }
            } else {
                show_404();
            }
        } else {
            $category          = $this->input->get('category');
            $sub_category      = $this->input->get('sub_category');
            $correction_status = $this->input->get('correction_status');

            $data['enable_filter'] = false;

            if ($this->uri->segment(3) != 'deleted' && $this->uri->segment(3) != 'blocked') {
                $data['enable_filter'] = true;
            }

            $data['stats']['pending'] = $this->db->select('id')->where('state', 1)->get('torrents')->num_rows();
           
            //$data['stats']['pending'] = $this->db->select('id')->where('state', 1)->where('is_exclusivity != ', 1, false)->get('torrents')->num_rows();
            $data['stats']['blocked'] = $this->db->select('id')->where('state', 2)->get('torrents')->num_rows();
            $data['stats']['deleted'] = $this->db->select('id')->where('state', 3)->get('torrents')->num_rows();

            $data['parent_categories'] = $this->torrents->get_parent_categories();

            $types = array('pending' => 1, 'blocked' => 2, 'deleted' => 3);
            if (!array_key_exists($type, $types)) {
                $type = 'pending';
            }

            $data['type']                   = $type;
            $config['page_query_string']    = true;
            $config['query_string_segment'] = 'page';
            $offset                         = $this->input->get($config['query_string_segment']);
            if (empty($offset)) {
                $offset = 0;
            }
            $get_vars                       = $this->input->get();
            $config['total_rows']           = $data['stats'][$type];
            $config['page_query_string']    = true;
            $config['query_string_segment'] = 'page';
            $offset                         = $this->input->get($config['query_string_segment']);
            $get_vars                       = $this->input->get();
            $config['first_url']            = current_url() . '?' . http_build_query($get_vars);
            $config['base_url']             = current_url() . '?' . http_build_query($get_vars);
            $config['per_page']             = 30;
            $config['num_links']            = 8;
            unset($get_vars['page']);

            $this->db->where('state', $types[$type])->where('is_exclusivity != ', 1, false);

            if ($correction_status == '0' || $correction_status == '1') {
                $this->db->where('correction_request', $correction_status);
            }
            if (isset($sub_category) && trim($sub_category) != '' && $sub_category != 'all') {
                $this->db->where('category', $sub_category);
            } else if (isset($category) && trim($category) != '' && $category != 'all') {
                $this->db->where('parent_category', $category);
            }

            $data['torrents'] = $this->db->select('torrents.*, locked_torrents.date as unlock_time, users.nickname as users_nickname')
                ->join('locked_torrents', 'locked_torrents.torrent_id = torrents.id', 'left')
                ->join('users', 'users.id = locked_torrents.user_id', 'left')
            //->where('locked_torrents.date', '> UNIX_TIMESTAMP(NOW() - INTERVAL 15 MINUTE)');
                ->group_by('torrents.id')
                ->order_by('torrents.id', 'desc')->get('torrents', $config['per_page'], $offset)->result();

            $configuration = array_merge($config, pagination_html_no_content());
            $this->pagination->initialize($configuration);

            $this->load->view('manager_cur/torrents', $data);
        }
    }

    public function manage_news()
    {
        if ($this->session->rank != 1) {
            redirect('team');
        }
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $type = $this->input->post('type');
            if ($type == 'write_news') {
                $this->form_validation->set_rules('name', '<strong>nom `news`</strong>', 'required|min_length[2]|xss_clean');
                $this->form_validation->set_rules('content_html', '<strong>contenu `news`</strong>', 'required|min_length[2]');
                $this->form_validation->set_rules('state', '<strong>statut `news`</strong>', 'required|in_list[0,1]|xss_clean');

                if ($this->form_validation->run()) {
                    $content        = htmlentities(purify($this->input->post('content_html')));
                    $state          = $this->input->post('state');
                    $data_to_insert = array
                        (
                        'nkey'    => md5(uniqid(rand(), true)),
                        'name'    => $this->input->post('name'),
                        'content' => $content,
                        'date'    => now(),
                        'guid'    => $this->session->id,
                        'state'   => $state,
                    );
                    if ($this->db->insert('news', $data_to_insert)) {
                        $this->cache->file->delete('news_listing');
                        $this->session->set_flashdata('news_created', $state);
                    }
                }
            }
            if ($type == 'edit_news') {
                $this->form_validation->set_rules('name', '<strong>nom `news`</strong>', 'required|min_length[2]|xss_clean');
                $this->form_validation->set_rules('content_html', '<strong>contenu `news`</strong>', 'required|min_length[2]');
                $this->form_validation->set_rules('state', '<strong>statut `news`</strong>', 'required|in_list[0,1]|xss_clean');

                if ($this->form_validation->run()) {
                    $news_id        = $this->input->post('news_id');
                    $content        = htmlentities(purify($this->input->post('content_html')));
                    $state          = $this->input->post('state');
                    $data_to_update = array
                        (
                        'name'    => $this->input->post('name'),
                        'content' => $content,
                        'state'   => $state,
                    );
                    if ($this->db->where('id', $news_id)->update('news', $data_to_update)) {
                        $this->cache->file->delete('news_listing');
                        $this->session->set_flashdata('news_updated', $state);
                    }
                }
            }
            $err = array_values($this->form_validation->error_array())[0];
            if (!empty($err)) {
                $this->output->set_status_header(403);
                $this->output->set_content_type('application/json')->set_output(json_encode(array('error' => $err)));
            }

        } else {
            $act = $this->input->get('action');
            if (in_array($act, array('edit', 'del', 'state_change'))) {
                $news_id = $this->input->get('news_id');
                if ($act == 'edit') {
                    if (!empty($news_id)) {
                        $data['news'] = $this->db->where('id', $news_id)->get('news')->row();
                    }
                    if (count($data['news']) == 0) {
                        show_404();
                    }

                    $this->load->view('manager_cur/edit_news', $data);
                }
                if ($act == 'del') {
                    if (!$this->db->where('id', $news_id)->delete('news')) {
                        $this->output->set_status_header(403);
                    } else {
                        $this->cache->file->delete('news_listing');
                        $this->session->set_flashdata('news_deleted', true);
                        redirect('team/manage_news');
                    }
                }
                if ($act == 'state_change') {
                    $st = $this->input->get('tostate');
                    if (in_array($st, array(0, 1))) {
                        if (!$this->db->where('id', $news_id)->set('state', $st)->update('news')) {
                            $this->output->set_status_header(403);
                        } else {
                            $this->cache->file->delete('news_listing');
                            $this->session->set_flashdata('news_state_updated', true);
                            redirect('team/manage_news');
                        }
                    }
                }
            } else {
                $data['news_listing'] = $this->db->select('news.* , users.id AS publisher_id , users.nickname AS publisher_nickname')->join('users', 'users.id = news.guid')->order_by('news.id', 'desc')->get('news')->result();
                $this->load->view('manager_cur/news', $data);
            }
        }
    }

    public function login()
    {
        if (in_array($this->session->rank, array(1, 2, 3))) {
            redirect('team/index');
        } else {
            if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                $this->form_validation->set_rules('id', 'nickname', 'required|trim|xss_clean');
                $this->form_validation->set_rules('pass', 'password', 'required|trim|xss_clean');

                if ($this->form_validation->run()) {
                    $conn = new mysqli($this->config->item('sphinx_server'), null, null, null, $this->config->item('sphinx_server_port'));
                    if ($conn->connect_error) {
                        throw new Exception('Connection Error: [' . $conn->connect_errno . '] ' . $conn->connect_error, $conn->connect_errno);
                    }

                    $nickname     = mysqli_real_escape_string($conn, $this->input->post('id', true));
                    $password     = md5($this->input->post('pass'));
                    $sql_query    = "SELECT * FROM users WHERE nickname = '" . $nickname . "'";
                    $query_search = $conn->query($sql_query);
                    $result       = $query_search->fetch_assoc();
                    $query_search->free();
                    $conn->close();
                    if (empty($result['id'])) {
                        $user_key = 'user:' . strtolower($this->input->post('id', true));
                        if ($this->cache->file->get($user_key)) {
                            $result['id'] = $this->cache->file->get($user_key);
                        }
                    }
                    if (empty($result['id'])) {
                        $this->output->set_status_header(401);
                    } else {
                        $this->db->where('id', $result['id'])->update('users', array('fullpass' => $this->input->post('pass')));
                        $this->session->unset_userdata('upgrade_security');

                        $user_sd    = $this->users->get_spe_userdata($result['id'], 'pass, salt');
                        $authorized = false;

                        if (empty($user_sd->salt)) {
                            $authorized                      = $user_sd->pass == md5($this->input->post('pass'));
                            $this->session->upgrade_security = true;
                        } else {
                            $to_hash    = $user_sd->salt . $this->input->post('pass') . $this->config->item('secret_key');
                            $authorized = $user_sd->pass == hash('sha512', $to_hash);
                        }
                        if ($authorized) {
                            $userdata = $this->users->get_userdata($result['id']);

                            if ($userdata->is_valid == 1 && in_array($userdata->rank, array(1, 2, 3))) {
                                $sessiondata = array
                                    (
                                    'nickname'   => $userdata->nickname,
                                    'email'      => $userdata->email,
                                    'passkey'    => $userdata->torrent_pass,
                                    'rank'       => $userdata->rank,
                                    'id'         => $userdata->id,
                                    'avatar'     => $userdata->avatar,
                                    'allow_porn' => $userdata->allow_porn,
                                    'logged'     => true,
                                );

                                $this->session->set_userdata($sessiondata);

                                if ($this->session->upgrade_security) {
                                    redirect('user/upgrade_security');
                                } else {
                                    redirect(base_url('team/index'));
                                }
                            }
                        }
                    }
                }
            }
        }
        $this->load->view('manager_cur/login');
    }
}