<?php

include '../c_leitura.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . "sealed" . DIRECTORY_SEPARATOR . "autoload.php";
include ('../db.php');

function getApoios($id_user) {
    $apoio = array();
    $resultSocios = mysql_query("SELECT id FROM user "
            . " WHERE id_apoio = $id_user "
            . " AND status = 1");
    $apoio[] = $id_user;
    while ($rowSocios = mysql_fetch_array($resultSocios)) {
        $apoio[] = $rowSocios['id'];
    }
    return $apoio;
}

$argAction = array(
    'action' => array(
        'filter' => FILTER_VALIDATE_REGEXP,
        'options' => array("regexp" => "/^(tabletsVirtuais|Jogadores)$/")
    )
);

$argsPost = array(
    'start' => array(
        'filter' => FILTER_SANITIZE_STRING
    ),
    'length' => array(
        'filter' => FILTER_SANITIZE_STRING
    ),
    'order' => array(
        'filter' => FILTER_SANITIZE_STRING,
        'flags' => FILTER_REQUIRE_ARRAY,
    ),
    'dir' => array(
        'filter' => FILTER_SANITIZE_STRING,
        'flags' => FILTER_REQUIRE_ARRAY,
    ),
    'column' => array(
        'filter' => FILTER_SANITIZE_STRING,
        'flags' => FILTER_REQUIRE_ARRAY,
    ),
    'ponto' => array(
        'filter' => FILTER_SANITIZE_STRING
    ),
    'cliente' => array(
        'filter' => FILTER_SANITIZE_STRING
    )
);

$inputPOST = filter_input_array(INPUT_POST, $argsPost);
$inputAction = filter_input_array(INPUT_POST, $argAction);

$ordercolumn = NULL;
$orderdir = NULL;
$order = NULL;


switch ($inputAction['action']) {
    case "tabletsVirtuais":
        $data = array();
        $like = NULL;
        $sqlCliente = NULL;

        if (isset($_POST['search']['value']) && !empty($_POST['search']['value'])) {
            $like = " AND ponto.nome LIKE '%" . $_POST['search']['value'] . "%' ";
        } elseif (isset($inputPOST['ponto']) && !empty($inputPOST['ponto'])) {
            $like = " AND ponto.nome LIKE '%" . $inputPOST['ponto'] . "' ";
        }

        if (isset($inputPOST['cliente']) && !empty($inputPOST['cliente'])) {
            $sqlCliente = " AND ponto.id_apoio = " . $inputPOST['cliente'];
        }

        if (!empty($inputPOST['order'][0]['dir'])) {
            $column = $inputPOST['order'][0]['column'];
            $orderdir = $inputPOST['order'][0]['dir'];
            $column+=1;
            if ($column == 1) {
                $order = " order by cadastro $orderdir";
            } elseif ($column == 2) {
                $order = " order by 3 $orderdir";
            } else {
                $order = " order by $column $orderdir";
            }
        }

        if ($_SESSION['UsuarioNivel'] == 1) {
            $rowUserCount = mysql_query("SELECT tablet_virtual.id"
                    . " FROM tablet_virtual INNER JOIN ponto "
                    . " ON tablet_virtual.id_apoio = ponto.id  "
                    . " $sqlCliente"
                    . " $like");
            $num_rows_total = mysql_num_rows($rowUserCount);

            $resultUser = mysql_query("SELECT "
                    . " DATE_FORMAT(tablet_virtual.last_update, '%d/%m/%Y %H:%i:%s') "
                    . " AS cadastro2,tablet_virtual.status,"
                    . " tablet_virtual.id,ponto.nome ponto,"
                    . " tablet_virtual.last_update cadastro,tablet_virtual.ligado,"
                    . " tablet_virtual.ativo, ponto.id id_ponto "
                    . " FROM tablet_virtual INNER JOIN ponto "
                    . " ON tablet_virtual.id_apoio = ponto.id "
                    . " WHERE 1=1"
                    . " $sqlCliente"
                    . " $like"
                    . " $order"
                    . " LIMIT " . $inputPOST['start'] . " ," . $inputPOST['length']);
        } elseif ($_SESSION['UsuarioNivel'] == 3) {
            $id_user = $_SESSION['UsuarioID'];
            $apoios = getApoios($id_user);

            $rowUserCount = mysql_query("SELECT tablet_virtual.id"
                    . " FROM tablet_virtual INNER JOIN ponto "
                    . " ON tablet_virtual.id_apoio = ponto.id"
                    . " WHERE  "
                    . " ponto.id_apoio IN (" . implode(',', $apoios) . ')'
                    . " $sqlCliente"
                    . " $like");
            $num_rows_total = mysql_num_rows($rowUserCount);

            $resultUser = mysql_query("SELECT "
                    . " DATE_FORMAT(tablet_virtual.last_update, '%d/%m/%Y %H:%i:%s') "
                    . " AS cadastro2,tablet_virtual.status,"
                    . " tablet_virtual.id,ponto.nome ponto,"
                    . " tablet_virtual.last_update cadastro,tablet_virtual.ligado,"
                    . " tablet_virtual.ativo, ponto.id id_ponto "
                    . " FROM tablet_virtual INNER JOIN ponto ON tablet_virtual.id_apoio = ponto.id"
                    . " WHERE  "
                    . " ponto.id_apoio IN (" . implode(',', $apoios) . ')'
                    . " $sqlCliente"
                    . " $like"
                    . " $order"
                    . " LIMIT " . $inputPOST['start'] . " ," . $inputPOST['length'] . " ");
        } elseif ($_SESSION['UsuarioNivel'] == 4) {

            $id_user = $_SESSION['UsuarioID'];

            $rowUserCount = mysql_query("SELECT tablet_virtual.id"
                    . " FROM tablet_virtual INNER JOIN ponto ON tablet_virtual.id_apoio = ponto.id"
                    . " WHERE  "
                    . " ponto.id_apoio IN (" . $id_user . ')'
                    . " $sqlCliente"
                    . " $like");
            $num_rows_total = mysql_num_rows($rowUserCount);

            $resultUser = mysql_query("SELECT "
                    . " DATE_FORMAT(tablet_virtual.last_update, '%d/%m/%Y %H:%i:%s') "
                    . " AS cadastro2,tablet_virtual.status,"
                    . " tablet_virtual.id,ponto.nome ponto,"
                    . " tablet_virtual.last_update cadastro,tablet_virtual.ligado,"
                    . " tablet_virtual.ativo, ponto.id id_ponto "
                    . " FROM tablet_virtual INNER JOIN ponto ON tablet_virtual.id_apoio = ponto.id"
                    . " WHERE  "
                    . " ponto.id_apoio = " . $id_user . " "
                    . " $sqlCliente"
                    . " $like"
                    . " $order"
                    . " LIMIT " . $inputPOST['start'] . " ," . $inputPOST['length'] . " ");
        } elseif (($_SESSION['UsuarioNivel'] == 5) OR ( $_SESSION['UsuarioNivel'] == 6)) {
            $rowUserCount = mysql_query("SELECT tablet_virtual.id"
                    . " FROM tablet_virtual INNER JOIN ponto "
                    . " ON tablet_virtual.id_apoio = ponto.id"
                    . " WHERE "
                    . " ponto.id_apoio IN (" . $_SESSION['UsuarioID'] . ')'
                    . " $sqlCliente"
                    . " $like");
            $num_rows_total = mysql_num_rows($rowUserCount);

            $resultUser = mysql_query("SELECT "
                    . " DATE_FORMAT(tablet_virtual.last_update, '%d/%m/%Y %H:%i:%s') "
                    . " AS cadastro2,tablet_virtual.status,"
                    . " tablet_virtual.id,ponto.nome ponto,"
                    . " tablet_virtual.last_update cadastro,tablet_virtual.ligado,"
                    . " tablet_virtual.ativo, ponto.id id_ponto "
                    . " FROM tablet_virtual INNER JOIN ponto ON tablet_virtual.id_apoio = ponto.id "
                    . " WHERE "
                    . " ponto.id_apoio = " . $_SESSION['UsuarioID']
                    . " $sqlCliente"
                    . " $like"
                    . " $order"
                    . " LIMIT " . $inputPOST['start'] . " ," . $inputPOST['length'] . " ");
        }


        $num_rows = mysql_num_rows($resultUser);
        if ($num_rows > 0) {
            while ($row = mysql_fetch_array($resultUser)) {
                if ($_SESSION['UsuarioNivel'] != 5) {
                    $link = '<a href="detalhes_tablet_virtual.php?id=' . $row['id'] . '" data-toggle="modal" style="font-weight:bold" data-target="#myModalDetalhesTablet2' . $row['id'] . '">Tablet #' . $row['id'] . '</a>';
                } else {
                    $link = $row['id'];
                }
                $row[1] = $link;

                $row[2] = $row['ponto'];

                $status = $row['status'] == 1 ? '<span style="color:red;font-weight:normal">Em uso</span>' : '<span style="color:black;font-weight:normal">Disponível</span>';
                $row[3] = $status;

                if ($_SESSION['UsuarioNivel'] == 1 && $row['status'] != 1) {
                    $row[4] = ' <a id="virtual_id_' . $row['id'] . '"  href="javascript:void(0);" data-id="' . $row['id'] . '"  data-toggle="modal" data-target="#deletetabletmodal" class="" style="color:red" role="button">Excluir</a>';
                } else {
                    $row[4] = '';
                }

                $painel.= '<div id="myModalDetalhesTablet2' . $row['id'] . '" class="modal fade">'
                        . '<div class="modal-dialog modal-lg">'
                        . ' <div class="modal-content modal-lg">'
                        . ' </div>'
                        . ' </div>'
                        . '</div>';
                $data[] = $row;
            }
        }
        $json_data = array(
            "draw" => intval($params['draw']),
            "recordsTotal" => intval($num_rows_total),
            "recordsFiltered" => intval($num_rows_total),
            "data" => $data, // total data array
            "painel" => $painel
        );
        echo json_encode($json_data);  // send data as json format
        break;

    case "Jogadores":
        $id_user = $_SESSION['UsuarioID'];
        if (!empty($_POST['search']['value'])) {
            if ($_SESSION['UsuarioNivel'] == 1) {
                $like = " AND username LIKE '%" . $_POST['search']['value'] . "%'";
            } elseif ($_SESSION['UsuarioNivel'] == 3 || $_SESSION['UsuarioNivel'] == 6) {
                 $like = " AND user_id = $id_user AND username LIKE '%" . $_POST['search']['value'] . "%'";
            }
        }
        if (!empty($inputPOST['order'][0]['dir'])) {
            $column = $inputPOST['order'][0]['column'];
            $orderdir = $inputPOST['order'][0]['dir'];
            $column+=1;
            if ($column == 1) {
                $order = " order by cadastro $orderdir";
            } elseif ($column == 2) {
                $order = " order by 3 $orderdir";
            } else {
                $order = " order by $column $orderdir";
            }
        }
        try {
            if ($_SESSION['UsuarioNivel'] == 1) {
                $num_rows_total = jogadorDAO::getJogadores_count(" 1 = 1 " . $like . " AND id_ponto <> ''");
                $args = " 1 = 1 AND p.status = 1 " . $like . $order . " LIMIT " . $inputPOST['start'] . " ," . $inputPOST['length'];
            } elseif ($_SESSION['UsuarioNivel'] == 3 || $_SESSION['UsuarioNivel'] == 6) {
                $num_rows_total = jogadorDAO::getJogadores_count(" user_id = $id_user " . $like . " AND id_ponto <> ''");
                $args = " user_id = $id_user AND p.status = 1" . $like . $order . " LIMIT " . $inputPOST['start'] . " ," . $inputPOST['length'];
            }
            if ($num_rows_total > 0) {
                $rows = jogadorDAO::getJogadores($args);
                foreach ($rows as $row) {
                    $link = $row['id'];
                    $link_remover_creditos = null;

                    $rowm[0] = $row['atualizacao'];
                    $current = date('Y-m-d H:i:s');
                    $ultimo_contato = date('Y-m-d H:i:s', strtotime($row['data']));
                    $decorrido = strtotime($current) - strtotime($ultimo_contato);

                    $status = $decorrido < 10 ? "<span style='color:green'>ONLINE</span>" : "<span style='color:red'>OFFLINE</span>";

                    $rowm[1] = $row['username'];

                    $rowm[2] = $row['nome'];

                    $rowm[3] = 'R$ ' . FUNCOES::formatoDecimalHTML(($row['creditos'] / 100));

                    $rowm[4] = $row['ponto'];

                    $rowm[5] = $status;

                    $idprod = "'" . $row['idprod'] . "'";
                    $link_remover_creditos = ' <a class="btn btn-danger" id="btnremoverCreditosTablet" onclick="fRemoverCreditos(' . $idprod . ', 2 , false , ' . $row['id'] . ');" title="Remover Créditos" role="button"><i class="fa fa-download fa-fw"></i></a>';
                    if ($decorrido < 10 && !empty($row['idprod'])) {
                        $rowm[6] = " <td class='center' style='min-width:166px; width:166px'>"
                                . ' <a class="btn btn-info btn-bg" data-login="" data-id="' . $row['id'] . '" data-nome="" data-toggle="modal" data-target="#newjogador" role="button"><i class="fa fa-edit fa-fw" title="Alterar dados de acesso"></i></a>'
                                . ' <a class="btn btn-primary" data-toggle="modal" data-login="Inserir Créditos" data-nome="set_creditos" data-target="#insertcreditojogadormodal" data-id="' . $row['id'] . '" title="Inserir Créditos" role="button"><i class="fa fa-upload fa-fw"></i></a>'
                                . $link_remover_creditos
                                . ' <a id="virtual_id_' . $row['id'] . '"  href="javascript:void(0);" data-id="' . $row['id'] . '"  data-toggle="modal" data-target="#deletetabletmodal" class=\'btn btn-danger\' role=\'button\'><i class=\'fa fa-times fa-fw\'></i></a></td>';
                    } else {
                        $rowm[6] = " <td class='center' style='min-width:166px; width:166px'>"
                                . ' <a class="btn btn-info btn-bg" data-login="" data-id="' . $row['id'] . '" data-nome="" data-toggle="modal" data-target="#newjogador" role="button"><i class="fa fa-edit fa-fw" title="Alterar dados de acesso"></i></a>'
                                . ' <a id="virtual_id_' . $row['id'] . '"  href="javascript:void(0);" data-id="' . $row['id'] . '"  data-toggle="modal" data-target="#deletetabletmodal" class=\'btn btn-danger\' role=\'button\'><i class=\'fa fa-times fa-fw\'></i></a></td>';
                    }
                    $painel.= '<div id="myModalDetalhesTablet2' . $row['id'] . '" class="modal fade">'
                            . '<div class="modal-dialog modal-lg">'
                            . ' <div class="modal-content modal-lg">'
                            . ' </div>'
                            . ' </div>'
                            . '</div>';

                    $data[] = $rowm;
                }
            } else {
                $data['error'] = null;
            }
            // }
            $json_data = array(
                "draw" => intval($params['draw']),
                "recordsTotal" => intval($num_rows_total),
                "recordsFiltered" => intval($num_rows_total),
                "data" => $data, // total data array
                "painel" => $painel
            );
            echo json_encode($json_data);  // send data as json format
        } catch (Exception $err) {
            FUNCOES::logMsg($err->getMessage(), 'error', 'error.log');
        }


        break;
}