<?php

namespace App\Model;

use \Zend\Db\TableGateway\TableGateway;
use \Zend\Hydrator\DelegatingHydrator;
use \Monolog\Logger;
use \App\Model\Categories;

class UsersCategory extends Common 
{
    
    /** @var Category */
    protected $categodyModel;


    public function __construct(TableGateway $tableGateway, DelegatingHydrator $delegatingHydrator, Logger $logger, Categories $category)
    {
        parent::__construct($tableGateway, $delegatingHydrator, $logger);
        
        $this->categodyModel = $category;
    }
    
    public function getUsersId($category)
    {
        $adapter = $this->tableGateway->getAdapter();
        
        if(!is_array($category)) {
            $category = array($category);
        }
        $category = array_map('intval', $category);
        
        $sql = 'SELECT user_id '
                . ' FROM ' . (string) $this->tableGateway->getTable() 
                . ' WHERE category_id in (\''.implode('\',\'', $category).'\')';                
        $res = $adapter->query($sql, \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);
        
        $usersId = array();
        if($res) {
            foreach($res as $r) {
                $usersId[] = $r['user_id'];                
            }
        }
        return $usersId;
    }

    public function findBy($where = null, $limit = null, $order = null) {
        $tmp = parent::findBy($where, $limit, $order);
        if($tmp->count()) {        
            $result = array();
            foreach($tmp as $userCatrory) {
                $caterory = $this->categodyModel->findById($userCatrory->getCategoryId());
                if($caterory) {
                    $result[$caterory->getId()] = $caterory;
                }
            }        
        } else {
            $result = null;
        }
        
        return $result;
    }
    
    public function saveAll($userId, $entityList) 
    {
        try {           
            $this->tableGateway->getAdapter()->getDriver()->getConnection()->beginTransaction();
            
            $this->tableGateway->delete([
                'user_id' => $userId,
            ]);
            
            foreach($entityList as $entity) {
                $data = $this->delegatingHydrator->extract($entity);
                // accept data columns only available at table
                $data = array_intersect_key($data, array_fill_keys($this->tableGateway->getColumns(), 1));
                
                $this->tableGateway->insert($data);            
            }
            
            $this->tableGateway->getAdapter()->getDriver()->getConnection()->commit();            
        } catch(\Exception $e) {
            $this->tableGateway->getAdapter()->getDriver()->getConnection()->rollback();
            throw $e;
        }
        return true;
    }           
}
