<?php
/**
 * Count repository
 *
 * @author Lucas Dantas <lucas@caju.nu>
 * @package classes
 * @subpackage count
 * @version 1.0
 * @since 2018/04/09 19:25
 */
Class CountRepositoryDBR{

	/**
	 * Connection's object
	 *
	 * @access private
	 * @var PDO
	 */
	private $connection;

	/**
	 * Showing or not the exception
	 *
	 * @access private
	 * @var boolean
	 */
	public $exception	= true;

	/**
	 * Instance
	 *
	 * @access private
	 * @static
	 * @var CountRepositoryDBR
	 */
	private static $instance = [];

	/**
	 * Class constructor
	 *
	 * @access public
	 * @param string $type Type
	 * @uses ConnectionDBR::getInstance Defining the instance
	 */
	public function __construct( $type ){

		$this->connection	= ConnectionDBR::getInstance()->getConnection();
		$this->type			= $type;

	}

	/**
	 * Getting the instance
	 *
	 * @access public
	 * @param string $type Type
	 * @return ConnectionDBR
	 */
	public static function getInstance( $type ){

		//Checking
		if( !array_key_exists( $type, self::$instance ) )
			//Defining
			self::$instance[ $type ]	= new self( $type );

		//Returning
		return self::$instance[ $type ];

	}

	/**
	 * Counting
	 *
	 * @access public
	 * @param string $complement Complement
	 * @param array $params PArams
	 * @throws Exception
	 * @return integer
	 */
	public function count( $complement = null, $params = [] ){

		try{

			//Checking
			switch( $this->type ){

				//Banner
				default:

					//Defining
					$sql	= 'SELECT COUNT(*) AS quantity FROM newsletter TBL WHERE TBL.id IS NOT NULL ' . $complement;

				break;

			}

			//Preparing
			$resource	= $this->connection->prepare( $sql );

			//Checking
			if( count( $params ) > 0 )
				//Listing
				foreach( $params as $field => $config )
					//Defining
					$resource->bindValue( $field, $config[ 'value' ], $config[ 'type' ] );

			//Executing
			$resource->execute();

			//Defining
			$records	= $resource->fetch( PDO::FETCH_OBJ );

			//Returning
			return $records->quantity;

		}catch( PDOException $e ){

			//Throwing the exception
			throw new Exception( 'Ocorreu um erro durante a contagem. Por favor, tente novamente mais tarde.' );

		}

	}

	/**
	 * Counting by email
	 *
	 * @access public
	 * @param integer $email E-mail
	 * @param string $complement Complement
	 * @param string $params Param
	 * @uses $this->count Counting
	 * @return integer
	 */
	public function byEmail( $email, $complement = null, $params = [] ){

		//Defining
		$complement	= 'AND email = :email ' . $complement;

		//Defining
		$params	= array_merge( [ ':email' => [ 'value' => $email, 'type' => PDO::PARAM_STR ] ], $params );

		//Listing
		return $this->count( $complement, $params );

	}

}