<?php

namespace AppBundle\Entity;
use Gedmo\Tree\Entity\Repository\NestedTreeRepository;

/**
 * PageRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PageRepository extends NestedTreeRepository
{
    /**
     * @param Page $page
     * @return Page[]|array
     *
     * @todo Optimize performance by adapting search algorithm's optimizations
     */
    public function getChildrenWithTravelProgramsAndDates(Page $page)
    {
        $pages = $this->getChildrenQueryBuilder($page)
            ->leftJoin('node.travelProgram', 'tp')
            ->addSelect('tp')
            ->andWhere('tp.status > 0')
            ->andWhere('node.status > 0')
            ->orderBy('node.order')
            ->addOrderBy('tp.position')
            ->addOrderBy('node.title')
            ->getQuery()
            ->execute();
        /** @var Page $childPage */
        foreach ($pages as &$childPage)
        {
            if ($childPage->getTravelProgram())
            {
                $this->getEntityManager()->getRepository('AppBundle:TravelPeriod')->getTrueTravelPeriods(
                  $childPage->getTravelProgram());
            }
        }
        return $pages;
    }

    /**
     * @param Page $page
     *
     * @return Page[]|\Doctrine\Common\Collections\Collection
     */
    public function getSiblings(Page $page)
    {
        $parent = $page->getParent();
        if (!$parent)
        {
            // On purpose, we don't treat root pages as if they were siblings
            return [];
        }
        $siblings = $parent->getChildren();
        foreach ($siblings as &$sibling)
        {
            $sibling->setParent($parent);
        }
        return $siblings;
    }
}
