<?php
/**
 * @copyright    OCTemplates
 * @support      https://octemplates.net/
 * @license      LICENSE.txt
 */

class ControllerOCTemplatesModuleOctPopupCallPhone extends Controller {
	private $error = [];

    public function index() {
	    if ($this->config->get('oct_popup_call_phone_status') && isset($this->request->server['HTTP_X_REQUESTED_WITH']) && !empty($this->request->server['HTTP_X_REQUESTED_WITH']) && strtolower($this->request->server['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
	        $this->load->language('octemplates/module/oct_popup_call_phone');

	        $data['oct_popup_call_phone_data'] = $oct_popup_call_phone_data = $this->config->get('oct_popup_call_phone_data');

	        $data['name']      = $this->customer->isLogged() ? $this->customer->getFirstName() : '';
	        
	        $telephone = $this->customer->isLogged() ? $this->customer->getTelephone() : '';
	        if ($telephone) {
	            $telephone = preg_replace('/[^0-9+]/', '', $telephone);
	        }
	        $data['telephone'] = $telephone;

			$data['comment'] = '';
			
			$oct_promo_data = $this->config->get('theme_oct_promo_data');
			$phone_masks = [];
			$allowed_countries = [];

			if (isset($oct_promo_data['phone_countries']) && is_array($oct_promo_data['phone_countries'])) {
				foreach ($oct_promo_data['phone_countries'] as $country) {
					if (!empty($country['country_code']) && !empty($country['mask'])) {
						$country_code_lower = strtolower($country['country_code']);
						$phone_masks[$country_code_lower] = [
							'mask' => $country['mask'],
							'regex' => !empty($country['regex']) ? $country['regex'] : ''
						];
						$allowed_countries[] = $country_code_lower;
					}
				}
			}
			$data['phone_masks'] = json_encode($phone_masks);
			$data['allowed_countries'] = json_encode($allowed_countries);

			$data['default_phone_country'] = !empty($oct_promo_data['default_phone_country'])
				? strtolower($oct_promo_data['default_phone_country'])
				: 'ua';
			if ($this->config->get('config_account_id')) {
				$this->load->model('catalog/information');

				$information_info = $this->model_catalog_information->getInformation($this->config->get('config_account_id'));

				if ($information_info) {
					$data['text_terms'] = sprintf($this->language->get('text_oct_terms'), $this->url->link('information/information', 'information_id=' . $this->config->get('config_account_id'), 'SSL'), $information_info['title'], $information_info['title']);
				} else {
					$data['text_terms'] = '';
				}
			} else {
				$data['text_terms'] = '';
			}

			if ($this->config->get('captcha_' . $this->config->get('config_captcha') . '_status') && in_array('oct_popup_call_phone', (array)$this->config->get('config_captcha_page'))) {
				$data['captcha'] = $this->load->controller('extension/captcha/' . $this->config->get('config_captcha'));
			} else {
				$data['captcha'] = '';
			}

			$data['ajax_send_url'] = str_replace('&amp;', '&', $this->url->link('octemplates/module/oct_popup_call_phone/send'));

	        $this->response->setOutput($this->load->view('octemplates/module/oct_popup_call_phone', $data));
        } else {
	        $this->response->redirect($this->url->link('error/not_found', '', true));
        }
    }

	public function send() {
		if ($this->config->get('oct_popup_call_phone_status') && isset($this->request->server['HTTP_X_REQUESTED_WITH']) && !empty($this->request->server['HTTP_X_REQUESTED_WITH']) && strtolower($this->request->server['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
			$json = [];

			$this->language->load('octemplates/module/oct_popup_call_phone');

			if ($this->validate()) {
				$this->load->model('octemplates/module/oct_popup_call_phone');

				$oct_popup_call_phone_data = $this->config->get('oct_popup_call_phone_data');

				$data = [];

				if (isset($this->request->post['name'])) {
					$data[] = [
						'name' => $this->language->get('enter_name'),
						'value' => $this->request->post['name']
					];
				}

				if (isset($this->request->post['telephone'])) {
					$data[] = [
						'name' => $this->language->get('enter_telephone'),
						'value' => $this->request->post['telephone']
					];
				}

				if (isset($this->request->post['comment'])) {
					$comment = strip_tags($this->request->post['comment']);
					$comment = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $comment);

					$data[] = [
						'name' => $this->language->get('enter_comment'),
						'value' => $comment
					];
				}

				if (isset($this->request->post['url_page'])) {
					$data[] = [
						'name' => $this->language->get('enter_url_page'),
						'value' => $this->request->post['url_page']
					];
				}

				$data_send = [
					'info' => serialize($data)
				];

				$this->model_octemplates_module_oct_popup_call_phone->addRequest($data_send);

				if (isset($oct_popup_call_phone_data['notify_status']) && $oct_popup_call_phone_data['notify_status']) {
					$html_data['date_added'] = date('d.m.Y H:i:s', time());
					$html_data['logo'] = $this->config->get('config_url') . 'image/' . $this->config->get('config_logo');
					$html_data['store_name'] = $this->config->get('config_name');
					$html_data['store_url'] = $this->config->get('config_url');
					$html_data['text_info'] = $this->language->get('text_info');
					$html_data['text_date_added'] = $this->language->get('text_date_added');
					$html_data['data_info'] = $data;

					$html = $this->load->view('octemplates/mail/oct_popup_call_phone_mail', $html_data);

					$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->setFrom($this->config->get('config_email'));
					$mail->setSender($this->config->get('config_name'));
					$mail->setSubject($this->language->get('heading_title') . " -- " . $html_data['date_added']);
					$mail->setHtml($html);

					$emails = explode(',', $oct_popup_call_phone_data['notify_email']);

					foreach ($emails as $email) {
						if ($email && preg_match('/^[^\@]+@.*.[a-z]{2,15}$/i', $email)) {
							$mail->setTo($email);
							$mail->send();
						}
					}

					$oct_sms_settings = $this->config->get('oct_sms_settings');
					$template_code = 'oct_popup_call_phone';
					$language_id = (int)$this->config->get('config_language_id');

					if (isset($oct_sms_settings['templates'][$template_code]['status']) && $oct_sms_settings['templates'][$template_code]['status']) {
						if (isset($oct_sms_settings['templates'][$template_code]['message'][$language_id]) && !empty($oct_sms_settings['templates'][$template_code]['message'][$language_id]) && isset($oct_sms_settings['templates'][$template_code]['edit_localization'])) {
							$sms_template = $oct_sms_settings['templates'][$template_code]['message'][$language_id];
						} else {
							$sms_template = $this->language->get('default_sms_template_admin');
						}

						if (!empty($sms_template)) {
							$customer_name = '';
							if (isset($this->request->post['name'])) {
								$customer_name = strip_tags($this->request->post['name']);
								$customer_name = mb_substr($customer_name, 0, 50);
							}

							$telephone = '';
							if (isset($this->request->post['telephone'])) {
								$telephone = strip_tags($this->request->post['telephone']);
								$telephone = mb_substr($telephone, 0, 20);
							}

							$url_page = '';
							if (isset($this->request->post['url_page'])) {
								$url_page = filter_var($this->request->post['url_page'], FILTER_SANITIZE_URL);
								if (filter_var($url_page, FILTER_VALIDATE_URL)) {
									$url_page = mb_substr($url_page, 0, 200);
								} else {
									$url_page = '';
								}
							}

							$replace = array(
								'[customer_name]' => $customer_name,
								'[telephone]' => $telephone,
								'[url_page]' => $url_page,
								'[store]' => $this->config->get('config_name')
							);

							$sms_message = str_replace(array_keys($replace), array_values($replace), $sms_template);

							if (!empty($oct_sms_settings['admin_phone']) && !empty($oct_sms_settings['oct_sms_token'])) {
								$this->load->model('octemplates/module/oct_sms_notify');

								$this->model_octemplates_module_oct_sms_notify->sendNotification(array(
									'phone' => $oct_sms_settings['admin_phone'],
									'message' => $sms_message,
									'template_code' => $template_code,
									'access_token' => $oct_sms_settings['oct_sms_token']
								));
							}
						}
					}
				}

				$json['output'] = $this->language->get('text_success_send');
			} else {
				$json['error'] = $this->error;
			}

			$this->response->addHeader('Content-Type: application/json');
			$this->response->setOutput(json_encode($json));
		} else {
			$this->response->redirect($this->url->link('error/not_found', '', true));
		}
	}

    protected function validate() {
    	$oct_popup_call_phone_data = $this->config->get('oct_popup_call_phone_data');

        if (isset($this->request->post['name']) && (isset($oct_popup_call_phone_data['name']) && $oct_popup_call_phone_data['name'] == 2) && (utf8_strlen(trim($this->request->post['name'])) < 1 || utf8_strlen(trim($this->request->post['name'])) > 32)) {
			$this->error['name'] = $this->language->get('error_name');
		}

		if (isset($this->request->post['telephone'])) {
			$postedTelephone = $this->request->post['telephone'] ?? '';
			$oct_promo_data  = $this->config->get('theme_oct_promo_data');
			
			$cleanPhoneDigits = preg_replace('/[^0-9]/', '', $postedTelephone);
			
			$telephone_setting = $oct_popup_call_phone_data['telephone'] ?? '';

			if ($telephone_setting == 2) {
				if (utf8_strlen($cleanPhoneDigits) < 3 || utf8_strlen($cleanPhoneDigits) > 15) {
					$this->error['telephone'] = $this->language->get('error_telephone');
				} else {
					$isValid = false;
					$hasAnyRegex = false;

					if (isset($oct_promo_data['phone_countries']) && is_array($oct_promo_data['phone_countries'])) {
						foreach ($oct_promo_data['phone_countries'] as $country) {
							if (!empty($country['regex'])) {
								$hasAnyRegex = true;
								$regex = $country['regex'];

								$regex = str_replace('\\+', '', $regex);

								if (substr($regex, 0, 1) !== '/') {
									$regex = '/' . $regex . '/';
								}

								if (@preg_match($regex, '') !== false) {
									if (preg_match($regex, $cleanPhoneDigits)) {
										$isValid = true;
										break;
									}
								}
							}
						}
					}
					
					if (!$hasAnyRegex) {
						$isValid = true;
					} elseif (!$isValid) {
						$this->error['telephone'] = $this->language->get('error_telephone_mask');
					}
				}
			}
		}

        if ($this->config->get('config_account_id') && !isset($this->request->post['agree'])) {
            $this->load->model('catalog/information');

            $information_info = $this->model_catalog_information->getInformation($this->config->get('config_account_id'));

			if (isset($information_info) && !empty($information_info)) {
				$this->error['agree'] = sprintf($this->language->get('error_oct_terms'), $information_info['title']);
			}
        }

		if ($this->config->get('captcha_' . $this->config->get('config_captcha') . '_status') && in_array('oct_popup_call_phone', (array)$this->config->get('config_captcha_page'))) {
			$captcha = $this->load->controller('extension/captcha/' . $this->config->get('config_captcha') . '/validate');

			if ($captcha) {
				$this->error['captcha'] = $captcha;
			}
		}

	    return !$this->error;
    }
}
