<?php
/**
 * Copyright (c) 2016 Serhii Borodai <clarifying@gmail.com>.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 *
 */

namespace App\Model;

use App\Entity\Site;


/**
 * Class Sites
 * @package App\Model
 */
class Sites extends Common
{

    /**
     * @param $id
     * @return Site[]
     */
    public function findByUserId($id)
    {
        /** @noinspection PhpIncompatibleReturnTypeInspection */
        return $this->findAll(['users_id' => $id], 'domain ASC');
    }

    /**
     * @param $id int
     * @param $usersId int
     * @return int
     */
    public function delete($id, $usersId)
    {
        return $this->tableGateway->delete(['id' => $id, 'users_id' => $usersId]);
    }

    /**
     * @param $siteId
     * @param $userId
     * @return \Zend\Db\ResultSet\HydratingResultSet
     */
    public function findByIdAndUserId($siteId, $userId)
    {
        return $this->findAll(['id' => $siteId, 'users_id' => $userId])->current();
    }
    
    
    /**
     * 
     * @param type $siteDomain
     * @param type $userId
     * 
     * @return \App\Entity\Common|object
     * @throws \Exception     
     */
    public function findByDomainAndUserId($siteDomain, $userId)
    {
        return $this->findOne(['domain' => $siteDomain, 'users_id' => $userId]);
    }
    
    public function findByDomain($siteDomain)
    {
        return $this->findAll(['domain' => $siteDomain]);
    }

    public function findByAlias($alias)
    {
        $sites = $this->findAll();
        foreach ($sites as $site) {
            $site_aliases = explode(",", $site->getAlias());
            foreach($site_aliases as $key=>$site_alias) {
                $site_aliases[$key] = trim($site_alias);
            }
            if (in_array($alias, $site_aliases)) {
              return $site;
            }
        }
        return null;
    }

    public function findBy($where = null, $limit = null, $order = null) 
    {
        if($where['category']) {
            $result = parent::findByLike($where, $limit, $order);
        } else {
            $result = parent::findBy($where, $limit, $order);
        }
        return $result;
    }
    
    public function findAllSites()
    {
        $url = 'http://piguiqproxy.com/api';
        $username='dev';
        $password='LJsVSwx2K5t5HvcWaBKKDbLzB625D5mhrbDFaxYzugkutp23eUB5F';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "m=whitelist_get");
        
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/x-www-form-urlencoded',
            'Authorization: Basic '.base64_encode($username.":".$password)
        ));
        
        // выполняем запрос
        $result=curl_exec ($ch);
        $info = curl_getinfo($ch);
        
        // закрываем curl
        curl_close ($ch);
        
        if($info['http_code'] != 200) {
            throw new \Exception('Error. ' . $info['http_code']);
        }
        
        return json_decode($result, 1);
    }
    
    public function createListItem($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));

        $query = function($data) {
            $this->tableGateway->insert($data);
            $insertId = $this->tableGateway->lastInsertValue;
            return $insertId;
        };

        try {
            $this->tableGateway->getAdapter()->getDriver()->getConnection()->beginTransaction();
            $id = $query($data);
            $this->tableGateway->getAdapter()->getDriver()->getConnection()->commit();
        } catch (\Exception $e) {
            $this->tableGateway->getAdapter()->getDriver()->getConnection()->rollback();
            throw $e;
        }
        return $id;
    }
    
    public function createListSites()
    {
        $list_sites = [];
        foreach($this->findAll()->toArray() as $site_data) {
            $list_sites[$site_data['id']] = $site_data['domain'];
        }
        return $list_sites;
    }
    
    
    public function createListSitesById($sites_id)
    {
        $list_sites = [];
        foreach($this->findAll(['id'=>$sites_id])->toArray() as $site_data) {
            $list_sites[$site_data['id']] = $site_data['domain'];
        }
        return $list_sites;
    }
    
    
    
}