<?php

/** Importação de classes  */
use vendor\model\Station;
use vendor\controller\station\StationValidate;

try{

    /** Instânciamento de classes  */
    $Station = new Station();
    $StationValidate = new StationValidate();

    /** Parametros de entrada  */
    $description        = isset($_POST['description'])         ? (string)filter_input(INPUT_POST,'description', FILTER_SANITIZE_SPECIAL_CHARS)         : '';
    $ip                 = isset($_POST['ip'])                  ? (string)filter_input(INPUT_POST,'ip', FILTER_SANITIZE_SPECIAL_CHARS)                  : '';
    $port               = isset($_POST['port'])                ? (int)filter_input(INPUT_POST,'port', FILTER_SANITIZE_NUMBER_INT)                      : '';
    $networkPath        = isset($_POST['network_path'])        ? (string)filter_input(INPUT_POST,'network_path', FILTER_SANITIZE_SPECIAL_CHARS)        : '';
    $connectionName     = isset($_POST['connection_name'])     ? (string)filter_input(INPUT_POST,'connection_name', FILTER_SANITIZE_SPECIAL_CHARS)     : '';
    $connectionId       = isset($_POST['connection_id'])       ? (int)filter_input(INPUT_POST,'connection_id', FILTER_SANITIZE_NUMBER_INT)             : 0;
    $connectionUser     = isset($_POST['connection_user'])     ? (string)filter_input(INPUT_POST,'connection_user', FILTER_SANITIZE_SPECIAL_CHARS)     : '';
    $connectionPassword = isset($_POST['connection_password']) ? (string)filter_input(INPUT_POST,'connection_password', FILTER_SANITIZE_SPECIAL_CHARS) : '';
    $type               = isset($_POST['type'])                ? (string)filter_input(INPUT_POST,'type', FILTER_SANITIZE_SPECIAL_CHARS)                : '';
    $observation        = isset($_POST['observation'])         ? (string)filter_input(INPUT_POST,'observation', FILTER_SANITIZE_SPECIAL_CHARS)         : '';
    $operatingSystem    = isset($_POST['operating_system'])    ? (string)filter_input(INPUT_POST,'operating_system', FILTER_SANITIZE_SPECIAL_CHARS)    : '';
    $cpu                = isset($_POST['cpu'])                 ? (string)filter_input(INPUT_POST,'cpu', FILTER_SANITIZE_SPECIAL_CHARS)                 : '';
    $memory             = isset($_POST['memory'])              ? (string)filter_input(INPUT_POST,'memory', FILTER_SANITIZE_SPECIAL_CHARS)              : '';
    $stationId          = isset($_POST['station_id'])          ? (int)filter_input(INPUT_POST,'station_id', FILTER_SANITIZE_NUMBER_INT)                : 0;
    $clientId           = isset($_POST['client_id'])           ? (int)filter_input(INPUT_POST,'client_id', FILTER_SANITIZE_NUMBER_INT)                 : 0;
    $userId             = isset($_SESSION['USERSID']) && $_SESSION['USERSID'] > 0 ? $_SESSION['USERSID'] : 0;


    /** Validando os campos de entrada */
    $StationValidate->setDescription($description);
    $StationValidate->setIp($ip);
    $StationValidate->setPort($port);
    $StationValidate->setNetworkPath($networkPath);
    $StationValidate->setConnectionName($connectionName);
    $StationValidate->setConnectionId($connectionId);
    $StationValidate->setConnectionUser($connectionUser);
    $StationValidate->setConnectionPassword($connectionPassword);
    $StationValidate->setType($type);
    $StationValidate->setObservation($observation);
    $StationValidate->setOperatingSystem($operatingSystem);
    $StationValidate->setCpu($cpu);
    $StationValidate->setMemory($memory);
    $StationValidate->setStationId($stationId);
    $StationValidate->setClientId($clientId);
    $StationValidate->setUserId($userId);


    /** Verifico a existência de erros */
    if (!empty($StationValidate->getErrors())) {

        /** Preparo o formulario para retorno **/
        $result = [

            'cod' => 0,
            'title' => 'Atenção',
            'message' => '<div class="alert alert-danger" role="alert">'.$StationValidate->getErrors().'</div>',

        ];

    } else {

        /** Efetua um novo cadastro ou salva os novos dados */
        if ($Station->Save($StationValidate->getStationId(), 
                           $StationValidate->getClientId(),
                           $StationValidate->getUserId(),
                           $StationValidate->getDescription(), 
                           $StationValidate->getIp(), 
                           $StationValidate->getPort(), 
                           $StationValidate->getNetworkPath(), 
                           $StationValidate->getConnectionName(), 
                           $StationValidate->getConnectionId(), 
                           $StationValidate->getConnectionUser(), 
                           $StationValidate->getConnectionPassword(), 
                           $StationValidate->getObservation(),
                           $StationValidate->getType(),                             
                           $StationValidate->getOperatingSystem(), 
                           $StationValidate->getCpu(), 
                           $StationValidate->getMemory())){                        

            /** Prepara a mensagem de retorno - sucesso */
            $message = '<div class="alert alert-success" role="alert">'.($StationValidate->getStationId() > 0 ? 'Cadastro atualizado com sucesso' : 'Cadastro efetuado com sucesso').'</div>';

            /** Result **/
            $result = [

                'cod' => 200,
                'title' => 'Atenção',
                'message' => $message,
                'redirect' => '',

            ];

        } else {

            /** Prepara a mensagem de retorno - erro */
            $message = '<div class="alert alert-success" role="alert">'.($StationValidate->getStationId() > 0 ? 'Não foi possível atualizar o cadastro' : 'Não foi possível efetuar o cadastro') .'</div>';

            /** Result **/
            $result = [

                'cod' => 0,
                'title' => 'Atenção',
                'message' => $message,
                'redirect' => '',

            ];

        }

    }

    /** Envio **/
    echo json_encode($result);

    /** Paro o procedimento **/
    exit;

}catch(Exception $exception){

    /** Preparo o formulario para retorno **/
    $result = [

        'cod' => 0,
        'message' => $exception->getMessage(),
        'title' => 'Erro Interno',
        'type' => 'exception',

    ];

    /** Envio **/
    echo json_encode($result);

    /** Paro o procedimento **/
    exit;
}