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

class ControllerOCTemplatesModuleOctPopupLogin extends Controller {
	public function index() {
		if (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_login');
			$this->load->language('octemplates/module/oct_otp_login');

			$data['register_url'] = $this->url->link('account/register', '', true);
			$data['forgotten_url'] = $this->url->link('account/forgotten', '', true);
			$data['account_url'] = $this->url->link('account/account', '', true);

			if (isset($this->request->post['redirect']) && (strpos($this->request->post['redirect'], $this->config->get('config_url')) !== false || strpos($this->request->post['redirect'], $this->config->get('config_ssl')) !== false)) {
				$data['redirect'] = $this->request->post['redirect'];
			} elseif (isset($this->session->data['redirect'])) {
				$data['redirect'] = $this->session->data['redirect'];

				unset($this->session->data['redirect']);
			} else {
				if (isset($this->request->server['HTTP_REFERER'])) {
					$data['redirect'] = $this->request->server['HTTP_REFERER'];
				} else {
					$data['redirect'] = '';
				}
			}

			$oct_otp_login_data = $this->getOtpSettings();

			$csrf_token = bin2hex(random_bytes(32));
			$this->session->data['csrf_token'] = $csrf_token;
			$data['csrf_token'] = $csrf_token;

			if (isset($oct_otp_login_data['status']) && $oct_otp_login_data['status']) {
				$data['action_send_otp'] = $this->url->link('octemplates/module/oct_otp_login/sendOtp', '', true);
				$data['action_verify_otp'] = $this->url->link('octemplates/module/oct_otp_login/verifyOtp', '', true);
				$data['otp_module_status'] = $oct_otp_login_data['status'] ?? false;

				$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';
			}

			$data['otp_email_enabled'] = $oct_otp_login_data['otp_email'] ?? false;
			$data['otp_length'] = $oct_otp_login_data['otp_length'] ?? 6;
			$data['action_verify_email_otp'] = $this->url->link('octemplates/module/oct_otp_login/verifyEmailOtp', '', true);

			$data['ajax_login_url'] = str_replace('&amp;', '&', $this->url->link('octemplates/module/oct_popup_login/login'));

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

	public function account() {
		if (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('extension/module/account');

			$data['logged'] = $this->customer->isLogged();
			$data['register'] = $this->url->link('account/register', '', true);
			$data['login'] = $this->url->link('account/login', '', true);
			$data['logout'] = $this->url->link('account/logout', '', true);
			$data['forgotten'] = $this->url->link('account/forgotten', '', true);
			$data['account'] = $this->url->link('account/account', '', true);
			$data['edit'] = $this->url->link('account/edit', '', true);
			$data['password'] = $this->url->link('account/password', '', true);
			$data['address'] = $this->url->link('account/address', '', true);
			$data['wishlist'] = $this->url->link('account/wishlist');
			$data['order'] = $this->url->link('account/order', '', true);
			$data['download'] = $this->url->link('account/download', '', true);
			$data['reward'] = $this->url->link('account/reward', '', true);
			$data['return'] = $this->url->link('account/return', '', true);
			$data['transaction'] = $this->url->link('account/transaction', '', true);
			$data['newsletter'] = $this->url->link('account/newsletter', '', true);
			$data['recurring'] = $this->url->link('account/recurring', '', true);

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

				$affiliate_info = $this->model_account_customer->getAffiliate($this->customer->getId());

				if (!$affiliate_info) {
					$data['affiliate'] = $this->url->link('account/affiliate/add', '', true);
					$data['tracking'] = '';
				} else {
					$data['affiliate'] = $this->url->link('account/affiliate/edit', '', true);
					$data['tracking'] = $this->url->link('account/tracking', '', true);
				}
			} else {
				$data['affiliate'] = $this->url->link('affiliate/login', '', true);
			}

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

	public function login() {
		if (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_login');
			$this->language->load('octemplates/module/oct_otp_login');
			$this->load->model('account/customer');

			if (!isset($this->request->post['email']) && empty($this->request->post['email'])) {
				$json['warning'] = $this->language->get('error_invalid_email');
				$this->response->addHeader('Content-Type: application/json');
				$this->response->setOutput(json_encode($json));
				return;
			}

			if (!isset($this->request->post['csrf_token']) || !isset($this->session->data['csrf_token']) || $this->request->post['csrf_token'] !== $this->session->data['csrf_token']) {
				$json['warning'] = $this->language->get('error_csrf');
				$this->response->addHeader('Content-Type: application/json');
				$this->response->setOutput(json_encode($json));
				return;
			}

			$login_info = $this->model_account_customer->getLoginAttempts($this->request->post['email']);

			if ($login_info && ($login_info['total'] >= $this->config->get('config_login_attempts')) && strtotime('-1 hour') < strtotime($login_info['date_modified'])) {
				$json['warning'] = $this->language->get('error_attempts');
			}

			$customer_info = $this->model_account_customer->getCustomerByEmail($this->request->post['email']);

			if ($customer_info && !$customer_info['status']) {
				$json['warning'] = $this->language->get('error_approved');
			}

			if (!isset($this->request->post['password']) || utf8_strlen(trim($this->request->post['password'])) < 2) {
				$json['warning'] = $this->language->get('error_invalid_password');
			}

			if (!isset($this->request->post['email']) || !preg_match('/^[^\@]+@.*.[a-z]{2,15}$/i', $this->request->post['email'])) {
				$json['warning'] = $this->language->get('error_invalid_email');
			}

			$json['redirect'] = '';

			if (!isset($json['warning'])) {
				$otp_email_enabled = $this->getOtpSettings('otp_email', false);

				if ($otp_email_enabled) {
					$customer_info = $this->validateCredentials($this->request->post['email'], $this->request->post['password']);
					
					if ($customer_info) {
						$this->load->model('octemplates/module/oct_otp_login');

						$otp_code = $this->generateOtpCode($customer_info['customer_id']);
						$this->sendEmailOtp($customer_info['email'], $otp_code, $customer_info['firstname']);

						$this->session->data['otp_customer_id'] = $customer_info['customer_id'];
						$this->session->data['otp_customer_email'] = $customer_info['email'];

						if (isset($this->request->post['redirect'])) {
							$redirect = $this->request->post['redirect'];
							$config_url = $this->config->get('config_url');
							$config_ssl = $this->config->get('config_ssl');
							
							if ($this->isValidRedirect($redirect, $config_url, $config_ssl)) {
								$this->session->data['otp_redirect'] = $redirect;
							} else {
								$this->session->data['otp_redirect'] = $this->url->link('account/account', '', true);
							}
						} else {
							$this->session->data['otp_redirect'] = $this->url->link('account/account', '', true);
						}

						$json['otp_required'] = true;
						$json['masked_email'] = $this->maskEmail($customer_info['email']);
						$json['message'] = $this->language->get('text_otp_email_sent');
					} else {
						$json['warning'] = $this->language->get('error_login');
						$this->model_account_customer->addLoginAttempt($this->request->post['email']);
					}
				} else {
					if (!$this->customer->login($this->request->post['email'], $this->request->post['password'])) {
						$json['warning'] = $this->language->get('error_login');
						$this->model_account_customer->addLoginAttempt($this->request->post['email']);
					} else {
						unset($this->session->data['guest']);
						unset($this->session->data['csrf_token']);

						$this->load->model('account/address');

						if ($this->config->get('config_tax_customer') == 'payment') {
							$this->session->data['payment_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
						}

						if ($this->config->get('config_tax_customer') == 'shipping') {
							$this->session->data['shipping_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
						}

						if (isset($this->session->data['wishlist']) && is_array($this->session->data['wishlist'])) {
							$this->load->model('account/wishlist');

							foreach ($this->session->data['wishlist'] as $key => $product_id) {
								$this->model_account_wishlist->addWishlist($product_id);
								unset($this->session->data['wishlist'][$key]);
							}
						}

						if (isset($this->request->post['redirect']) && $this->request->post['redirect'] != $this->url->link('account/logout', '', true) && (strpos($this->request->post['redirect'], $this->config->get('config_url')) !== false || strpos($this->request->post['redirect'], $this->config->get('config_ssl')) !== false)) {
							$json['redirect'] = str_replace('&amp;', '&', $this->request->post['redirect']);
						}

						$this->model_account_customer->deleteLoginAttempts($this->request->post['email']);
					}
				}
			}

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

	private function isValidRedirect($redirect, $config_url, $config_ssl) {
		$parsed = parse_url($redirect);
		$allowed_hosts = [parse_url($config_url, PHP_URL_HOST), parse_url($config_ssl, PHP_URL_HOST)];
		return isset($parsed['host']) && in_array($parsed['host'], $allowed_hosts);
	}
	
	private function validateCredentials($email, $password) {
		$this->load->model('account/customer');
		
		$customer_info = $this->model_account_customer->getCustomerByEmail($email);
		
		if (!$customer_info) {
			return false;
		}
		
		if (!$customer_info['status']) {
			return false;
		}
		
		if (isset($customer_info['salt']) && $customer_info['salt']) {
			$password_hash = sha1($customer_info['salt'] . sha1($customer_info['salt'] . sha1($password)));
		} else {
			$password_hash = sha1($password);
		}
		
		if (!hash_equals($password_hash, $customer_info['password'])) {
			return false;
		}
		
		return $customer_info;
	}

	private function generateOtpCode($customer_id) {
		$this->load->model('octemplates/module/oct_otp_login');

		$otp_length = (int)$this->getOtpSettings('otp_length', 6);
		$otp_code = random_int(pow(10, $otp_length - 1), pow(10, $otp_length) - 1);

		$hashed_otp_code = hash('sha256', $otp_code);
		$expires_at = date('Y-m-d H:i:s', time() + $this->getOtpSettings('otp_expiry', 5) * 60);

		$this->model_octemplates_module_oct_otp_login->createOtp($customer_id, $hashed_otp_code, $expires_at);

		return $otp_code;
	}

	private function sendEmailOtp($email, $otp_code, $firstname = '') {
		$this->load->language('octemplates/module/oct_otp_login');

		$subject = $this->language->get('email_otp_subject');
		$message = sprintf($this->language->get('email_otp_message'), $firstname, $otp_code, $this->config->get('config_name'));

		$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($email);
		$mail->setFrom($this->config->get('config_email'));
		$mail->setSender(html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8'));
		$mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
		$mail->setText($message);
		$mail->send();
	}

	private function maskEmail($email) {
		$parts = explode('@', $email);
		if (count($parts) !== 2) {
			return $email;
		}

		$name = $parts[0];
		$domain = $parts[1];

		$name_length = strlen($name);
		if ($name_length <= 2) {
			$masked_name = $name[0] . str_repeat('*', $name_length - 1);
		} else {
			$visible_chars = max(1, floor($name_length * 0.3));
			$masked_name = substr($name, 0, $visible_chars) . str_repeat('*', $name_length - $visible_chars);
		}

		return $masked_name . '@' . $domain;
	}

	private function getOtpSettings($key = null, $default = null) {
		$settings = $this->config->get('oct_otp_login_settings');
		return $key ? ($settings[$key] ?? $default) : $settings;
	}
}