<?php

namespace KupShop\UserManagerBundle\Admin\Tabs;

use KupShop\AdminBundle\Admin\WindowTab;
use Query\Operator;

class UserManagerTab extends WindowTab
{
    protected $title = 'flapUserManager';

    protected $template = 'window/users.manager.tpl';

    public static function getTypes()
    {
        return [
            'users' => 99,
        ];
    }

    public function getVars($smarty_tpl_vars)
    {
        $users = sqlQueryBuilder()
            ->select('u.id, CONCAT(u.firm, " ", u.name, " ", u.surname, " - ", u.email) as text')
            ->from('users_manager_relations', 'umr')
            ->join('umr', 'users', 'u', 'u.id = umr.id_user')
            ->where(
                Operator::equals(
                    [
                        'umr.id_user_master' => $this->getID(),
                    ]
                )
            )->execute()->fetchAll();

        $manager = sqlQueryBuilder()
           ->select('u.id, CONCAT(u.firm, " ", u.name, " ", u.surname, " - ", u.email) as text')
           ->from('users_manager_relations', 'umr')
           ->join('umr', 'users', 'u', 'u.id = umr.id_user_master')
           ->where(
               Operator::equals(
                   [
                       'umr.id_user' => $this->getID(),
                   ]
               )
           )->execute()->fetchAssociative();

        return [
            'users' => $users,
            'manager' => $manager,
        ];
    }

    public function handleUpdate()
    {
        $data = $this->getData();

        sqlQueryBuilder()
            ->delete('users_manager_relations')
            ->where(Operator::equals(['id_user_master' => $this->getID()]))
            ->execute();

        foreach ($data['users_manager_relations'] ?? [] as $key => $item) {
            if (!empty($item['delete'])) {
                continue;
            }

            sqlQuery('INSERT IGNORE INTO users_manager_relations (id_user_master, id_user) VALUE (:id_user_master, :id_user)', [
                'id_user_master' => $this->getID(),
                'id_user' => $item['id_user'],
            ]);
        }
    }
}
