<?php
/**
* Classe StationFolder.class.php
* @filesource
* @autor		Kenio de Souza
* @copyright	Copyright 2024 - Souza Consultoria Tecnológica
* @package		vendor
* @subpackage	model
* @version		1.0
* @date			07/08/2024
*/


/** Defino o local onde esta a classe */
namespace vendor\model;

class StationFolder
{
	/** Declaro as vaiavéis da classe */
	private $connection = null;
	private $sql = null;
	private $stmt = null;
	private $start = null;
	private $max = null;
	private $limit = null;
	private $stationFolderId = null;
	private $stationId = null;
	private $folderPath = null;
	private $amountOfFiles = null;
	private $amountOfFilesCurrent = null;
	private $dateRegister = null;
	private $lastUpdate = null;
	private $field = null;
	private $errors = [];
	private $lastId = null;

	/** Construtor da classe */
	function __construct()
	{
		/** Cria o objeto de conexão com o banco de dados */
		$this->connection = new Mysql();
	}

	/** Carrega os campos de uma tabela */
	public function Describe()
	{

		/** Consulta SQL */
		$this->sql = "describe station_folder";

		/** Preparo o SQL para execução */
		$this->stmt = $this->connection->connect()->prepare($this->sql);

		/** Executo o SQL */
		$this->stmt->execute();

		/** Retorno o resultado */
		$this->field = $this->stmt->fetchAll(\PDO::FETCH_OBJ);

		/** Declara o objeto */
		$resultDescribe = new \stdClass();
		$Field = '';

		/** Lista os campos da tabela para objetos */
		foreach($this->field as $UsersKey => $Result){

			/** Pega o nome do Field/Campo */
			$Field = $Result->Field;

			/** Carrega os objetos como null */
			$resultDescribe->$Field = null;

		}

		/** Retorna os campos declarados como vazios */
		return $resultDescribe;

	}

	/** Lista os registros do banco de dados com limitação */
	public function Get(int $stationFolderId)
	{

		/** Parametros de entrada */
		$this->stationFolderId = $stationFolderId;

		/** Consulta SQL */
		$this->sql = 'select * from station_folder  
					  where client_id = :client_id';

		/** Preparo o SQL para execução */
		$this->stmt = $this->connection->connect()->prepare($this->sql);

		/** Preencho os parâmetros do SQL */
		$this->stmt->bindParam(':station_folder_id', $this->stationFolderId);

		/** Executo o SQL */
		$this->stmt->execute();

		/** Retorno o resultado */
		return $this->stmt->fetchObject();

	}

	/** Localiza uma pasta pelo nome */
	public function Search(int $stationId, string $folderPath)
	{

		/** Parametros de entrada */
		$this->folderPath = $folderPath;
		$this->stationId = $stationId;

		/** Consulta SQL */
		$this->sql = 'select * from station_folder  
					  where folder_path = :folder_path
					  and station_id = :station_id';

		/** Preparo o SQL para execução */
		$this->stmt = $this->connection->connect()->prepare($this->sql);

		/** Preencho os parâmetros do SQL */
		$this->stmt->bindParam(':folder_path', $this->folderPath);
		$this->stmt->bindParam(':station_id', $this->stationId);

		/** Executo o SQL */
		$this->stmt->execute();

		/** Retorno o resultado */
		return $this->stmt->fetchObject();

	}	

	/** Lista todos os egistros do banco com ou sem paginação*/
	public function All(int $stationId)
	{

		/** Parametros de entrada */
		$this->stationId = $stationId;

		/** Consulta SQL */
		$this->sql = 'select * from station_folder 
		              where station_id = :station_id';

		/** Preparo o SQL para execução */
		$this->stmt = $this->connection->connect()->prepare($this->sql);

		/** Preencho os parâmetros do SQL */
		$this->stmt->bindParam(':station_id', $this->stationId);		

		/** Executo o SQL */
		$this->stmt->execute();

		/** Retorno o resultado */
		return $this->stmt->fetchAll(\PDO::FETCH_OBJ);

	}

	/** Conta a quantidades de registros */
	public function Count()
	{
		/** Consulta SQL */
		$this->sql = 'select count(client_id) as qtde
					  from station_folder ';

		/** Preparo o SQL para execução */
		$this->stmt = $this->connection->connect()->prepare($this->sql);

		/** Executo o SQL */
		$this->stmt->execute();

		/** Retorno o resultado */
		return $this->stmt->fetchObject()->qtde;

	}

	/** Insere um novo registro no banco */
	public function Save(? int $stationFolderId, 
	                     ? int $stationId, 
						 ? string $folderPath, 
						 ? int $amountOfFiles, 
						 ? int $amountOfFilesCurrent)
	{


		/** Parametros */
		$this->stationFolderId = $stationFolderId;
		$this->stationId = $stationId;
		$this->folderPath = $folderPath;
		$this->amountOfFiles = $amountOfFiles;
		$this->amountOfFilesCurrent = $amountOfFilesCurrent;
	

		/** Verifica se o ID do registro foi informado */
		if($this->stationFolderId > 0){

			/** Consulta SQL */
			$this->sql = 'update station_folder set amount_of_files_current = :amount_of_files_current,
									   	            last_update = CURRENT_TIMESTAMP
					  	  where station_folder_id = :station_folder_id';

			/** Preparo o sql para receber os valores */
			$this->stmt = $this->connection->connect()->prepare($this->sql);

			try{
							
				/** Inicia a transação */
				$this->connection->connect()->beginTransaction();		

				/** Preencho os parâmetros do SQL */
				$this->stmt->bindParam('station_folder_id', $this->stationFolderId);
				$this->stmt->bindParam('amount_of_files_current', $this->amountOfFilesCurrent);

				/** Executo o SQL */
				$this->stmt->execute();

				/** Confirma a transação */
				$this->connection->connect()->commit();				
				return true;			

			}catch(\Exception $exception) {
															
				/** Desfaz a transação */
				$this->connection->connect()->rollback();

				/** Captura o erro */
				array_push($this->errors, $exception->getMessage());
				return false;
			}							  

		}else{//Se o ID não foi informado, grava-se um novo registro

			/** Consulta SQL */
			$this->sql = 'insert into station_folder(station_id, 
													 folder_path, 
													 amount_of_files 
										   ) values (:station_id,
													 :folder_path,
													 :amount_of_files)';

			/** Preparo o sql para receber os valores */
			$this->stmt = $this->connection->connect()->prepare($this->sql);

			try{
							
				/** Inicia a transação */
				$this->connection->connect()->beginTransaction();		

				/** Preencho os parâmetros do SQL */
				$this->stmt->bindParam('station_id', $this->stationId);
				$this->stmt->bindParam('folder_path', $this->folderPath);
				$this->stmt->bindParam('amount_of_files', $this->amountOfFiles);

				/** Executo o SQL */
				$this->stmt->execute();

				/** Retorna o ID do novo registro */
				$this->setId($this->connection->connect()->lastInsertId());

				/** Confirma a transação */
				$this->connection->connect()->commit();				
				return true;			

			}catch(\Exception $exception) {
															
				/** Desfaz a transação */
				$this->connection->connect()->rollback();

				/** Captura o erro */
				array_push($this->errors, $exception->getMessage());
				return false;
			}													 

		}						

	}

	/** Define o Último ID inserido */
	public function setId($lastId) : void
	{
		$this->lastId = $lastId;
	}

	/** Recupera o Último ID inserido */
	public function getId(): ? int
	{
		return (int)$this->lastId;
	}	

	/** Deleta um determinado registro no banco de dados */
	function Delete(int $stationFolderId)
	{
		/** Parametros de entrada */
		$this->stationFolderId = $stationFolderId;

		/** Consulta SQL */
		$this->sql = 'delete from station_folder
					  where  station_folder_id = :station_folder_id';

		/** Preparo o sql para receber os valores */
		$this->stmt = $this->connection->connect()->prepare($this->sql);

		/** Preencho os parâmetros do SQL */
		$this->stmt->bindParam('station_folder_id', $this->stationFolderId);

		/** Executo o SQL */
		return $this->stmt->execute();

	}

	/** Fecha uma conexão aberta anteriormente com o banco de dados */
	function __destruct()
	{
		$this->connection = null;
    }
}
