<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Usuarios extends CI_Controller {


	public function index()
	{
        $this->list();   
	}
    public function list()
	{
        $this->login->checkIsAdminSession();

        $query['nomepagina'] = 'Lista de usuários';
		$query['nomesistema'] =  $this->app->nomeSistema();
        $query['logo'] =  $this->app->logo();

        // Configuração da paginação
        $config['base_url'] = site_url('usuarios/list');
        $config['total_rows'] = $this->db->count_all_results('usuarios'); // Total de registros na tabela
        $config['per_page'] = 10; // Número de registros por página
        $config['uri_segment'] = 3; // Segmento da URI que contém o número da página
    
        // Estilo da paginação
        $config['full_tag_open'] = '<ul class="pagination justify-content-center">';
        $config['full_tag_close'] = '</ul>';
        $config['num_tag_open'] = '<li class="page-item">';
        $config['num_tag_close'] = '</li>';
        $config['cur_tag_open'] = '<li class="page-item active"><span class="page-link">';
        $config['cur_tag_close'] = '</span></li>';
        $config['prev_tag_open'] = '<li class="page-item">';
        $config['prev_tag_close'] = '</li>';
        $config['next_tag_open'] = '<li class="page-item">';
        $config['next_tag_close'] = '</li>';
        $config['attributes'] = array('class' => 'page-link');

        $config['first_link'] = 'Inicio';
        $config['last_link'] = 'Final';
    
        $this->pagination->initialize($config);

        $checkUsers = $this->app->checkUserExistInWallet();

        $this->db->select('usuarios.*, financeiro.saldo, financeiro.bonus');
        $this->db->from('usuarios');
        $this->db->join('financeiro', 'usuarios.id = financeiro.usuario', 'left');
        $query['users'] = $this->db->limit($config['per_page'], $this->uri->segment($config['uri_segment']))->get()->result();

        $this->load->view('pages/layout/header', $query);
        $this->load->view('pages/usuarios/list', $query);
        $this->load->view('pages/layout/footer', $query);
	}
    public function create()
	{
        $this->login->checkIsAdminSession();

        $query['nomepagina'] = 'Novo usuário';
		$query['nomesistema'] =  $this->app->nomeSistema();
        $query['logo'] =  $this->app->logo();

        $this->load->view('pages/layout/header', $query);
        $this->load->view('pages/usuarios/create', $query);
        $this->load->view('pages/layout/footer', $query);
	}

    public function historico($id){

        $this->login->checkIsAdminSession();

        $query['nomepagina'] = 'Lista de usuários';
		$query['nomesistema'] =  $this->app->nomeSistema();
        $query['logo'] =  $this->app->logo();

        $this->db->where('id', $id);
        $query['user'] = $this->db->get('usuarios')->row(); 

        $query['historico'] = $this->app->getUsuarioHistoricoJogo($id);

        $query['resultados'] = $this->db->get('games')->result(); 

        $this->db->where('usuario', $id);
        $query['financeiro'] = $this->db->get('financeiro')->row();

        $this->load->view('pages/layout/header', $query);
        $this->load->view('pages/usuarios/cima', $query);
        $this->load->view('pages/usuarios/hist', $query);
        $this->load->view('pages/usuarios/modals', $query);
        $this->load->view('pages/layout/footer', $query);
    }

    public function saques($id){

        $this->login->checkIsAdminSession();

        $query['nomepagina'] = 'Saques do usuário';
		$query['nomesistema'] =  $this->app->nomeSistema();
        $query['logo'] =  $this->app->logo();

        $this->db->where('id', $id);
        $query['user'] = $this->db->get('usuarios')->row(); 

        $query['saques'] = $this->app->getSaquesByUser($id);

        $this->db->where('usuario', $id);
        $query['financeiro'] = $this->db->get('financeiro')->row();

        $query['resultados'] = $this->db->get('games')->result(); 

        $this->load->view('pages/layout/header', $query);
        $this->load->view('pages/usuarios/cima', $query);
        $this->load->view('pages/usuarios/saques', $query);
        $this->load->view('pages/usuarios/modals', $query);
        $this->load->view('pages/layout/footer', $query);
    }
    public function depositos($id){

        $this->login->checkIsAdminSession();

        $query['nomepagina'] = 'Depositos do usuário';
		$query['nomesistema'] =  $this->app->nomeSistema();
        $query['logo'] =  $this->app->logo();

        $this->db->where('id', $id);
        $query['user'] = $this->db->get('usuarios')->row(); 

        $query['saques'] = $this->app->getDepByUser($id);

        $this->db->where('usuario', $id);
        $query['financeiro'] = $this->db->get('financeiro')->row();

        $query['resultados'] = $this->db->get('games')->row(); 

        $this->load->view('pages/layout/header', $query);
        $this->load->view('pages/usuarios/cima', $query);
        $this->load->view('pages/usuarios/depositos', $query);
        $this->load->view('pages/usuarios/modals', $query);
        $this->load->view('pages/layout/footer', $query);
    }
    public function metricas($id){

        $this->login->checkIsAdminSession();

        $query['nomepagina'] = 'Metricas';
		$query['nomesistema'] =  $this->app->nomeSistema();
        $query['logo'] =  $this->app->logo();

        $this->db->where('id', $id);
        $query['user'] = $this->db->get('usuarios')->row(); 

        $query['saques'] = $this->app->getDepByUser($id);

        $this->db->where('usuario', $id);
        $query['financeiro'] = $this->db->get('financeiro')->row();

        $this->db->where('usuario', $id);	
		$query['afiliado'] =  $this->db->get('afiliado')->result();

        $historico_ids = array('Crédito REV', 'Crédito CPA');

        $this->db->select('*');
        $this->db->from('historico');
        $this->db->where('usuario', $id);
        $this->db->where_in('pagina', $historico_ids);
        $query['historico'] = $this->db->get()->result();

        $query['resultados'] = $this->db->get('games')->result(); 

        $this->load->view('pages/layout/header', $query);
        $this->load->view('pages/usuarios/cima', $query);
        $this->load->view('pages/usuarios/metricas', $query);
        $this->load->view('pages/usuarios/modals', $query);
        $this->load->view('pages/layout/footer', $query);
    }
    public function configAfiliado($id){

        $this->login->checkIsAdminSession();

        $query['nomepagina'] = 'Configuração de Afiliado';
		$query['nomesistema'] =  $this->app->nomeSistema();
        $query['logo'] =  $this->app->logo();

        $this->db->where('id', $id);
        $query['user'] = $this->db->get('usuarios')->row(); 

        $this->db->where('usuario', $id);
        $query['financeiro'] = $this->db->get('financeiro')->row();

        $this->db->where('usuario', $id);	
		$query['afiliado'] =  $this->db->get('afiliado')->result();

        $query['resultados'] = $this->db->get('games')->result(); 

        $this->load->view('pages/layout/header', $query);
        $this->load->view('pages/usuarios/cima', $query);
        $this->load->view('pages/usuarios/configAfiliado', $query);
        $this->load->view('pages/usuarios/modals', $query);
        $this->load->view('pages/layout/footer', $query);
    }
    public function edit($id)
	{
        $this->login->checkIsAdminSession();
        $query['nomepagina'] = 'Editar usuário';
		$query['nomesistema'] =  $this->app->nomeSistema();
        $query['logo'] =  $this->app->logo();

        $this->db->where('id', $id);
        $query['user'] = $this->db->get('usuarios')->row(); 

        $this->db->where('usuario', $id);
        $query['financeiro'] = $this->db->get('financeiro')->row();

        $this->load->view('pages/layout/header', $query);
        $this->load->view('pages/usuarios/edit', $query);
        $this->load->view('pages/usuarios/modals', $query);
        $this->load->view('pages/layout/footer', $query);
	}

    public function store()
	{
        $this->login->checkIsAdminSession();
        if ($this->input->post()) {

            $data = $this->input->post();
            $data['senha'] = md5($this->input->post('senha'));

            $this->db->insert('usuarios', $data);
            redirect('Usuarios/list');
        } else {

            $this->load->view('Usuarios/create');
        }
	}
    public function update($id)
	{
        $this->login->checkIsAdminSession();
        if ($id !== null) {

            if ($this->input->post()) {

                $data = $this->input->post();

                $this->db->where('id', $id);
                $this->db->update('usuarios', $data);

                $msg = "Usuário atualizado com sucesso!";
                $this->session->set_flashdata('msg', $msg);
                $this->session->set_flashdata('tipo', "success");

                redirect('Usuarios/list');
            } else {
                $query['user'] = $this->db->get_where('usuarios', array('id' => $id))->row();

                $query['nomepagina'] = 'Editar usuário';
		        $query['nomesistema'] =  $this->app->nomeSistema();
                $query['logo'] =  $this->app->logo();

                $this->load->view('pages/layout/header', $query);
                $this->load->view('pages/usuarios/edit', $query);
                $this->load->view('pages/layout/footer', $query);
            }
        } else {
            redirect('Usuarios/list');
        }
	}
    public function updateSaldo($id)
	{
        $this->login->checkIsAdminSession();
        if ($id !== null) {

            if ($this->input->post()) {

                $saldo = $this->input->post('saldo');

                $query['financeiro'] = $this->db->get_where('financeiro', array('usuario' => $id))->row();

                $this->fiverscans->resetSaldo($id);

                $this->fiverscans->enviarSaldo($id,$saldo);
                
                $insert = array(
                    'transacao_id' => 'INTERNO '.date('dmYHis'),
                    'usuario' => $id,
                    'valor' => $saldo,
                    'tipo' => 'deposito',
                    'data_hora' => date('Y-m-d H:i:s'),
                    'status' => 'processando'
                );
    
                $this->db->insert('transacoes', $insert);

                $data = array(
                    'saldo' => $saldo
                );
                $this->db->where('usuario', $id);
                $this->db->update('financeiro', $data);

                $msg = "O saldo do usuário foi atualizado com sucesso!";
                $this->session->set_flashdata('msg', $msg);
                $this->session->set_flashdata('tipo', "success");

                redirect('Usuarios/historico/'.$id);
            } else {
                $query['user'] = $this->db->get_where('usuarios', array('id' => $id))->row();

                $query['nomepagina'] = 'Editar usuário';
		        $query['nomesistema'] =  $this->app->nomeSistema();
                $query['logo'] =  $this->app->logo();

                $this->load->view('pages/layout/header', $query);
                $this->load->view('pages/usuarios/edit', $query);
                $this->load->view('pages/layout/footer', $query);
            }
        } else {
            redirect('Usuarios/list');
        }
	}
    public function senhaUpdate($id)
	{
        $this->login->checkIsAdminSession();
        if ($id !== null) {

            if ($this->input->post()) {

                $data['senha'] = md5($this->input->post('senha'));

                $this->db->where('id', $id);
                $this->db->update('usuarios', $data);

                $msg = "Usuário atualizado com sucesso!";
                $this->session->set_flashdata('msg', $msg);
                $this->session->set_flashdata('tipo', "success");

                redirect('Usuarios/list');
            } else {
                $query['user'] = $this->db->get_where('usuarios', array('id' => $id))->row();

                $query['nomepagina'] = 'Editar usuário';
		        $query['nomesistema'] =  $this->app->nomeSistema();
                $query['logo'] =  $this->app->logo();

                $this->load->view('pages/layout/header', $query);
                $this->load->view('pages/usuarios/edit', $query);
                $this->load->view('pages/layout/footer', $query);
            }
        } else {
            redirect('Usuarios/list');
        }
	}

    public function buscar()
	{
        $this->login->checkIsAdminSession();

        $query['nomepagina'] = 'Lista de usuários';
		$query['nomesistema'] =  $this->app->nomeSistema();
        $query['logo'] =  $this->app->logo();

		$filtro = $this->input->post('busca');

        $db = "SELECT usuarios.*, financeiro.saldo, financeiro.bonus
        FROM usuarios
        LEFT JOIN financeiro ON usuarios.id = financeiro.usuario
        WHERE usuarios.nome LIKE '%".$filtro."%' OR usuarios.cpf LIKE '%".$filtro."%' OR usuarios.email LIKE '%".$filtro."%';";
        $query['users']  = $this->db->query($db)->result();

        $this->load->view('pages/layout/header', $query);
        $this->load->view('pages/usuarios/list', $query);
        $this->load->view('pages/layout/footer', $query);
	}

    public function saveAfiliado($id)
	{
        $this->login->checkIsAdminSession();

        $data = $this->input->post();
        
        $this->db->where('usuario', $id);
        $this->db->update('afiliado', $data);
        
        $msg = "Configurações atualizadas com sucesso!";
        $this->session->set_flashdata('msg', $msg);
        $this->session->set_flashdata('tipo', "success");
        
        redirect('Usuarios/list');

    } 
    public function rtp($id){
        $game_code = $this->input->post('game_code');
        $call_rtp = $this->input->post('call_rtp');

        $this->fiverscans->geraWin($id,$game_code);

        $msg = "Sessão criada com sucesso!";
        $this->session->set_flashdata('msg', $msg);
        $this->session->set_flashdata('tipo', "success");
        
        redirect('Usuarios/list');
    }
    public function delete($id){

        $this->login->checkIsAdminSession();
        $this->db->where('id', $id);
        $this->db->delete('usuarios');
        echo 'Deleted successfully.';
    } 
}
