<?php

namespace Vinteract;

use Exception;
use InvalidArgumentException;

use \Vinteract\DB;
use \Vinteract\Utils;
use \Vinteract\Payments\Payments;

use Illuminate\Database\Capsule\Manager as Capsule;

class Client {
	
	/*
		Properties
	*/
	
	public static $db;
	
	private static $public_id;
	
	private static $type;
	private static $name;
	private static $id;
	
	private static $data = [];
	
	private static $databaseConnections = [
		"default" => [
			"driver" => "mysql",
			"host" => "localhost", //"legacy-vinteract-database.cgrmswx93nt2.ap-southeast-2.rds.amazonaws.com",
			"database" => "vstaging_v_global",
			"username" => "vstaging_churches",
			"password" => "k+CdX,lTlo0[",
			"charset" => "utf8",
			"collation" => "utf8_unicode_ci",
			"prefix" => "",
		],
		"churches" => [
			"driver" => "mysql",
			"host" => "localhost", //"legacy-vinteract-database.cgrmswx93nt2.ap-southeast-2.rds.amazonaws.com",
			"database" => "vstaging_v_churches",
			"username" => "vstaging_churches",
			"password" => "k+CdX,lTlo0[",
			"charset" => "utf8",
			"collation" => "utf8_unicode_ci",
			"prefix" => "",
		],
		"businesses" => [
			"driver" => "mysql",
			"host" => "localhost", //"legacy-vinteract-database.cgrmswx93nt2.ap-southeast-2.rds.amazonaws.com",
			"database" => "vstaging_v_businesses",
			"username" => "vstaging_churches",
			"password" => "k+CdX,lTlo0[",
			"charset" => "utf8",
			"collation" => "utf8_unicode_ci",
			"prefix" => "",
		],
	];
	
	/*
		Methods
	*/
	
	public static function ready() {
		return count(self::$data) > 0;
	}
	
	public static function init($public_id = null) {
		
		// Load database.
		
		self::$db = new DB(self::getDatabaseConnections());
		
		// See if this client is a church.
		
		$church = self::$db->capsule->table("global_churches")->where("public_id", $public_id)->first();
		
		if (isset($church) and property_exists($church, "id")) {
			
			$type = "churches";
			
			self::__set_public_id($public_id);
			self::__set_type($type);
			self::__set_name($church->title);
			self::__set_id($church->id);
			self::__set_data($church);
			
			self::$db->connect($type);
			
		}
		
		// See if this client is a business.
		
		$business = self::$db->capsule->table("global_businesses")->where("public_id", $public_id)->first();
		
		if (isset($business) and property_exists($business, "id")) {
			
			$type = "businesses";
			
			self::__set_public_id($public_id);
			self::__set_type($type);
			self::__set_name($business->title);
			self::__set_id($business->id);
			self::__set_data($business);
			
			self::$db->connect($type);
			
		}
		
		// Check if the client failed to load.
		
		if (!self::ready()) {
			throw new Exception("Client couldn't be loaded: {$public_id}");
		}
		
	}
	
	public static function setDatabaseConnections($databaseConnections = []) {
		foreach($databaseConnections as $connection => $values) {
			if (array_key_exists($connection, self::$databaseConnections)) {
				foreach($values as $key => $value) {
					self::$databaseConnections[$connection][$key] = $value;
				}
			}
		}
	}
	
	public static function getDatabaseConnections() {
		return self::$databaseConnections;
	}
	
	public static function db($connection_name = "default") {
		return self::$db
			->capsule
			->getConnection($connection_name);
	}
	
	public static function local($table) {
		return self::db(self::getType())
			->table(self::getName() . "_{$table}");
	}
	
	public static function global($table) {
		return self::db()
			->table($table);
	}
	
	public static function update($data) {
		return self::global("global_" . self::getType())->wherePublicId(self::getPublicId())->update($data);
	}
	
	public static function findByKey($key, $value) {
		return self::global("global_" . self::getType())->where($key, $value)->exists();
	}
	
	public static function isChurch() {
		return self::getType() === "churches";
	}
	
	public static function isBusiness() {
		return self::getType() === "businesses";
	}
	
	public static function isPaymentsPlatformOnly() {
		return self::isPaymentsPlatformEnabled() and (!self::isWebsitePlatformEnabled() and !self::isEnterpriseAppPlatformEnabled() and !self::isChurchCentralPlatformEnabled());
	}
	
	public static function isWebsitePlatformOnly() {
		return self::isWebsitePlatformEnabled() and (!self::isPaymentsPlatformEnabled() and !self::isEnterpriseAppPlatformEnabled() and !self::isChurchCentralPlatformEnabled());
	}
	
	public static function isAppPlatformOnly() {
		return (self::isEnterpriseAppPlatformEnabled() or self::isChurchCentralPlatformEnabled()) and (!self::isPaymentsPlatformEnabled() and !self::isWebsitePlatformEnabled());
	}
	
	public static function isEnterpriseAppPlatformOnly() {
		return self::isEnterpriseAppPlatformEnabled() and (!self::isPaymentsPlatformEnabled() and !self::isWebsitePlatformEnabled() and !self::isChurchCentralPlatformEnabled());
	}
	
	public static function isChurchCentralPlatformOnly() {
		return self::isChurchCentralPlatformEnabled() and (!self::isPaymentsPlatformEnabled() and !self::isWebsitePlatformEnabled() and !self::isEnterpriseAppPlatformEnabled());
	}
	
	public static function isCmsEnabled() {
		return self::getData("cms_state") === "enabled";
	}
	
	public static function isWebsitePlatformEnabled() {
		return self::getData("website") == "1";
	}
	
	public static function isEnterpriseAppPlatformEnabled() {
		return self::getData("custom_app") == "1";
	}
	
	public static function isChurchCentralPlatformEnabled() {
		return self::getData("church_central") == "1";
	}
	
	public static function isPaymentsPlatformEnabled() {
		return self::getData("payments") == "1";
	}
	
	public static function isAppPlatformEnabled() {
		return self::isEnterpriseAppPlatformEnabled() or self::isChurchCentralPlatformEnabled();
	}
	
	public static function hasWebsite() {
		$domain = self::getData("website_domain");
		return isset($domain) and !empty($domain);
	}
	
	/*
		Getters
	*/
	
	public static function getEndUserAgreementTemplateText() {
		
		$template = [
			
			"<p>This End User License Agreement is between you (User) us {CLIENT_NAME} (Licensee) and Verto Group Pty Ltd (Licensor). If you do not agree with the terms of this Agreement, please do not proceed in creating an account. </p>",
			
			"<h3>Background</h3>",
			
			"<p>We {CLIENT_NAME} license the Software, being the V interact Platform and all of its features for our web and mobile applications. Verto Group (the Licensor) owns all rights within the Software, including all intellectual property rights. As a User of the Software, you grant certain rights to us and the Licensor under the terms of this Agreement, that govern your use of the Software. </p>",
			
			"<h3>Definitions</h3>",
			
			"<p>“Agreement” means this End User License Agreement and all documents incorporated therein; “Software” means the V interact Software Platform (including {PAYMENTS_PLATFORM_NAME}) and all associated rights therein being the subject of a license granted from the Licensor to the Licensee, which may include web and mobile applications, or {PAYMENTS_PLATFORM_NAME} as a standalone product (or a mixture of all of them); “User” means the user seeking access to use the Software in order to receive information, make payments or otherwise receive services from the Licensee.</p>",
			
			"<p>This Agreement is also subject to the following documents: <a href='{VERTO_PRIVACY_POLICY_URL}'>Verto Group Privacy Policy</a>, <a href='{CLIENT_PRIVACY_POLICY_URL}'>Licensee Privacy Policy</a>, Payment Terms and Conditions (if applicable).</p>",
			
			"<p>This User Agreement and the Privacy Policy may be updated from time to time. We will do our best to update you of these changes, however please check these documents regularly. If you do not agree to the terms set out in this EULA, please do not proceed in creating an account.</p>",
			
			"<h3>General</h3>",
			
			"<p>When you create an account or register with us as a user within this Software, you are providing us with personal details to assist with how we can communicate and distribute content and notifications to you within this Software.</p>",
			
			"<p>The Software we use is under a license agreement with our technology partner Verto Group Pty Ltd. By the term “Software’ we mean the platforms we license (such as V interact and {PAYMENTS_PLATFORM_NAME}) where you can access our content and by registering an account and logging in, this includes but is not limited to our website and mobile application.</p>",
			
			"<p>By creating an account you represent and agree that as a user:</p>",
			
			"<ul>",
			"<li>You are at least of minimum age to use this Software, that being 16 years of age;</li>",
			"<li>You will use your true legal name when creating an account;</li>",
			"<li>You will not create an account on behalf of another person or as a fake person;</li>",
			"<li>You will create and keep safe, your account password;</li>",
			"<li>You will comply with all applicable laws relating to the use of the Software;</li>",
			"</ul>",
			
			"<p>You consent to us and the Licensor communicating to you through the Software, including via push notification, SMS, email or other means through details provided by you;</p>",
			
			"<p>You consent to us and the Licensor sending you push notifications via the mobile application or web, if you are not, you can disable notifications within your device settings.</p>",
			
			"<h3>Ownership and access to End User Data</h3>",
			
			"<p>By registering as a user on the Software, any data and information that you provide us will be owned by us and is subject to our privacy policy. Under the terms of our Service Agreement with the Licensor, we give Verto Group the right to use your data to provide services to us, including support, integration and other services that we agree from time to time. The way that the Licensor uses your personal information is also subject to their privacy policy. You can delete your data at any time under the My Profile tab, and no copy of your data will be kept on the software after it has been deleted. The Software may provide the Licensor with information related to your use of the Software, information regarding your computer system, and information regarding your interaction with the Software, which Verto Group may use to provide and improve the Software and related products.</p>",
			
			"<p>Without limiting the generality of anything herein, you acknowledge and agree that the Software may collect user or device data for the purposes of providing services or functions that are relevant to use of the Software.</p>",
			
			"<h3>Grant of License to End User Data</h3>",
			
			"<p>As a User of the Software, you will submit information, content and data (referred to as End User Data) which will be collected, used and stored by both us {CLIENT_NAME} and Verto Group, in accordance with our respective privacy policies. By submitting this End User Data, you hereby grant the following licenses:</p>",
			
			"<p>1, To us {CLIENT_NAME}: a worldwide, non-exclusive, royalty-free, fee-free. perpetual, irrevocable, transferable and sublicensable right to use, copy, modify, distribute, publish, and process your End User Data for the purposes of providing our services to you; and </p>",
			
			"<p>2. To Verto Group and its related bodies corporate: a worldwide, non-exclusive, royalty-free, fee-free. perpetual, irrevocable, transferable and sublicensable right to use, copy, modify, distribute, publish, and process your End User Data for the purposes of providing our Software and other services.</p>",
			
			"<p>For the avoidance of doubt Verto Group will not publish any content or information that has been supplied by an end user that is identified as being confidential or private.</p>",
			
			"<h3>Grant of License to Software</h3>",
			
			"<p>The Software, including software embedded in the Software, is licensed, not sold, to the Licensee by Verto Group only under the terms of a separate written agreement, and Verto Group reserves all rights not expressly granted to the Licensee. Verto Group retain ownership of the Software itself.</p>",
			
			"<p>In order for you to use the Software, the Licensor grants the User a non-exclusive, non-sublicensable, non-transferable, limited license to use the Software for the purposes of:</p>",
			
			"<ol>",
			"<li>Accessing our {CLIENT_NAME} content;</li>",
			"<li>Enabling us to provide you with our services;</li>",
			"<li>Helping us to communicate with you;</li>",
			"<li>Making a payment through the Software including making a donation, paying for content (e.g. subscriptions) or paying for any other services we offer now or in the future.</li>",
			"</ol>",
			
			"<p>You acknowledge that if you use the Software to send spam or upload inappropriate content (as detailed below) either us or Verto Group may disable your account with immediate effect and without notice to you.</p>",
			
			"<p>You may not distribute or make the Software available over a network where it could be used by multiple devices at the same time.</p>",
			
			"<p>With respect to updates to the Software that Verto Group may make available for download, this EULA allows you to download such Software updates to update or restore the Software on any supported device.</p>",
			
			"<p>Except as and only to the extent permitted by applicable law, or by licensing terms governing use of open-sourced components included with the Software, neither you nor any other Customer personnel may copy, decompile, reverse engineer, disassemble, attempt to derive the source code of, decrypt, modify, or create derivative works of the Software or Software updates, or any part thereof. Any attempt to do so is a violation of the rights of Verto Group. If you or any other Licensee personnel violate this restriction, you or they, and the Licensee, may be subject to prosecution and damages.</p>",
			
			"<p>Neither you nor the Licensee may rent, lease, lend, redistribute or sublicense the Software. The Licensee may, however, allow other authorized Users under the Service Agreement to use the Software.</p>",
			
			"<p>Without limiting the generality of anything herein, you acknowledge and agree that the Software may collect user or device data for the purposes of providing services or functions that are relevant to use of the Software.</p>",
			
			"<h3>User Conduct</h3>",
			
			"<p>You Agree:</p>",
			
			"<ul>",
			"<li>that any information you submit electronically within the Software is owned by the Licensee that all content may be moderated, edited or removed by us or Verto Group;</li>",
			"<li>that you will not infringes or violate (or cause any infringement or violation of) the intellectual property or other rights of any person or entity;</li>",
			"<li>not to intentionally interfere with the operation of the Software or other Verto Group products or services;</li>",
			"<li>that you will only provide information that you have the legal right to submit;</li>",
			"<li>that you will not act dishonestly or unprofessionally, nor will you post inappropriate, inaccurate, or objectionable content;</li>",
			"<li>you will not harass, abuse or harm another person;</li>",
			"<li>you will not send spam or other unwelcomed communications to others;</li>",
			"<li>you will not act in an unlawful, libelous, abusive, obscene, discriminatory or otherwise objectionable manner;</li>",
			"<li>you will not disclose information that you do not have the legal right to disclose;</li>",
			"<li>that the content or information you submit does not contain or install any viruses, worms, bugs, Trojan horses, malware or other code;</li>",
			"<li>you will not install any files or programs designed or having the capability to disrupt, damage or limit the functionality of any software or hardware; and that any content that you submit may be rejected or removed by us or Verto Group for any reason in its sole discretion;</li>",
			"<li>that we may access, store and use any information that you provide in accordance with the terms of the Privacy Policy;</li>",
			"<li>that by using the Software, you may encounter content or information that might be inaccurate, incomplete, delayed, misleading, illegal, offensive, sensitive or otherwise harmful;</li>",
			"<li>that we are not obligated to publish any information or content within the Software and can remove it in our sole discretion, with or without notice.</li>",
			"</ul>",
			
			"<h3>Service Availability</h3>",
			
			"<p>The Software is provided on an ‘as is’ and ‘as available’ basis, we do not guarantee there will be no disruptions to the Software.</p>",
			
			"<p>We cannot promise to store or keep showing any information and content you've posted. We may change, suspend or end any content, subscription, or change and modify prices prospectively in our discretion. To the extent allowed under law, these changes may be effective upon notice provided to you.</p>",
			
			"<h3>Managing Your Free User Account</h3>",
			
			"<p>You understand that you:</p>",
			
			"<ul>",
			"<li>can delete your free user account by selecting ‘delete’ within the My Profile section.</li>",
			"<li>can edit your personal content preferences (for free content) at any time within the My Profile section.</li>",
			"</ul>",
			
			"<h3>Managing Your Paid Subscriptions (if relevant)</h3>",
			
			"<p>You Agree</p>",
			
			"<ul>",
			"<li>and understand that you can cancel your paid subscription by selecting ‘delete subscription’ via Subscriptions within the My Profile section. Please refer to our Payment Terms and Conditions (if applicable) for more details.</li>",
			"</ul>",
			
			"<h3>Disclaimer and Limit of Liability (No Warranty)</h3>",
			
			"<p>This is our disclaimer of legal liability for the quality, safety, or reliability of our Services. Your use of the Software is entirely at your own risk.</p>",
			
			"<p>To the extent permitted by law, we {CLIENT_NAME} and Verto Group, including our respective agents, contractors and suppliers are not liable to you on account of your use or misuse of or reliance on the Software. We {CLIENT_NAME} and Verto Group, including our respective agents, contractors and suppliers (a) disclaim all implied warranties and representations (e.g. warranties of merchantability, fitness for a particular purpose, accuracy of data, and noninfringement); (b) do not guarantee that the services will function without interruption or errors, and (c) provide the Software (including content and information) on an “as is” and “as available” basis.</p>",
			
			"<h3>Exclusion of Liability</h3>",
			
			"<p>These are the limits of legal liability we may have to you the User. You agree that we and Verto Group are not responsible in any way for third parties' (including other Members') content or information or for any damages as result of the content being disclosed or of your use of or reliance on it.</p>",
			
			"<p>For any loss associated with payments, please refer to our Payment Terms and Conditions (if applicable) which also contains our refund policy and mechanisms for resolving disputes.</p>",
			
			"<p>To the extent permitted under law, we, {CLIENT_NAME} and Verto Group, including our respective agents, contractors and suppliers shall not be liable to you or others for any indirect, incidental, special, consequential or punitive damages (including but not limited to loss of profits, loss of savings) or other damages arising out of the use or inability to use the Software, or any loss of data, opportunities, reputation, or revenues, related to the Software (e.g. offensive, illegal or defamatory statements, down time or loss, use or changes to your information or content).</p>",
			
			"<h3>TERM AND TERMINATION</h3>",
			
			"<p>This EULA shall terminate immediately and automatically upon any termination or expiration of the Licensee’s license to the Software. Upon any such termination or expiration, the Licensee (including you) shall no longer be permitted to use the Software and shall delete or destroy all copies of the Software in its (including your) possession. Termination of this EULA shall not entitle the Licensee to any refund, credit, or other compensation from Verto Group under the Service Agreement or any other agreement or from any third party. </p>",
			
			"<p>Neither Verto Group nor its third-party providers warrant the Software will perform in accordance with any specifications, documentation, or other standards, perform in an uninterrupted capacity, be error-free or bug-free, provide complete or accurate data, nor do they make any warranties as to the results to be obtained from the use of the Software. Use of the Software and reliance thereon is at the User’s sole risk. Verto Group will not in any way be liable to the User or any other entity or person for their inability to use the Software, or for any inaccuracies, errors, omissions, delays, computer viruses or other infirmity or corruption, damages, claims, liabilities or losses, regardless of cause, in or arising from the use of the Software. The Software is provided on an “as is” basis and without warranty or any technical support of any kind. No warranties, either express or implied, including but not limited to any implied warranty of merchantability, fitness for a particular purpose, title, non-infringement, or of any other type is provided hereunder.</p>",
			
			"<p>Verto Group may terminate this End User License Agreement at any time without cause. Upon any such termination or expiration, you shall no longer be permitted to use the Software, and shall delete or destroy all copies of the Software in your possession. Termination of this End User License Agreement shall not entitle you to any refund, credit, or other compensation from Verto Group under this agreement or any other agreement or from any third party.</p>",
			
			"<p>You will defend and hold harmless Verto Group against any claim, demand, suit or proceeding made or brought against Verto Group by you or a third party alleging that any of your data that you upload into the Software, or your use of the Software in breach of this Agreement, infringes a third party’s intellectual property rights or violates applicable law.</p>",
			
			"<h3>Contact Us</h3>",
			
			"<p>Please refer to our Privacy Policy for more information on how we use personal information and for ways to get in touch with us.</p>",
			
			"<p>{CLIENT_NAME}</p>",
			
		];
		
		$variables = [
			"{CLIENT_NAME}" => self::getDisplayName(),
			"{CLIENT_PRIVACY_POLICY_URL}" => self::getWebsiteURL("privacy_policy"),
			"{PAYMENTS_PLATFORM_NAME}" => Payments::getName(),
			"{VERTO_PRIVACY_POLICY_URL}" => "https://www.vertogroup.com.au/files/Verto%20Privacy%20Policy%20and%20GDPR%20Statement%20(Aug%202019).pdf",
			"{VINTERACT_PRIVACY_POLICY_URL}" => "https://www.vinteract.net.au/privacy_policy",
		];
		
		return Utils::replaceVariablesInString(join("", $template), $variables);
		
	}
	
	public static function getPrivacyPolicyTemplateText() {
		
		$template = [
			
			"<p>We use Software under a license agreement with our technology partner Verto Group Pty Ltd, who are committed to protecting your personal information in accordance with the Privacy Act 1988 (Cth) and the Australian Privacy Principles. For more information on how Verto Group use personal information, please refer to the <a href='{VERTO_PRIVACY_POLICY_URL}'>Verto Group Privacy Policy</a>.</p>",
			
			"<p>However, it is our responsibility to collect and manage information that you as the user provide <strong>(“User Provided Information”)</strong> or information that is automatically collected through the use of the Software <strong>(“Automatically Collected Information”)</strong>. This Privacy Policy will outline how User Provided and Automatically Collected Information is collected, used and managed. </p>",
			
			"<h3>When is information collected?</h3>",
			
			"<p>User Provided Information – The Software obtains the information you provide when you download our Mobile Application and submit forms (enquiries/testimonials) and create an account within the Software (if relevant). Creating an account is optional; however, please keep in mind that you may not be able to use some of the features offered by the Software if you do not have an account.</p>",
			
			"<h3>What ‘User Provided’ information is collected?</h3>",
			
			"<p>(a) Your name, phone number and email address when you make an enquiry; and</p>",
			"<p>(b) Your name, email address and phone number information when you submit a prayer request; and</p>",
			"<p>(c) Your name, email address, date of birth, gender, state, country, password, content preferences and optional phone number and profile picture when you create an account.</p>",
			"<p>(d) (if relevant) your name, email address, cause and donation amount ($) when you submit a payment; or</p>",
			"<p>(e) (if relevant) your name, email address, address, state, cause and donation amount ($) when you submit a payment and request a receipt.</p>",
			"<p>Any financial information such as credit card or bank details are collected at the time of making a one-off or recurring payment, for the purposes of processing those payments. Please refer to our Payment Terms and Conditions for more details.</p>",
			
			"<h3>What ‘Automatically Collected’ information is collected?</h3>",
			
			"<p>Our Software may collect certain information automatically, such as your operating system (browser and platform), your IP address and information about the way you use the Software. (See: “Automatic Data Collection”). If you would like to disable ‘cookies’, you can do so within your browser settings.</p>",
			
			"<h3>Is location information collected?</h3>",
			
			"<p>(a) If there is only one location listed for us, then we do not collect precise information about your location.</p>",
			"<p>(b) If there are multiple locations listed for Us and you have enabled Location Services on your device or browser, our Software will only collect precise information about the location of your device in order to calculate distances from your current position to our nearest locations. You can disable Location Services in your browser and device settings.</p>",
			
			"<h3>Do third parties see and/or have access to information?</h3>",
			
			"<p>We may share your information with third parties only in the ways that are described in this privacy statement.</p>",
			
			"<p>We may disclose ‘User Provided’ and ‘Automatically Collected’ Information:</p>",
			
			"<ul>",
			"<li>to our employees, contractors, suppliers, agents or service providers in order to deliver our services to you;</li>",
			"<li>As required by law, such as to comply with a subpoena, or similar legal process;</li>",
			"<li>When we believe in good faith that disclosure is necessary to protect our rights, protect your safety or the safety of others, investigate fraud, or respond to a government request;</li>",
			"<li>With our trusted services providers who work on our behalf, and have agreed to adhere to the rules set forth in this privacy statement including but not limited to Verto Group, whom we license Software from, that manage all our web and mobile applications.</li>",
			"<li>To third party analytics companies as described below under the Section entitled ‘Automatic Data Collection.’</li>",
			"</ul>",
			
			"<p>We may need to disclose your personal information to a third party located overseas, for a purpose set out in this Privacy Policy, or where you have provided your consent for us to do so. In this case, we will only do so to the extent necessary and take reasonable steps where we can to ensure that the third party handles your personal information in accordance with Australian privacy laws.</p>",
			
			"<h3>Automatic Data Collection</h3>",
			
			"<p>We may work with analytics companies to help us understand how the Software is being used, such as the frequency and duration of usage and what content is accessed the most.</p>",
			
			"<h3>How can I update my details?</h3>",
			
			"<p>If you have an Account, you may update your Account including name, phone number, date of birth, gender, state, password, content preferences and profile picture under ‘My Profile’. If you are unsure how to do this, please contact us. However, if you do not have an account, you can contact us and we can update these for you.</p>",
			
			"<h3>How do I delete my account?</h3>",
			
			"<p>If you have an Account, you may delete your account by selecting ‘Delete Account’ under ‘My Profile’ to have all your details removed from our system. This will remove your account including all personal details and content preferences. If you are still unsure how to do this, or if you do not have an Account please contact us and request to be removed from the system.</p>",
			
			"<h3>Data Retention Policy, Managing Your Information</h3>",
			
			"<p>All information collected is stored on our secure servers located in Australia. We will retain User Provided data for as long as you use our Software and for a reasonable time thereafter. If you would like us to delete User Provided Data that you have provided, please contact us directly.</p>",
			
			"<p>Please note that some or all of the User Provided Data may be required in order for the Software to function properly, and we may be required to retain certain information by law.</p>",
			
			"<h3>Children</h3>",
			
			"<p>We do not use the Software to knowingly solicit data from, or market to, children under the age of 13. If a parent or guardian becomes aware that his or her child has provided us with information without their consent, he or she should contact us directly.</p>",
			
			"<h3>Security</h3>",
			
			"<p>Our technology partner is concerned about safeguarding the confidentiality of your information. They provide physical, electronic, and procedural safeguards within their Software to protect information that is processed and stored. For example, they limit access to this information to authorised employees and contractors who need to know that information in order to operate, develop or improve their Software. Please be aware that although they endeavour to provide reasonable security for information we process and maintain, no security system can prevent all potential security breaches.</p>",
			
			"<h3>Changes</h3>",
			
			"<p>This Privacy Policy may be updated from time to time for any reason. We will notify you of any changes to our Privacy Policy by posting the new Privacy Policy here. You are advised to consult this Privacy Policy regularly for any changes.</p>",
			
			"<h3>Your Consent</h3>",
			
			"<p>By using the Services, you are consenting to our processing of User Provided and Automatically Collected information as set forth in this Privacy Policy now and as amended by us. ”Processing,” means using cookies on a computer/hand held device or using or touching information in any way, including, but not limited to, collecting, storing, deleting, using, combining and disclosing information, all of which activities will take place in Australia. If you reside outside of Australia your information will be transferred to Australia, and processed and stored there under Australian privacy standards. By using the Software and providing information to us, you consent to such transfer to, and processing in, Australia.</p>",
			
			"<h3>Contacting us</h3>",
			
			"<p>If you have any questions regarding Privacy while using the Software, or have questions about these practices, please contact us directly at:</p>"
			
		];
		
		$variables = [
			"{CLIENT_NAME}" => self::getDisplayName(),
			"{CLIENT_PRIVACY_POLICY_URL}" => self::getWebsiteURL("privacy_policy"),
			"{VERTO_PRIVACY_POLICY_URL}" => "https://www.vertogroup.com.au/files/Verto%20Privacy%20Policy%20and%20GDPR%20Statement%20(Aug%202019).pdf",
		];
		
		return \Vinteract\Utils::replaceVariablesInString(join("", $template), $variables);
		
	}
	
	public static function getPlatforms() {
		return [
			"website" => self::isWebsitePlatformEnabled(),
			"enterprise_app" => self::isEnterpriseAppPlatformEnabled(),
			"church_central" => self::isChurchCentralPlatformEnabled(),
			"payments" => self::isPaymentsPlatformEnabled(),
			"payments_only" => self::isPaymentsPlatformOnly(),
		];
	}
	
	public static function getSetting($key) {
		return self::local("settings")->where("key", $key)->value("value");
	}
	
	public static function getAPIKey($key) {
		return self::local("settings_api_keys")->where("key", $key)->value("value");
	}
	
	public static function getChurchCentralPushAPIKey() {
		return "7To9oNlzZHKl09xkJpLMZF7vh3ogWVmV";
	}
	
	public static function getJWTSecretKey() {
		return "sec!" . "LlUSAkxcpxHkCXAnz3KAKDNixitda0jX";
	}
	
	public static function getTimezoneOffset() {
		$timezone = self::getTimezone();
		if (isset($timezone)) {
			$time = new \DateTime("now", new \DateTimeZone($timezone));
			return $time->format("P");
		}
		return "+00:00";
	}
	
	public static function getTimezone() {
		return self::getData("timezone");
	}
	
	public static function getAccountHolder() {
		return self::global("global_" . self::$type . "_users")
			->select(["id", "name", "email"])
			->where("org_id", self::$id)
			->where("global_" . self::$type . "_users_permissions.permission_id", 6)
			->join("global_" . self::$type . "_users_permissions", function($join) {
	            $join->on("global_" . self::$type . "_users.id", "=", "global_" . self::$type . "_users_permissions.user_id");
	        })
			->first();
	}
	
	public static function getAddress() {
		return self::global("global_" . self::$type . "_locations")->select(["street_1", "street_2", "city", "region AS state", "postcode", "country", "lat", "lng"])->where("org_id", self::$id)->first();
	}
	
	public static function getData($key) {
		if (property_exists(self::$data, $key)) {
			return self::$data->$key;
		}
		return null;
	}
	
	public static function getWebsiteURL($extra = "") {
		$domain = self::$data->website_domain;
		if (ENVIRONMENT === "development") {
			return "http://localhost/{$domain}/{$extra}";
		} else {
			return "https://www.{$domain}/{$extra}";
		}
	}
	
	public static function getDisplayName() {
		return self::$data->title_display;
	}
	
	public static function getPublicId() {
		return self::$public_id;
	}
	
	public static function getType() {
		return self::$type;
	}
	
	public static function getName() {
		return self::$name;
	}
	
	public static function getId() {
		return self::$id;
	}
	
	/*
		Setters
	*/
	
	protected static function __set_public_id($public_id) {
		if (!isset($public_id)) {
			throw new InvalidArgumentException("Public Id is not set");
		}
		self::$public_id = $public_id;
	}
	
	protected static function __set_type($type) {
		if (!isset($type)) {
			throw new InvalidArgumentException("Type is not set");
		}
		self::$type = $type;
	}
	
	protected static function __set_name($name) {
		if (!isset($name)) {
			throw new InvalidArgumentException("Name is not set");
		}
		self::$name = $name;
	}
	
	protected static function __set_id($id) {
		if (!isset($id)) {
			throw new InvalidArgumentException("Id is not set");
		}
		self::$id = $id;
	}
	
	protected static function __set_data($data) {
		if (!isset($data)) {
			throw new InvalidArgumentException("Data is not set");
		}
		self::$data = $data;
	}
	
}
