<?php

/** Importação de classes */

use vendor\model\Log;
use vendor\model\Client;
use vendor\model\Backup;
use vendor\model\Station;
use vendor\model\StationDisk;
use vendor\model\StationFolder;

/** Verifica se o token de acesso é válido */
if ($Main->verifyToken()) {

    /** Instânciamento de classes */
    $Log = new Log();
    $Client = new Client();
    $Backup = new Backup();
    $Station = new Station();
    $StationDisk = new StationDisk();
    $StationFolder = new StationFolder();

    /** Carrega as configurações de paginação */
    $config = $Main->LoadConfigPublic();

    /** Parametros de entrada */
    $clientId = isset($_POST['client_id']) ? (int)filter_input(INPUT_POST, 'client_id', FILTER_SANITIZE_NUMBER_INT) : 0;

    /** Verifica se o cliente possu estações de trabalho para serem listadas  */
    $StationQtde = $Station->Count($clientId);

    /** Pega as informações do cliente */
    $resultClient = $Client->Get($clientId);

    /** Verifico a quantidade de registros localizados */
    if ($StationQtde > 0) { ?>

        <div class="col-lg-12">

            <div class="card shadow mb-12">

                <div class="card-header">

                    <div class="row">

                        <div class="col-md-8">

                            <h5>

                                <?php echo $resultClient->name; ?>

                            </h5>

                        </div>

                    </div>

                </div>

                <div class="card-body">

                    <?php

                    /** Consulta a quantidade de registros */
                    $StationResult = $Station->All($clientId);

                    /** Lista as estações do cliente */
                    foreach ($StationResult as $StationKey => $Result) {
                    ?>

                        <ul class="nav nav-tabs" id="myTab" role="tablist">

                            <?php if ($Result->type == 1) { ?>

                                <li class="nav-item" role="presentation">
                                    <button class="nav-link active" id="backup-tab<?php echo $Result->station_id; ?>" data-toggle="tab" data-target="#backup<?php echo $Result->station_id; ?>" type="button" role="tab" aria-controls="contact" aria-selected="false">Backup</button>
                                </li>

                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="contact-tab<?php echo $Result->station_id; ?>" data-toggle="tab" data-target="#contact<?php echo $Result->station_id; ?>" type="button" role="tab" aria-controls="contact" aria-selected="false">Pastas</button>
                                </li>

                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="log-tab<?php echo $Result->station_id; ?>" data-toggle="tab" data-target="#log<?php echo $Result->station_id; ?>" type="button" role="tab" aria-controls="contact" aria-selected="false">Avisos</button>
                                </li>

                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="profile-tab<?php echo $Result->station_id; ?>" data-toggle="tab" data-target="#profile<?php echo $Result->station_id; ?>" type="button" role="tab" aria-controls="profile" aria-selected="false">Discos</button>
                                </li>

                            <?php } ?>

                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="home-tab<?php echo $Result->station_id; ?>" data-toggle="tab" data-target="#home<?php echo $Result->station_id; ?>" type="button" role="tab" aria-controls="home" aria-selected="true">Detalhes</button>
                            </li>

                        </ul>

                        <div class="tab-content" id="myTabContent">


                            <?php if ($Result->type == 1) { ?>

                                <div class="tab-pane fade active show" id="backup<?php echo $Result->station_id; ?>" role="tabpanel" aria-labelledby="backup-tab<?php echo $Result->station_id; ?>">

                                    <div class="table-responsive">

                                        <table class="table table-bordered table-striped table-hover bg-white shadow-sm table-sm">

                                            <thead>
                                                <tr>
                                                    <th class="text-center">#</th>
                                                    <th class="text-center">Cadastro</th>
                                                    <th class="text-center">Arquivo</th>
                                                    <th class="text-center">Data Arquivo</th>
                                                    <th class="text-center">Hora Arquivo</th>
                                                    <th class="text-center">Dia</th>
                                                    <th class="text-center">Período</th>
                                                    <th class="text-center">Tamanho</th>
                                                    <th class="text-center">Caminho</th>
                                                </tr>
                                            </thead>

                                            <tbody>


                                                <?php

                                                /** Consulta a quantidade de registros */
                                                $BackupResult = $Backup->All($Result->client_id, $Result->station_id);

                                                /** Lista as estações do cliente */
                                                foreach ($BackupResult as $BackupKey => $ResultBackup) {

                                                    /** Pega o tamanho do arquivo sem mascara */
                                                    $size = str_replace(['GB', 'MB', 'KB'], '', $ResultBackup->size);
                                                ?>

                                                    <tr class="<?php echo $size <  '1.048.576' ? 'table-warning text-danger' : ''; ?>">
                                                        <td width="30" align="center"><?php echo $ResultBackup->backup_id; ?></td>
                                                        <td width="160" align="center"><?php echo date('d/m/Y', strtotime($ResultBackup->date_register)); ?></td>
                                                        <td width="160"><?php echo $ResultBackup->file; ?></td>
                                                        <td width="160" align="center"><?php echo date('d/m/Y', strtotime($ResultBackup->file_date)); ?></td>
                                                        <td width="160" align="center"><?php echo date('H:i:s', strtotime($ResultBackup->file_hour)); ?></td>
                                                        <td width="160" align="center"><?php echo $ResultBackup->day; ?></td>
                                                        <td width="160" align="center"><?php echo $ResultBackup->period; ?></td>
                                                        <td width="160" align="center"><?php echo $ResultBackup->size; ?></td>
                                                        <td width="160" align="center"><?php echo $ResultBackup->path; ?></td>
                                                    </tr>

                                                <?php } ?>




                                            </tbody>

                                            <tfoot>
                                                <tr>
                                                    <td colspan="7">


                                                    </td>
                                                </tr>
                                            </tfoot>

                                        </table>

                                    </div>

                                </div>


                                <div class="tab-pane fade" id="contact<?php echo $Result->station_id; ?>" role="tabpanel" aria-labelledby="contact-tab<?php echo $Result->station_id; ?>">

                                    <div class="table-responsive">

                                        <table class="table table-bordered table-striped table-hover bg-white shadow-sm table-sm">

                                            <thead>
                                                <tr>
                                                    <th class="text-center">#</th>
                                                    <th class="text-center">Cadastro</th>
                                                    <th class="text-center">Atualizado</th>
                                                    <th class="text-center">Pasta</th>
                                                    <th class="text-center">Qtde.</th>
                                                    <th class="text-center">Qtde. Atual</th>
                                                </tr>
                                            </thead>

                                            <tbody>


                                                <?php

                                                /** Consulta a quantidade de registros */
                                                $StationFolderResult = $StationFolder->All($Result->station_id);

                                                /** Lista as estações do cliente */
                                                foreach ($StationFolderResult as $StationFolderKey => $ResultFolder) {
                                                ?>

                                                    <tr class="<?php echo ($ResultFolder->amount_of_files_current) > 0 && ($ResultFolder->amount_of_files >  $ResultFolder->amount_of_files_current) ? 'table-warning text-danger' : ''; ?>">
                                                        <td width="30" align="center"><?php echo $ResultFolder->station_folder_id; ?></td>
                                                        <td width="160" align="center"><?php echo date('d/m/Y H:i:s', strtotime($ResultFolder->date_register)); ?></td>
                                                        <td width="160" align="center"><?php echo !empty($ResultFolder->last_update) ? date('d/m/Y H:i:s', strtotime($ResultFolder->last_update)) : null; ?></td>
                                                        <td width="160"><?php echo $ResultFolder->folder_path; ?></td>
                                                        <td width="160" align="center"><?php echo $ResultFolder->amount_of_files; ?></td>
                                                        <td width="160" align="center"><?php echo $ResultFolder->amount_of_files_current; ?></td>
                                                    </tr>

                                                <?php } ?>




                                            </tbody>

                                            <tfoot>
                                                <tr>
                                                    <td colspan="7">


                                                    </td>
                                                </tr>
                                            </tfoot>

                                        </table>

                                    </div>


                                </div>


                                <div class="tab-pane fade" id="log<?php echo $Result->station_id; ?>" role="tabpanel" aria-labelledby="log-tab<?php echo $Result->station_id; ?>">

                                    <div class="table-responsive">

                                        <table class="table table-bordered table-striped table-hover bg-white shadow-sm table-sm">

                                            <thead>
                                                <tr>
                                                    <th class="text-center">#</th>
                                                    <th class="text-center">Postagem</th>
                                                    <th class="text-center">Hora</th>
                                                    <th class="text-center"></th>
                                                </tr>
                                            </thead>

                                            <tbody>


                                                <?php

                                                /** Consulta a quantidade de registros */
                                                $LogResult = $Log->All($Result->client_id, $Result->station_id);

                                                /** Lista as estações do cliente */
                                                foreach ($LogResult as $LogKey => $ResultLog) {
                                                ?>

                                                    <tr>
                                                        <td width="40" align="center"><?php echo $ResultLog->log_id; ?></td>
                                                        <td align="center"><?php echo date('d/m/Y', strtotime($ResultLog->date_post)); ?></td>
                                                        <td align="center"><?php echo date('H:i:s', strtotime($ResultLog->date_post)); ?></td>
                                                        <td width="20" align="center"><button class="btn btn-light btn-view" id="btn-<?php echo $ResultLog->log_id; ?>" data-target="show-<?php echo $ResultLog->log_id; ?>"><i class="fas fa-eye"></i></button></td>
                                                    </tr>
                                                    <tr>
                                                        <td colspan="4" class="display-none" id="show-<?php echo $ResultLog->log_id; ?>">

                                                            <table class="table table-bordered table-striped table-hover bg-white shadow-sm table-sm">

                                                                <thead>
                                                                    <tr>
                                                                        <th class="text-center">Descrição</th>
                                                                    </tr>
                                                                </thead>

                                                                <tbody>
                                                                    <?php
                                                                    $log = json_decode($ResultLog->file);
                                                                    foreach ((array)$log->warning as $data) { ?>

                                                                        <tr>
                                                                            <td><?php echo $data; ?></td>
                                                                        </tr>
                                                                    <?php
                                                                    }
                                                                    ?>
                                                                </tbody>
                                                            </table>
                                                        </td>
                                                    </tr>

                                                <?php } ?>




                                            </tbody>

                                            <tfoot>
                                                <tr>
                                                    <td colspan="4">


                                                    </td>
                                                </tr>
                                            </tfoot>

                                        </table>

                                    </div>

                                </div>

                                <div class="tab-pane fade" id="profile<?php echo $Result->station_id; ?>" role="tabpanel" aria-labelledby="profile-tab<?php echo $Result->station_id; ?>">

                                    <div class="table-responsive">

                                        <table class="table table-bordered table-striped table-hover bg-white shadow-sm table-sm">

                                            <thead>
                                                <tr>
                                                    <th class="text-center">#</th>
                                                    <th class="text-center">Cadastro</th>
                                                    <th class="text-center">Descrição</th>
                                                    <th class="text-center">Capacidade</th>
                                                    <th class="text-center">Utilizados</th>
                                                    <th class="text-center">Disponível</th>
                                                    <th class="text-center">%</th>
                                                </tr>
                                            </thead>

                                            <tbody>


                                                <?php

                                                /** Consulta a quantidade de registros */
                                                $StationDiskResult = $StationDisk->All($Result->station_id);

                                                /** Lista as estações do cliente */
                                                foreach ($StationDiskResult as $StationDiskKey => $ResultDisk) {
                                                ?>

                                                    <tr>
                                                        <td width="30" align="center"><?php echo $ResultDisk->station_disk_id; ?></td>
                                                        <td width="160" align="center"><?php echo date('d/m/Y', strtotime($ResultDisk->registration_date)); ?></td>
                                                        <td width="160"><?php echo $ResultDisk->description; ?></td>
                                                        <td width="160"><?php echo $ResultDisk->capacity; ?></td>
                                                        <td width="160"><?php echo $ResultDisk->used; ?></td>
                                                        <td width="160"><?php echo $ResultDisk->available; ?></td>
                                                        <td width="160" class="text-center"><?php echo $ResultDisk->available_percentage; ?>%</td>
                                                    </tr>

                                                <?php } ?>




                                            </tbody>

                                            <tfoot>
                                                <tr>
                                                    <td colspan="7">

                                                        <div class="row" style="width: 99%;">

                                                            <?php

                                                            /** Consulta a quantidade de registros */
                                                            $StationDiskResult = $StationDisk->All($Result->station_id);

                                                            /** Lista as estações do cliente */
                                                            foreach ($StationDiskResult as $StationDiskKey => $ResultDisk) {

                                                                /** Trata os valores para montar o grafico */
                                                                //$capacity  = (float)trim( str_replace('GB', '', $ResultDisk->capacity) );
                                                                $used      = (float)trim(str_replace('GB', '', $ResultDisk->used));
                                                                $available = (float)trim(str_replace('GB', '', $ResultDisk->available));
                                                            ?>


                                                                <div class="col-xl-6 col-lg-6">

                                                                    <div class="card shadow mb-4">

                                                                        <!-- Card Header - Dropdown -->
                                                                        <div class="card-header py-3">
                                                                            <h6 class="m-0 font-weight-bold text-primary"><?php echo $ResultDisk->description; ?> <?php echo $ResultDisk->capacity; ?></h6>
                                                                        </div>

                                                                        <!-- Card Body -->
                                                                        <div class="card-body">
                                                                            <div class="chart-pie p-4">
                                                                                <div class="chartjs-size-monitor">
                                                                                    <div class="chartjs-size-monitor-expand">
                                                                                        <div class=""></div>
                                                                                    </div>
                                                                                    <div class="chartjs-size-monitor-shrink">
                                                                                        <div class=""></div>
                                                                                    </div>
                                                                                </div>
                                                                                <canvas id="myPieChart<?php echo $ResultDisk->station_disk_id; ?>" style="display: block; height: 229px; width: 522px;" width="652" height="286" class="chartjs-render-monitor"></canvas>
                                                                            </div>
                                                                        </div>

                                                                    </div>

                                                                </div>

                                                                <script type="text/javascript">
                                                                    /** Operações ao carregar a página */
                                                                    $(document).ready(function() {

                                                                        chartPieentries('myPieChart<?php echo $ResultDisk->station_disk_id; ?>', ['Utilizados', 'Disponível'], ['<?php echo $used; ?>', '<?php echo $available; ?>']);

                                                                    });
                                                                </script>



                                                            <?php } ?>

                                                        </div>

                                                    </td>
                                                </tr>
                                            </tfoot>

                                        </table>

                                    </div>

                                </div>

                            <?php } ?>

                            <div class="tab-pane fade" id="home<?php echo $Result->station_id; ?>" role="tabpanel" aria-labelledby="home-tab<?php echo $Result->station_id; ?>">

                                <form id="frmStation<?php echo $Result->station_id; ?>">

                                    <div class="table-responsive">

                                        <table class="table table-bordered table-striped table-hover bg-white shadow-sm table-sm">

                                            <tbody>

                                                <tr>
                                                    <td align="right" width="160">Descrição</td>
                                                    <td><input type="text" class="form-control form-control" maxlength="100" id="description" name="description" value="<?php echo $Result->description; ?>" /></td>
                                                </tr>

                                                <tr>
                                                    <td align="right" width="160">IP</td>
                                                    <td><input type="text" class="form-control form-control" maxlength="20" id="ip" name="ip" value="<?php echo $Result->ip; ?>" /></td>
                                                </tr>

                                                <tr>
                                                    <td align="right" width="160">Porta</td>
                                                    <td><input type="text" class="form-control form-control date" maxlength="20" id="port" name="port" value="<?php echo $Result->port; ?>" /></td>
                                                </tr>

                                                <tr>
                                                    <td align="right" width="160">Caminho na rede</td>
                                                    <td><input type="text" class="form-control form-control" maxlength="160" id="network_path" name="network_path" value="<?php echo $Result->network_path; ?>" /></td>
                                                </tr>

                                                <tr>
                                                    <td align="right" width="160">Software de conexão</td>
                                                    <td><input type="text" class="form-control form-control" maxlength="100" id="connection_name" name="connection_name" value="<?php echo $Result->connection_name; ?>" /></td>
                                                </tr>

                                                <tr>
                                                    <td align="right" width="160">ID da conexão</td>
                                                    <td><input type="text" class="form-control form-control" maxlength="20" id="connection_id" name="connection_id" value="<?php echo $Result->connection_id; ?>" /></td>
                                                </tr>

                                                <tr>
                                                    <td align="right" width="160">Usuário da Conexão</td>
                                                    <td><input type="text" class="form-control form-control" maxlength="30" id="connection_user" name="connection_user" value="<?php echo $Result->connection_user; ?>" /></td>
                                                </tr>

                                                <tr>
                                                    <td align="right" width="160">Senha da Conexão</td>
                                                    <td><input type="text" class="form-control form-control" maxlength="30" id="connection_password" name="connection_password" value="<?php echo $Result->connection_password; ?>" /></td>
                                                </tr>

                                                <tr>
                                                    <td align="right" width="160">Tipo</td>
                                                    <td>
                                                        <select class="form-control form-control" id="type" name="type">
                                                            <option value="S" <?php echo (int)$Result->type == 1 ? 'selected' : ''; ?>>Servidor</option>
                                                            <option value="N" <?php echo (int)$Result->type == 2 ? 'selected' : ''; ?>>Estação</option>
                                                        </select>
                                                    </td>
                                                </tr>

                                                <tr>
                                                    <td align="right" width="160">Observação</td>
                                                    <td><textarea class="form-control form-control" cols="50" rows="5" id="observation" name="observation"><?php echo $Result->observation; ?></textarea></td>
                                                </tr>

                                                <tr>
                                                    <td align="right" width="160">Sistema Operacional</td>
                                                    <td><input type="text" class="form-control form-control" maxlength="300" id="operating_system" name="operating_system" value="<?php echo $Result->operating_system; ?>" /></td>
                                                </tr>

                                                <tr>
                                                    <td align="right" width="160">CPU</td>
                                                    <td><textarea class="form-control form-control" cols="50" rows="5" id="cpu" name="cpu"><?php echo htmlspecialchars($Result->cpu); ?></textarea></td>
                                                </tr>

                                                <tr>
                                                    <td align="right" width="160">Memória</td>
                                                    <td><textarea class="form-control form-control" cols="50" rows="5" id="memory" name="memory"><?php echo $Result->memory; ?></textarea></td>
                                                </tr>


                                            </tbody>

                                            <tfoot>
                                                <tr>
                                                    <td colspan="2" align="right">

                                                        <button type="button" class="btn btn-success btn-sm" onclick="sendForm('#frmStation<?php echo $Result->station_id; ?>', '', true, '', 0, '', '<?php echo $Result->station_id > 0 ? 'Atualizando cadastro' : 'Cadastrando novo Statione'; ?>', 'random', 'circle', 'sm', true)" data-toggle="tooltip" data-placement="left" title="Salvar dados do Statione">

                                                            <i class="fas fa-save mr-1"></i>Salvar

                                                        </button>

                                                    </td>
                                                </tr>
                                            </tfoot>

                                        </table>


                                        <input type="hidden" name="TABLE" value="station" />
                                        <input type="hidden" name="ACTION" value="station_save" />
                                        <input type="hidden" name="FOLDER" value="action" />
                                        <input type="hidden" name="station_id" value="<?php echo $Result->station_id; ?>" />
                                        <input type="hidden" name="client_id" value="<?php echo $Result->client_id; ?>" />

                                    </div>

                                </form>

                            </div>

                        </div>


                    <?php } ?>



                </div>

            </div>

        </div>

        <script type="text/javascript">
            /** Carrega as mascaras dos campos inputs */
            $(document).ready(function(e) {

                loadMask();

                $(".btn-view").click(function() {

                    $("#" + $(this).attr('data-target')).toggle();

                });

            });
        </script>

    <?php

    } else { //Caso não tenha registros cadastrados, informo 
    ?>

        <div class="col-lg-12">

            <!-- Informo -->
            <div class="card shadow mb-12">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Atenção</h6>
                </div>
                <div class="card-body">

                    <div class="row">

                        <div class="col-md-8 text-right">
                            <h4>Não foram cadastradas estações.</h4>
                        </div>

                        <div class="col-md-4 text-right">

                            <button type="button" class="btn btn-success btn-sm" onclick="request('FOLDER=view&TABLE=station&ACTION=station_form', '#loadContent', true, '', '', '', 'Preparando formulário', 'blue', 'circle', 'sm', true)">

                                <i class="fas fa-plus-circle mr-1"></i>Cadastrar nova estação

                            </button>

                        </div>

                    </div>

                </div>
            </div>

        </div>

<?php }

    /** Caso o token de acesso seja inválido, informo */
} else {

    /** Informa que o usuário precisa efetuar autenticação junto ao sistema */
    $authenticate = true;

    /** Informo */
    throw new InvalidArgumentException('Sua sessão expirou é necessário efetuar nova autenticação junto ao sistema', 0);
}
