<?php 

/**
 * Management of the homepage brick layout for a specific user.
 * There is one homepageuserbrick entry per brick on the user's homepage.
 */

class homepageuserbrick {
	
	private static string $select='SELECT 
			 homepageuserbrick.id AS id, homepagebrick.id AS homepagebrickid,
			 homepagebrick.name, /*homepagebrick.title, homepagebrick.version, homepagebrick.description, 
			 homepagebrick.apiurl, homepagebrick.scriptblock, homepagebrick.content,
			 homepagebrick.headertemplates, homepagebrick.rowtemplates, homepagebrick.adminonly,*/
			 homepageuserbrick.height, homepageuserbrick.width, 
             homepageuserbrick.row, homepageuserbrick.col, homepageuserbrick.userid
			FROM homepagebrick, homepageuserbrick 
			WHERE homepagebrick.id=homepageuserbrick.homepagebrickid 
			 ';

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

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

	/**
	 * @param string $name
	 * @param string $value
	 * @param array $request
	 * @return array|null
	 * @throws BadRequestException
	 * @noinspection PhpUnusedParameterInspection
	 */
	public static function getByProperty(string $name, string $value, array $request=[]): ?array {
		throw new BadRequestException('getByProperty not implemented on homepageuserbrick');
	}

	/**
	 * @param array $keyValuePairs
	 * @param array $request
	 * @return array|null
	 * @throws BadRequestException
	 * @noinspection PhpUnusedParameterInspection
	 */
	public static function getByProperties(array $keyValuePairs, array $request=[]): ?array {
		throw new BadRequestException('getByProperties not implemented on homepageuserbrick');
	}

    /**
     * @param array $request
     * @return array
     * @throws BadRequestException
     * @throws ServerException
     * @noinspection PhpUnusedParameterInspection
     */
	public static function getAll(array $request=[]): array {
		$sqlStatement=static::$select.' AND homepageuserbrick.userid=:userid ORDER BY homepageuserbrick.row, homepageuserbrick.col';
		$parameters=array(':userid'=>session::getUserId());
		return database::queryGetAll($sqlStatement, $parameters);
	}

	/**
	 * @param int $id
	 * @param array $request
	 * @return array
	 * @throws BadRequestException
	 * @throws ServerException
	 */
	public static function update(int $id, array $request=[]): array {
		$userBrick=static::getById($id);
		if(!$userBrick || $userBrick['userid']!=session::getUserId()){
			throw new BadRequestException('homeuserpagebrick ID '.$id.' does not exist or is not yours');
		}
		$parts=array();
		foreach($request as $k=>$v){
			if(!in_array($k, array('row','col','height','width'))){
				unset($request[$k]);
				continue;
			}
			$v=(int)$v;
			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 homepageuserbrick SET '.implode(', ',$parts).' WHERE id=:id';
		database::query($sqlStatement, $request);
		return static::getById($id);
	}

    /**
     * @param array $request
     * @return array
     * @throws BadRequestException
     * @throws ServerException
     * @throws ForbiddenException
     */
	public static function create(array $request=[]): array{
        if(!isset($request['homepagebrickid']) || !isset($request['row']) || !isset($request['col'])){
            throw new BadRequestException('Brick ID, row and col are required');
        }
        $isForCurrentUser=true;
        if(isset($request['userid'])){
            if(session::getUserId()!=$request['userid']){
                $isForCurrentUser=false;
                if(!user::canCreate()) {
                    throw new ForbiddenException('You cannot create homepage bricks for others');
                }
            }
        } else {
            $request['userid']=session::getUserId();
        }
        $result=database::queryGetOne(
            'SELECT * FROM homepageuserbrick WHERE userid=:userid AND homepagebrickid=:homepagebrickid',
            array(
                ':homepagebrickid'=>$request['homepagebrickid'],
                ':userid'=>$request['userid'],
            )
        );
        if(!empty($result)){
            $msg='This user already has that brick on their homepage.';
            if($isForCurrentUser){
                $msg='You already have that brick on your homepage.';
            }
            throw new BadRequestException($msg);
        }
        $brick=homepagebrick::getById($request['homepagebrickid']);
        if(!$brick){ throw new BadRequestException('No homepage brick with ID '.$request['homepagebrickid']); }

		$sqlStatement='INSERT INTO homepageuserbrick(`homepagebrickid`, `userid`, `row`, `col`, `height`,`width`) 
				VALUES(:homepagebrickid, :userid, :row, :col, :height, :width)';
		$parameters=array(
				':homepagebrickid'=>$request['homepagebrickid'],
				':userid'=>$request['userid'],
				':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
	 * @return array
	 * @throws BadRequestException
	 * @throws ServerException
	 */
	public static function delete(int $id): array{
		$userBrick=static::getById($id);
		if(!$userBrick || $userBrick['userid']!=session::getUserId()){
			throw new BadRequestException('homepageuserbrick ID '.$id.' does not exist or is not yours');
		}
		$sqlStatement='DELETE FROM homepageuserbrick WHERE id=:id AND userid=:userid';
		$parameters=array(
				':id'=>$id,
				':userid'=>session::getUserId(),
		);
		database::query($sqlStatement, $parameters);
		return array('deleted'=>$id);
	}

}