<?php
namespace Incoviba\Repository;

use Incoviba\Common\Ideal;
use Incoviba\Common\Define;
use Incoviba\Common\Implement;
use Incoviba\Model;

class Menu extends Ideal\Repository
{
    public function __construct(Define\Connection $connection)
    {
        parent::__construct($connection);
        $this->setTable('menus');
    }

    public function create(?array $data = null): Define\Model
    {
        $map = (new Implement\Repository\MapperParser(['title']))
            ->register('url', (new Implement\Repository\Mapper())
                ->setDefault(''));
        $model = $this->parseData(new Model\Menu(), $data, $map);
        $model->children = $this->fetchChildren($model->id);
        return $model;
    }
    public function save(Define\Model $model): Define\Model
    {
        $model->id = $this->saveNew(
            ['title', 'url'],
            [$model->title, $model->url]
        );
        return $model;
    }
    public function edit(Define\Model $model, array $new_data): Define\Model
    {
        return $this->update($model, ['title', 'url'], $new_data);
    }

    public function fetchByUser(int $user_id): array
    {
        $query = "SELECT a.*
FROM `{$this->getTable()}` a
    JOIN `menu_permissions` mp ON mp.`menu_id` = a.`id`
    JOIN `permissions` ON `permissions`.`id` = mp.`permission_id`
    LEFT JOIN `users` u1 ON u1.`id` = `permissions`.`'ext_id` AND `permissions`.`type` = 2
    LEFT JOIN (SELECT u2.* FROM `roles` ON `roles`.`id` = `permissions`.`ext_id` AND `permissions`.`type` = 1
        JOIN `user_roles` ur ON ur.`role` = `role`.`id`
        JOIN `users` u2 ON u2.`id` = ur.`user`) us
    LEFT JOIN `menu_relations` mr ON mr.`child_id` = a.`id`
WHERE u1.`id` = ? OR us.`id` = ? AND mr.`id` IS NULL";
        return $this->fetchMany($query, [$user_id, $user_id]);
    }
    public function fetchChildren(int $menu_id): array
    {
        $query = "SELECT sm.* FROM `menu_relations` mr WHERE mr.`parent_id` = ?";
        try {
            return $this->fetchMany($query, [$menu_id]);
        } catch (Implement\Exception\EmptyResult) {
            return [];
        }
    }
}
