<?php

namespace Velis\Repository\QuickReport;

use Velis\Db\EntityRepository;
use Velis\Model\DataObject\NoColumnsException;
use Velis\QuickReport\Category;
use Velis\User;

/**
 * @author Jan Małysiak <jan.malysiak@velis.pl>
 */
class CategoryRepository extends EntityRepository
{
    /**
     * Find categories assigned to the user or to user's roles
     * @param User $user
     * @return Category[]
     * @throws NoColumnsException
     */
    public function findByUser(User $user): array
    {
        $query = '
            SELECT c.*
            FROM app.quick_report_category_tab c
            WHERE
                EXISTS (
                    SELECT 1
                    FROM app.quick_report_category_user_tab cu
                    WHERE
                        cu.quick_report_category_id = c.quick_report_category_id
                        AND cu.user_id = :user_id
                )   
                OR EXISTS (
                    SELECT 1
                    FROM
                        app.quick_report_category_role_tab cr
                        JOIN acl.user_role_tab ur USING (role_id)
                    WHERE
                        cr.quick_report_category_id = c.quick_report_category_id
                        AND ur.user_id = :user_id
                )
        ';

        $rows = $this->db->getAll($query, [
            'user_id' => $user->id(),
        ]);

        $result = [];

        foreach ($rows as $row) {
            $result[] = new Category($row);
        }

        return $result;
    }
}
