<?php
class ControllerToolCallback extends Controller {
	public function index() {
		$this->load->language('tool/upload');

		$json = array();

		$json['error'] = [];

		$telephone = isset($this->request->post['telephone']) && is_scalar($this->request->post['telephone']) ? trim((string)$this->request->post['telephone']) : '';

		if (utf8_strlen($telephone) < 3 || utf8_strlen($telephone) > 32) {
			$json['error'][] = 'Укажите номер телефона.';

			$this->response->addHeader('Content-Type: application/json');
			$this->response->setOutput(json_encode($json));

			return;
		}

		$data['request_type'] = isset($this->request->post['request_type']) ? $this->request->post['request_type'] : '';
		$data['fitting_room_products'] = array();

		if ($data['request_type'] == 'fitting_room') {
			$data['fitting_room_products'] = $this->getFittingRoomProducts();

			if (!$data['fitting_room_products']) {
				$json['error'][] = 'Ваша примерочная пуста. Добавьте хотя бы одно платье и попробуйте снова.';

				$this->response->addHeader('Content-Type: application/json');
				$this->response->setOutput(json_encode($json));

				return;
			}
		}

		if (isset($this->request->post['product_id']) && $this->request->post['product_id']) {
			
			$this->load->model('catalog/product');
			
			$data['product_info'] = $this->model_catalog_product->getProduct($this->request->post['product_id']);
		}

		$this->load->model('localisation/zone');

		$zone_id = isset($this->session->data['city_id']) ? (int)$this->session->data['city_id'] : (int)$this->config->get('config_zone_id');
		$zone = $this->model_localisation_zone->getZone($zone_id);

		$data['city'] = $zone ? $zone['name'] : '';
		
		$data['config_name'] = $this->config->get('config_name');
		$data['post'] = $this->request->post;
		
		$message = $this->load->view('mail/request', $data);
		$this->sendTG($message);
		
		$mail = new Mail($this->config->get('config_mail_engine'));
		$mail->parameter = $this->config->get('config_mail_parameter');
		$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
		$mail->smtp_username = $this->config->get('config_mail_smtp_username');
		$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
		$mail->smtp_port = $this->config->get('config_mail_smtp_port');
		$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');

		$mail->setTo($this->config->get('config_email'));
		$mail->setFrom($this->config->get('config_email'));
		$mail->setSender($this->config->get('config_name'));
		$mail->setSubject('Новая заявка');
		$mail->setHtml($message);
		
		$mail->send();
		
		if($this->config->get('config_mail_alert_email')){
			foreach(explode(",", $this->config->get('config_mail_alert_email')) as $email){
				$mail->setTo(trim($email));
				$mail->send();
			}
		}
		
		
			
		
		
		$json['success'] = true;
		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	private function getFittingRoomProducts() {
		$product_ids = array();

		if ($this->customer->isLogged()) {
			$this->load->model('account/wishlist');

			foreach ($this->model_account_wishlist->getWishlist() as $result) {
				$product_ids[] = (int)$result['product_id'];
			}
		} elseif (isset($this->session->data['wishlist']) && is_array($this->session->data['wishlist'])) {
			$product_ids = array_map('intval', $this->session->data['wishlist']);
		}

		$this->load->model('catalog/product');

		$products = array();

		foreach (array_unique($product_ids) as $product_id) {
			$product_info = $this->model_catalog_product->getProduct($product_id);

			if ($product_info) {
				$products[] = array(
					'name'  => $product_info['name'],
					'model' => $product_info['model'],
					'href'  => $this->url->link('product/product', 'product_id=' . (int)$product_id)
				);
			}
		}

		return $products;
	}
	
	private function sendTG($message){
		
		$message = str_replace(['<div>','</div>'], '', $message);
		$message = str_replace('<br>', PHP_EOL, $message);
		$message = strip_tags($message, ['b','i','u','s','a','code','pre']);
		
		
		$botToken = '6230708188:AAH5lLczb7oZ2xs8rTcRMchm1OxKZH7wLSo';
		$chatId = -1003452493446;
		
		 $url = "https://api.telegram.org/bot{$botToken}/sendMessage";

		// Параметры запроса
		$params = [
			'chat_id' => $chatId,
			'text' => $message,
			'parse_mode' => 'HTML',
		];

		// Инициализируем cURL
		$ch = curl_init($url);

		// Устанавливаем опции для cURL
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		// Выполняем запрос и получаем ответ
		$response = curl_exec($ch);

		// Закрываем cURL
		curl_close($ch);

		// Возвращаем ответ (можно использовать для отладки)
		return $response;
		
	}
}
