<?php

namespace App\Bundle\Bitrix;

use Doctrine\DBAL\DriverManager;
use App\Bundle\Infoclinica\Region;

class Request
{
	private $connect = null;
	private $regionId = NULL;

	public static $instance = NULL;

	private function __construct() {}
	
	public static function init($regionId = NULL)
    {
        if (self::$instance === null) {
            self::$instance = new self();
	        self::$instance->connect = DriverManager::getConnection([
				'url' => $_ENV['DATABASE_BITRIX_URL']
			]);

	        self::$instance->connect->executeQuery("SET NAMES utf8");

			if ($regionId == NULL) {
				self::$instance->regionId = Region::getId();
			} else {
				self::$instance->regionId = $regionId;
			}
        }

        return self::$instance;
    }

    public function setRegionId($id)
    {
    	$this->regionId = $id;

    	return $this;
    }

   	public function getPropPriceId($param = 'value')
    {
    	$props = [
    		'91' => [
    			'value' => 2980,
    			'name' => 'Саратов'
    		],
    		'comfort' => [
    			'value' => 2980,
    			'name' => 'Саратов Comfort'
    		],
    		'93' => [
    			'value' => 2985,
    			'name' => 'Воронеж'
    		],
    		'92' => [
    			'value' => 2990,
    			'name' => 'Волгоград'
    		],
    		'94' => [
    			'value' => 4477,
    			'name' => 'Краснодар'
    		],
    		
    	];

    	return $props[$this->regionId][$param];
    }

    public function getBlockId($param = 'value')
    {
    	$iblock_ids = [
    		'sovenok' => [
    			'value' => 174,
    			'uslugi' => 175,
    			'name' => 'Саратов Совенок'
    		],
    		'comfort' => [
    			'value' => 145,
    			'uslugi' => 146,
    			'name' => 'Саратов Comfort'
    		],
    		'91' => [
    			'value' => 91,
    			'uslugi' => 165,
    			'name' => 'Саратов'
    		],
    		'92' => [
    			'value' => 92,
    			'uslugi' => 167,
    			'name' => 'Волгоград'
    		],
    		'93' => [
    			'value' => 93,
    			'uslugi' => 166,
    			'name' => 'Воронеж'
    		],
    		'94' => [
    			'value' => 219,
    			'uslugi' => 229,
    			'name' => 'Краснодар'
    		],
    	];

    	return $iblock_ids[$this->regionId][$param];
    }

    public function getDoctors($isActive = false)
    {
    	$specialist = $this->connect->createQueryBuilder()
			->select('*')
			->from('`b_iblock_element`', 'el')
			->where('el.IBLOCK_ID = :IBLOCK_ID')
			->andWhere('el.WF_PARENT_ELEMENT_ID IS NULL')
			->andWhere('el.PREVIEW_PICTURE IS NOT NULL')
			->setParameter('IBLOCK_ID', $this->getBlockId());

		if ($isActive) {
			$specialist
				->andWhere('el.ACTIVE = :ACTIVE')
				->setParameter('ACTIVE', 'Y');
		}

		$specialist = $specialist
			->execute()
			->fetchAll()
		;

		return $specialist;
    }

    public function getSpecialist($sid, $infoclinica = false)
    {
		$specialist = $this->connect->createQueryBuilder()
			->select('*')
			->from('`b_iblock_element`', 'el');
		
		if ($infoclinica) {
			$specialist
				->where('el.XML_ID = :XML_ID')
				->setParameter('XML_ID', $sid);
		} else {
			$specialist
				->where('el.ID = :ID')
				->setParameter('ID', $sid);
		}

		$specialist = $specialist
			->execute()
			->fetch()
		;

		if ($specialist) {
			$specialist['NAME'] = explode(' ', trim($specialist['NAME']));
		}

		return $specialist;
    }


	// SELECT biep.IBLOCK_ELEMENT_ID as DOCTOR_ID FROM b_iblock_element_property biep LEFT JOIN b_iblock_property bip ON biep.IBLOCK_PROPERTY_ID = bip.ID WHERE biep.VALUE = $doctorId AND bip.CODE REGEXP 'MEDIC' AND bip.ACTIVE = 'Y'
	
	// SELECT biep.VALUE, bip.NAME, bip.CODE FROM b_iblock_element bie INNER JOIN b_iblock_element_property biep ON biep.IBLOCK_ELEMENT_ID = bie.ID LEFT JOIN b_iblock_property bip ON biep.IBLOCK_PROPERTY_ID  = bip.ID WHERE bie.ID = $itemID;
	public function getReviews($doctorId, $infoclinica)
	{
		$specialist = $this->getSpecialist($doctorId, $infoclinica);
		
		if (! $specialist) {
			return [];
		}

		$items = $this->connect->createQueryBuilder()
			->select('biep.IBLOCK_ELEMENT_ID as REVIEW_ID')
			->from('b_iblock_element_property', 'biep')
			->leftJoin('biep', 'b_iblock_property', 'bip', 'biep.IBLOCK_PROPERTY_ID = bip.ID')
			->where('biep.VALUE = :VALUE')
			->andWhere('bip.CODE REGEXP :CODE')
			->setParameter('VALUE', $specialist['ID'])
			->setParameter('CODE', 'MEDIC')
			->execute()
			->fetchAll()
		;

		foreach ($this->docPropsCode($specialist['ID'], 'LINK_REVIEWS') as $item) {
			$items[]['REVIEW_ID'] = $item['VALUE'];
		}

		if (! empty($items)) {
			foreach ($items as $key => $item) {
				$items[$key]['DATA'] = $this->docPropsCode($item['REVIEW_ID']);

				foreach ($items[$key]['DATA'] as $i => $props) {
					if ($props['CODE'] == 'MESSAGE') {
    					$data = preg_replace_callback('!s:(\d+):"(.*?)";!s', function($m) {
						            $len = strlen($m[2]);
						            $result = "s:$len:\"{$m[2]}\";";
						            return $result;
						        }, $props['VALUE']);
    					
    					if (@unserialize($data) !== false) {
							$items[$key]['DATA'][$i]['VALUE'] = unserialize($data)['TEXT'];
    					}
					}
				}
			}
		}

		return $items;
	}

	// select biep.ID, bie.ACTIVE, bie.IBLOCK_SECTION_ID, bie.DATE_CREATE, biep.VALUE, bip.NAME, bip.CODE 
	// from b_iblock_element bie
	// inner join b_iblock_element_property biep on biep.IBLOCK_ELEMENT_ID = bie.ID
	// left join b_iblock_property bip on biep.IBLOCK_PROPERTY_ID = bip.ID
	// where bie.ID = :ID
	public function docPropsCode($elementId, $code = NULL, $all = true) 
	{
		$qb = $this->connect->createQueryBuilder()
			->select('bie.NAME as BIE_NAME, biep.ID, bie.ACTIVE, bie.IBLOCK_SECTION_ID, bie.DATE_CREATE, biep.VALUE, bip.NAME, bip.CODE')
			->from('b_iblock_element', 'bie')
			->innerJoin('bie', 'b_iblock_element_property', 'biep', 'biep.IBLOCK_ELEMENT_ID = bie.ID')
			->leftJoin('biep', 'b_iblock_property', 'bip', 'biep.IBLOCK_PROPERTY_ID = bip.ID')
			->where('bie.ID = :ID')
			->setParameter('ID', $elementId);
			
		if ($code) {
			$qb->andWhere('bip.CODE = :CODE')
				->setParameter('CODE', $code);	
		}

		if ($all) {
			return $qb->execute()->fetchAll();
		}
		
		return $qb->execute()->fetch();
	}

	public function getImage($id) 
	{
		$data = $this->connect->createQueryBuilder()
			->select('*')
			->from('b_file', 'f')
			->where('f.ID = :ID')
			->setParameter('ID', $id)
			->execute()
			->fetch()
		;
		
		if (empty($data['FILE_NAME'])) {
			$response = '/images/no_img.png';
		} else {
			$response = 'https://sovamed.ru/upload/'. $data['SUBDIR'];
			$response .= '/'. $data['FILE_NAME'];
		}

		return $response;
	}

// SELECT * FROM `b_iblock_section` WHERE ACTIVE = 'Y' AND	IBLOCK_SECTION_ID IS NULL  AND (IBLOCK_ID = 165 OR IBLOCK_ID = 166 OR IBLOCK_ID = 167);
	public function getFilials()
	{
		return $this->connect->createQueryBuilder()
			->select('ID, NAME, IBLOCK_ID, IBLOCK_SECTION_ID, ACTIVE')
			->from('`b_iblock_section`', 'el')
			->where('el.ACTIVE = :ACTIVE')
			->andWhere('el.IBLOCK_ID = :IBLOCK_ID')
			->andWhere('el.IBLOCK_SECTION_ID IS NULL')
			->setParameter('ACTIVE', 'Y')
			->setParameter('IBLOCK_ID', $this->getBlockId('uslugi'))
			->execute()
			->fetchAll()
		;
	}

	public function getDepartments($sectionId)
	{
		try {
			return $this->connect->createQueryBuilder()
				->select('ID, NAME, IBLOCK_ID, IBLOCK_SECTION_ID, ACTIVE')
				->from('`b_iblock_section`', 'el')
				->where('el.ACTIVE = :ACTIVE')
				->andWhere('el.IBLOCK_ID = :IBLOCK_ID')
				->andWhere('el.IBLOCK_SECTION_ID = :IBLOCK_SECTION_ID')
				->setParameter('ACTIVE', 'Y')
				->setParameter('IBLOCK_SECTION_ID', $sectionId)
				->setParameter('IBLOCK_ID', $this->getBlockId('uslugi'))
				->execute()
				->fetchAll()
			;
		} catch (Exception $e) {
			return false;
		}
	}

	public function getServices($sectionId)
	{
		return $this->connect->createQueryBuilder()
			->select('el.ID, el.NAME, el.IBLOCK_ID, el.IBLOCK_SECTION_ID, el.ACTIVE, prop.VALUE')
			->from('`b_iblock_element`', 'el')
			->leftJoin('el', 'b_iblock_element_property', 'prop', 
				'prop.IBLOCK_ELEMENT_ID = el.ID AND prop.IBLOCK_PROPERTY_ID = IBLOCK_PROPERTY_ID'
			)
			->where('el.ACTIVE = :ACTIVE')
			->andWhere('el.IBLOCK_ID = :IBLOCK_ID')
			->andWhere('el.IBLOCK_SECTION_ID = :IBLOCK_SECTION_ID')
			->setParameter('ACTIVE', 'Y')
			->setParameter('IBLOCK_SECTION_ID', $sectionId)
			->setParameter('IBLOCK_PROPERTY_ID', $this->getPropPriceId())
			->setParameter('IBLOCK_ID', $this->getBlockId('uslugi'))
			->execute()
			->fetchAll()
		;
	}
}