<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminOptions extends pjAdmin
{
    protected function pjActionCopySettings($source_calendar_id, $dest_calendar_id)
    {
        $pjOptionModel = pjOptionModel::factory();
        $src = $pjOptionModel->where('t1.foreign_id', $source_calendar_id)->where("(`key` != 'o_paypal_address' AND `key` != 'o_cut_off_day' AND `key` != 'o_cut_off_time')")->findAll()->getData();
        $src_pair = $pjOptionModel->getDataPair('key', 'value');
        $pjOptionModel->begin();
        foreach ($src as $option)
        {
            $pjOptionModel
            ->reset()
            ->where('foreign_id', $dest_calendar_id)
            ->where('`key`', $option['key'])
            ->limit(1)
            ->modifyAll(array('value' => $option['value']));
        }
        $pjOptionModel->commit();
        $fields = array('confirm_subject_client', 'confirm_tokens_client', 'payment_subject_client', 'payment_tokens_client',
            'confirm_subject_admin', 'confirm_tokens_admin', 'payment_subject_admin', 'payment_tokens_admin',
            'reminder_subject_client', 'reminder_tokens_client', 'confirm_sms_admin', 'payment_sms_admin',
            'reminder_sms_client', 'terms_url', 'terms_body'
        );
        if (!empty($fields))
        {
            $pjMultiLangModel = pjMultiLangModel::factory();
            
            $src = $pjMultiLangModel
            ->where('t1.model', 'pjCalendar')
            ->where('t1.foreign_id', $source_calendar_id)
            ->whereIn('t1.field', $fields)
            ->findAll()->getData();
            
            $pjMultiLangModel->begin();
            foreach ($src as $item)
            {
                $item['id'] = NULL;
                unset($item['id']);
                $item['foreign_id'] = $dest_calendar_id;
                
                $pjMultiLangModel->prepare(sprintf(
                    "INSERT INTO `%s` (`id`, `foreign_id`, `model`, `locale`, `field`, `content`)
							VALUES (NULL, :foreign_id, :model, :locale, :field, :content)
							ON DUPLICATE KEY UPDATE `content` = :content", $pjMultiLangModel->getTable())
                    )->exec($item);
            }
            $pjMultiLangModel->commit();
        }
    }
    
	public function pjActionCopy()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['calendar_id']) && (int) $_POST['calendar_id'] > 0 && isset($_POST['tab_id']) && (int) $_POST['tab_id'] > 0)
			{
				$pjOptionModel = pjOptionModel::factory();
	
				$src = $pjOptionModel->where('t1.foreign_id', $_POST['calendar_id'])->where('t1.tab_id', $_POST['tab_id'])->findAll()->getData();
				$src_pair = $pjOptionModel->getDataPair('key', 'value');
				$pjOptionModel->begin();
				foreach ($src as $option)
				{
					$pjOptionModel
						->reset()
						->where('foreign_id', $this->getForeignId())
						->where('`key`', $option['key'])
						->limit(1)
						->modifyAll(array('value' => $option['value']));
				}
				$pjOptionModel->commit();
	
				$fields = array();
				if ((int) $_POST['tab_id'] === 5)
				{
					$fields = array('confirm_subject_client', 'confirm_tokens_client', 'payment_subject_client', 'payment_tokens_client', 
									'confirm_subject_admin', 'confirm_tokens_admin', 'payment_subject_admin', 'payment_tokens_admin', 
									'reminder_subject_client', 'reminder_tokens_client', 'confirm_sms_admin', 'payment_sms_admin',
									'reminder_sms_client'
					);
				} elseif ((int) $_POST['tab_id'] === 6) {
					$fields = array('terms_url', 'terms_body');
				}
	
				if (!empty($fields))
				{
					$pjMultiLangModel = pjMultiLangModel::factory();
						
					$src = $pjMultiLangModel
						->where('t1.model', 'pjCalendar')
						->where('t1.foreign_id', $_POST['calendar_id'])
						->whereIn('t1.field', $fields)
						->findAll()->getData();
	
					$pjMultiLangModel->begin();
					foreach ($src as $item)
					{
						$item['id'] = NULL;
						unset($item['id']);
						$item['foreign_id'] = $this->getForeignId();
							
						$pjMultiLangModel->prepare(sprintf(
								"INSERT INTO `%s` (`id`, `foreign_id`, `model`, `locale`, `field`, `content`)
							VALUES (NULL, :foreign_id, :model, :locale, :field, :content)
							ON DUPLICATE KEY UPDATE `content` = :content", $pjMultiLangModel->getTable())
						)->exec($item);
					}
					$pjMultiLangModel->commit();
				}
			}
		}
		exit;
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();

		if (!$this->isAdmin() && !$this->isOwner())
		{
			$this->set('status', 2);
			return;
		}
		
		if (isset($_GET['cid']))
		{
			$this->setForeignId($_GET['cid']);
			pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminOptions&action=pjActionIndex&tab=" . $_GET['tab']);
		}
		
		if ($this->isOwner() && isset($_GET['tab']) && in_array((int) $_GET['tab'], array(1))) {
			pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminOptions&action=pjActionIndex&tab=3");
		}
		
		if (isset($_GET['tab']) && in_array((int) $_GET['tab'], array(5,6)))
		{
			$locale_arr = pjLocaleModel::factory()->select('t1.*, t2.file')
				->join('pjLocaleLanguage', 't2.iso=t1.language_iso', 'left')
				->where('t2.file IS NOT NULL')
				->orderBy('t1.sort ASC')->findAll()->getData();
					
			$lp_arr = array();
			foreach ($locale_arr as $v)
			{
				$lp_arr[$v['id']."_"] = $v['file'];
			}
			$this->set('lp_arr', $locale_arr);
			
			$arr = array();
			$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($this->getForeignId(), 'pjCalendar');
			$this->set('arr', $arr);
			
			if ((int) $this->option_arr['o_multi_lang'] === 1)
			{
				$this->set('locale_str', pjAppController::jsonEncode($lp_arr));
				$this->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			}
		} else {
			$tab_id = isset($_GET['tab']) && (int) $_GET['tab'] > 0 ? (int) $_GET['tab'] : 1;
			
			$arr = pjOptionModel::factory()
				->where("((t1.foreign_id='".$this->getForeignId()."' AND t1.`key` NOT IN('".implode("','", pjUtil::getCommonOptions())."')) OR (t1.foreign_id='0' AND t1.`key` IN('".implode("','", pjUtil::getCommonOptions())."')))")
				->where('tab_id', $tab_id)
				->orderBy('t1.order ASC')
				->findAll()
				->getData();
			
				foreach ($arr as &$row) {
					if (in_array($row['key'], ['o_stripe_secret_key', 'o_stripe_api_key']) && !empty($row['value'])) {
						$decrypted = $this->decrypt($row['value']);
						if ($decrypted === false || $decrypted === null) {
							$row['value_decrypted'] = 'DECRYPTION FAILED';
						} else {
							$row['value_decrypted'] = $decrypted;
							 
							$row['value_masked'] = $this->maskKey($decrypted, 2, 4);

						}
					}
				}

			$this->set('arr', $arr);
			
			$tmp = $this->models['Option']->reset()->where('foreign_id', $this->getForeignId())->findAll()->getData();
			$o_arr = array();
			foreach ($tmp as $item)
			{
				$o_arr[$item['key']] = $item;
			}
			$this->set('o_arr', $o_arr);
		}
		
		$this->appendCss('jquery.ui.timepicker.css', PJ_THIRD_PARTY_PATH . 'timepicker/');
		$this->appendJs('jquery.ui.timepicker.js', PJ_THIRD_PARTY_PATH . 'timepicker/');
		$this->appendJs('jquery.tipsy.js', PJ_THIRD_PARTY_PATH . 'tipsy/');
		$this->appendCss('jquery.tipsy.css', PJ_THIRD_PARTY_PATH . 'tipsy/');
		$this->appendJs('pjAdminOptions.js');
	}
	
	public function pjActionInstall()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			$locale_arr = pjLocaleModel::factory()->select('t1.*, t2.title')
				->join('pjLocaleLanguage', 't2.iso=t1.language_iso', 'left outer')
				->orderBy('t1.sort ASC')->findAll()->getData();
			$this->set('locale_arr', $locale_arr);

			$slot_length = 0;
			$is_weekly_ok = 1;
			
			$wt_arr = pjWorkingTimeModel::factory()
				->where('t1.foreign_id', $this->getForeignId())
				->limit(1)
				->findAll()
				->getDataIndex(0);
			if ($wt_arr !== FALSE)
			{
				foreach (array('monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday') as $weekday)
				{
					if ($wt_arr[$weekday.'_dayoff'] == 'T')
					{
						continue;
					}
					if ($slot_length == 0)
					{
						$slot_length = $wt_arr[$weekday.'_length'];
					}
					if ($slot_length != $wt_arr[$weekday.'_length'])
					{
						$is_weekly_ok = 0;
						break;
					}
				}
			}
			
			$dt_arr = pjDateModel::factory()
				->select('t1.slot_length')
				->where('t1.foreign_id', $this->getForeignId())
				->where('t1.is_dayoff', 'F')
				->groupBy('t1.slot_length')
				->findAll()
				->getData();
				
			foreach ($dt_arr as $data)
			{
				if ($slot_length == 0)
				{
					$slot_length = $data['slot_length'];
				}
				if ($slot_length != $data['slot_length'])
				{
					$is_weekly_ok = 0;
					break;
				}
			}
			$this->set('is_weekly_ok', $is_weekly_ok);
			
			$pjCalendarModel = pjCalendarModel::factory();
			if ($this->isOwner()) {
				$pjCalendarModel->where('t1.user_id', $this->getUserId());
			}
			$calendar_arr = $pjCalendarModel
				->select('t1.*, t2.content AS `title`')
				->join('pjMultiLang', "t2.model='pjCalendar' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left')
				->orderBy('t1.id ASC')
				->findAll()->getData();
			$this->set('calendar_arr', $calendar_arr);
			$this->set('user_arr', pjUserModel::factory()->orderBy('t1.name ASC')->findAll()->getData());
			
			$this->appendJs('pjAdminOptions.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetCalendars() {
		$this->setAjax(true);
		if ($this->isXHR()) {
			$pjCalendarModel = pjCalendarModel::factory();
			if (isset($_GET['owner_id']) && (int)$_GET['owner_id'] > 0) {
				$pjCalendarModel->where('t1.user_id', $_GET['owner_id']);
			}
			$calendar_arr = $pjCalendarModel
				->select('t1.*, t2.content AS `title`')
				->join('pjMultiLang', "t2.model='pjCalendar' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left')
				->orderBy('t1.id ASC')
				->findAll()->getData();
			$this->set('calendar_arr', $calendar_arr);
		}
	}

	public function pjActionPreview()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			$this->appendJs('pjAdminOptions.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	private function maskKey($key, $visibleStart, $visibleEnd)
		{
			$length = strlen($key);
			if ($length <= ($visibleStart + $visibleEnd)) {
				return str_repeat('x', $length);
			}

			$start = substr($key, 0, $visibleStart);
			$end = substr($key, -$visibleEnd);
			$masked = str_repeat('x', $length - ($visibleStart + $visibleEnd));

			return $start . $masked . $end;
		}


	private function encrypt11($data)
		{ 
			$encryption_key = $_POST['value-string-o_stripe_api_key']; // ✅ Replace with secure config/env value
			$iv = openssl_random_pseudo_bytes(16);
			$encrypted = openssl_encrypt($data, 'aes-256-cbc', $encryption_key, 0, $iv);
			return base64_encode($iv . $encrypted);
		}

	private function encryptKey($data)
		{  
			$encryption_key = $_POST['value-string-o_stripe_api_key'];
			$iv = openssl_random_pseudo_bytes(16);
			$encrypted = openssl_encrypt($data, 'aes-256-cbc', $encryption_key, 0, $iv);
			return base64_encode($iv . $encrypted);
		}
	private function encrypt($data)
		{
			$key = hash('sha256', PJ_SALT, true); // derive 256-bit key
			$iv = openssl_random_pseudo_bytes(16);
			$encrypted = openssl_encrypt($data, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
			return base64_encode($iv . $encrypted);
		}

	private function decrypt($data)
		{
			$key = hash('sha256', PJ_SALT, true);
			$data = base64_decode($data);
			$iv = substr($data, 0, 16);
			$ciphertext = substr($data, 16);
			return openssl_decrypt($ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
		}


	public function pjActionUpdate()
	{ 
		$this->checkLogin();

		if (!$this->isAdmin() && !$this->isOwner())
		{
			$this->set('status', 2);
			return;
		}

		if (isset($_POST['options_update']))
		{
			if (isset($_POST['tab']) && in_array($_POST['tab'], array(5, 6)))
			{
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $this->getForeignId(), 'pjCalendar', 'data');
				}
			} else {
				$OptionModel = new pjOptionModel();
				$OptionModel
					->where('foreign_id', $this->getForeignId())
					->where('type', 'bool')
					->where('tab_id', $_POST['tab'])
					->modifyAll(array('value' => '1|0::0'));

				foreach ($_POST as $key => $value)
				{
					if (preg_match('/value-(string|text|int|float|enum|bool|color)-(.*)/', $key) === 1)
					{
						list(, $type, $k) = explode("-", $key);
						if (!empty($k))
						{
							
							if (in_array($k, ['o_stripe_secret_key', 'o_stripe_api_key']) && !empty($value)) {
								// Check if value is a masked placeholder (e.g., skxxxxxxxxxxxx or pkxxxxxxxxxxxx)
								if (preg_match('/^(sk|pk)x{6,}/i', $value)) {
									// Value is masked – use existing encrypted one
									$existing = pjOptionModel::factory()
										->reset()
										->where('foreign_id', $this->getForeignId())
										->where('`key`', $k)
										->limit(1)
										->findAll()
										->getData();

									if (!empty($existing)) {
										$value = $existing[0]['value'];
									} else {
										$value = ''; // fallback if no record found
									}
								} else {
									// New value entered – encrypt it
									$value = $this->encrypt($value);
								}
							}

							

							// if ($k == 'o_stripe_secret_key' && !empty($value)) {

							// 	print_r($value); die();
							// 	$value = $this->encrypt($value);

							// }

							// if ($k == 'o_stripe_api_key' && !empty($value)) {
							// 	$value = $this->encrypt($value);
							// }
							
							if(in_array($k, pjUtil::getCommonOptions()))
							{
								$OptionModel
									->reset()
									->where('foreign_id', 0)
									->where('`key`', $k)
									->limit(1)
									->modifyAll(array(
										'value' => $OptionModel->escape($value, null, $type)
									));
							}
							else
							{
								if ($k == 'o_cut_off_time') {
									$value = ':NULL';
									if (!empty($_POST['value-string-o_cut_off_time'])) {
										$value = date('H:i', strtotime($_POST['value-string-o_cut_off_time']));
									}
								}

								$exist = $OptionModel->reset()->where('foreign_id', $this->getForeignId())->where('`key`', $k)->findCount()->getData();

								if (!$exist) {
									$OptionModel
										->reset()
										->setAttributes(array(
											'foreign_id' => $this->getForeignId(),
											'key'        => $k,
											'tab_id'     => $_POST['tab'],
											'value'      => $value,
											'type'       => $type,
											'order'      => 99,
											'is_visible' => 0
										))
										->insert();
								} else {
									$OptionModel
										->reset()
										->where('foreign_id', $this->getForeignId())
										->where('`key`', $k)
										->limit(1)
										->modifyAll(array(
											'value' => $OptionModel->escape($value, null, $type)
										));
								}
							}
						}
					}
				}
			}

			if (isset($_POST['tab']))
			{
				switch ($_POST['tab'])
				{
					case '1': $err = 'AO01'; break;
					case '2': $err = 'AO02'; break;
					case '3': $err = 'AO03'; break;
					case '4': $err = 'AO04'; break;
					case '5': $err = 'AO05'; break;
					case '6': $err = 'AO06'; break;
					case '7': $err = 'AO07'; break;
					case '8': $err = 'AO08'; break;
				}
			}

			$pjCalendarModel = pjCalendarModel::factory();
			$calendar = $pjCalendarModel->find($this->getForeignId())->getData();
			$owner_id = $calendar['user_id'];
			$calendar_arr = $pjCalendarModel->reset()->where('user_id', $owner_id)->where('id <>', $this->getForeignId())->findAll()->getDataPair(null, 'id');

			foreach($calendar_arr as $calendar_id)
			{
				$this->pjActionCopySettings($this->getForeignId(), $calendar_id);
			}

			pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminOptions&action=" . @$_POST['next_action'] . "&tab=" . @$_POST['tab'] . "&err=$err");
		}
	}


	// public function pjActionUpdateOld()
	// {
	// 	echo "<pre>"; print_r($_POST); echo "</pre>";
	// 	$this->checkLogin();

	// 	if (!$this->isAdmin() && !$this->isOwner())
	// 	{
	// 		$this->set('status', 2);
	// 		return;
	// 	}
		
	// 	if (isset($_POST['options_update']))
	// 	{
	// 		if (isset($_POST['tab']) && in_array($_POST['tab'], array(5, 6)))
	// 		{
	// 			if (isset($_POST['i18n']))
	// 			{
	// 				pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $this->getForeignId(), 'pjCalendar', 'data');
	// 			}
	// 		} else {
	// 			$OptionModel = new pjOptionModel();
	// 			$OptionModel
	// 				->where('foreign_id', $this->getForeignId())
	// 				->where('type', 'bool')
	// 				->where('tab_id', $_POST['tab'])
	// 				->modifyAll(array('value' => '1|0::0'));
					
	// 			foreach ($_POST as $key => $value)
	// 			{
	// 				if (preg_match('/value-(string|text|int|float|enum|bool|color)-(.*)/', $key) === 1)
	// 				{
	// 					list(, $type, $k) = explode("-", $key);
	// 					if (!empty($k))
	// 					{
	// 						if(in_array($k, pjUtil::getCommonOptions()))
	// 						{
	// 							$OptionModel
	// 								->reset()
	// 								->where('foreign_id', 0)
	// 								->where('`key`', $k)
	// 								->limit(1)
	// 								->modifyAll(array(
	// 									'value' => $OptionModel->escape($value, null, $type)
	// 								));
	// 						}else{
	// 						    if($k == 'o_cut_off_time')
	// 						    {
    // 							    $value = ':NULL';
    // 							    if(!empty($_POST['value-string-o_cut_off_time']))
    // 							    {
    // 							        $value = date('H:i', strtotime($_POST['value-string-o_cut_off_time']));
    // 							    }
	// 						    }
	// 							$exist = $OptionModel->reset()->where('foreign_id', $this->getForeignId())->where('`key`', $k)->findCount()->getData();
	// 							echo "<pre>"; print_r($k); echo "</pre>";
								
	// 							if (!$exist) {
	// 								$OptionModel
	// 									->reset()
	// 									->setAttributes(array(
	// 										'foreign_id' => $this->getForeignId(),
	// 										'key'      => $k,
	// 										'tab_id'     => $_POST['tab'],
	// 										'value'      => $value,
	// 										'type'       => $type,
	// 										'order'      => 99,
	// 										'is_visible' => 0
	// 									))
	// 									->insert();
	// 							}
	// 							else {
	// 							$OptionModel
	// 								->reset()
	// 								->where('foreign_id', $this->getForeignId())
	// 								->where('`key`', $k)
	// 								->limit(1)
	// 								->modifyAll(array(
	// 									'value' => $OptionModel->escape($value, null, $type)
	// 								));
	// 						}
	// 					}
	// 				}
	// 			}
	// 		}
	// 		} die('okk');
	// 		if (isset($_POST['tab']))
	// 		{
	// 			switch ($_POST['tab'])
	// 			{
	// 				case '1':
	// 					$err = 'AO01';
	// 					break;
	// 				case '2':
	// 					$err = 'AO02';
	// 					break;
	// 				case '3':
	// 					$err = 'AO03';
	// 					break;
	// 				case '4':
	// 					$err = 'AO04';
	// 					break;
	// 				case '5':
	// 					$err = 'AO05';
	// 					break;
	// 				case '6':
	// 					$err = 'AO06';
	// 					break;
	// 				case '7':
	// 					$err = 'AO07';
	// 					break;
	// 				case '8':
	// 					$err = 'AO08';
	// 					break;
	// 			}
	// 		}
	// 		$pjCalendarModel = pjCalendarModel::factory();
	// 		$calendar = $pjCalendarModel->find($this->getForeignId())->getData();
	// 		$owner_id = $calendar['user_id'];
	// 		$calendar_arr = $pjCalendarModel->reset()->where('user_id', $owner_id)->where('id <>', $this->getForeignId())->findAll()->getDataPair(null, 'id');
	// 		foreach($calendar_arr as $calendar_id)
	// 		{
	// 		    $this->pjActionCopySettings($this->getForeignId(), $calendar_id);
	// 		}
	// 		pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminOptions&action=" . @$_POST['next_action'] . "&tab=" . @$_POST['tab'] . "&err=$err");
	// 	}
	// }
	
	public function pjActionUpdateTheme()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			pjOptionModel::factory()
				->where('foreign_id', 0)
				->where('`key`', 'o_theme')
				->limit(1)
				->modifyAll(array('value' => 'theme1|theme2|theme3|theme4|theme5|theme6|theme7|theme8|theme9|theme10::theme' . $_GET['theme']));
	
		}
	}
}
?>