<?php 

/**
 * This class is used to manage the default layout of the homepage for new users.
 * Nothing in this class affects the homepage layout of existing users.
 * There is one homepagedefaultlayout entry per brick on the default homepage.
 */

class homepagedefaultbrick {
	
	private static string $select='SELECT db.id AS id, b.id AS homepagebrickid,
				db.row AS `row`, db.col AS `col`,
				b.name AS name, b.version AS version, b.title AS title,
				b.description AS description, db.height AS height, db.width AS width,
				b.adminonly AS adminonly
				FROM homepagedefaultbrick AS db, homepagebrick AS b
				WHERE db.homepagebrickid=b.id';

    /**
     * @throws ForbiddenException
     */
	private static function checkCanUpdate(): void {
		if(!session::isAdmin()){
			throw new ForbiddenException('Only administrators can configure the default homepage');
		}
	}

	/**
	 * @param int $id
	 * @return array|null
	 * @throws BadRequestException
	 * @throws ServerException
	 */
	public static function getById(int $id): ?array {
	    return database::queryGetOne(
	        static::$select.' AND db.id=:id',
	        array(':id'=>$id)
	        );
	}

	/**
	 * @param string $name
	 * @return array|null
	 * @throws BadRequestException
	 * @noinspection PhpUnusedParameterInspection
	 */
	public static function getByName(string $name): ?array {
	    throw new BadRequestException('getByName not implemented on homepagedefaultbrick');
	}

	/**
	 * @throws ServerException
	 * @noinspection PhpUnusedParameterInspection
	 */
	public static function getByProperty(string $key, string $value, array $request=[]): ?array {
		throw new ServerException('getByProperty not implemented on homepagedefaultbrick');
	}

	/**
	 * @throws ServerException
	 * @noinspection PhpUnusedParameterInspection
	 */
	public static function getByProperties(array$keyValuePairs, array $request=[]): ?array {
		throw new ServerException('getByProperties not implemented on homepagedefaultbrick');
	}

	/**
     * @param array $request
     * @return array
     * @noinspection PhpUnusedParameterInspection
     * @throws BadRequestException
     * @throws ServerException
     */
	public static function getAll(array $request=array()): array {
		return database::queryGetAll(
				static::$select
		);	
	}

    /**
     * @return array
     */
	public static function getFieldHelpTexts(): array {
		return array();
	}

    /**
     * @return array
     */
	public static function getFieldValidations(): array {
		return array();
	}

    /**
     * @param array $request
     * @return array
     * @throws BadRequestException
     * @throws ForbiddenException
     * @throws ServerException
     */
	public static function create(array $request=[]): array {
		static::checkCanUpdate();
		if(!isset($request['homepagebrickid']) || !isset($request['row']) || !isset($request['col'])){
			throw new BadRequestException('Brick ID, row and col are required');
		}

        $brick=homepagebrick::getById($request['homepagebrickid']);
        if(!$brick){ throw new BadRequestException('No homepage brick with ID '.$request['homepagebrickid']); }

        $sqlStatement='INSERT INTO homepagedefaultbrick(`homepagebrickid`, `row`, `col`, `height`, `width`)
				VALUES(:homepagebrickid, :row, :col, :height, :width)';
		$parameters=array(
				':homepagebrickid'=>$request['homepagebrickid'],
				':row'=>$request['row'],
				':col'=>$request['col'],
                ':height'=>$brick['height'],
                ':width'=>$brick['width']
		);
		database::query($sqlStatement, $parameters);
		$newId=database::getLastInsertId();
		return array('type'=>'homepageuserbrick', 'created'=>self::getById($newId));
	}

	/**
	 * @param int $id
	 * @param array $request
	 * @return array
	 * @throws BadRequestException
	 * @throws ForbiddenException
	 * @throws NotFoundException
	 * @throws ServerException
	 */
	public static function update(int $id, array $request=[]): array{
		static::checkCanUpdate();
		$defaultBrick=static::getById($id);
		if(!$defaultBrick){
			throw new NotFoundException('No default homepage brick with ID '.$id);
		}
		$parts=array();
		foreach($request as $k=>$v){
			if(!in_array($k, array('row','col','height','width'))){
				unset($request[$k]);
				continue;
			}
			$v=(int)$v;
			//We assume that the client threw out any overlapping/non-fitting layouts, but check for the truly stupid
			if($v<1 ||$v>3){
				throw new BadRequestException($k.' must be between 1 and 3, was '.$v);
			}
			$parts[]='`'.$k.'`=:'.$k;
		}
		$request['id']=$id;
		$sqlStatement='UPDATE homepagedefaultbrick SET '.implode(', ',$parts).' WHERE id=:id';
		database::query($sqlStatement, $request);
		return static::getById($id);
	}

    /**
     * @param int $id
     * @return array
     * @throws BadRequestException
     * @throws ForbiddenException
     * @throws NotFoundException
     * @throws ServerException
     */
	public static function delete(int $id): array {
		static::checkCanUpdate();
		$defaultBrick=static::getById($id);
		if(!$defaultBrick){
			throw new NotFoundException('No default homepage brick with ID '.$id);
		}
		$sqlStatement='DELETE FROM homepagedefaultbrick WHERE id=:id';
		database::query($sqlStatement, array(':id'=>$id));
		return array('deleted'=>$id);
	}

}