<?php

// TODO: force canDelete on entities
// TODO: clean cache also...?

namespace Modules\Utils\CleanDb;

class Model
{

	private $tablesFullList = [];

	private $tablesDropPatterns = [
		 // the important ones
		'bak_.*', 'report_content_.*', 'zz.*',
		 // plugins
		'plugins_agmReservations', 'plugins_aidaServicePaymentsStatus', 'plugins_BgFiscalPrinters_receipts', 'plugins_BrNotaFiscaleNdd_invoices',
		'plugins_ccReconciliation_files', 'plugins_ccReconciliation_posTerminals', 'plugins_ccReconciliation_transactions', 'plugins_AmexReport_exportedRows',
		'plugins_EgenciaReports_exportedRows', 'plugins_etos', 'plugins_etosComments', 'plugins_etosSecurityHashes', 'plugins_etosServices',
		'plugins_exportedCashingDocuments', 'plugins_Farelogix_parsedFiles', 'plugins_Farelogix_services', 'plugins_flightRefund_exportedFlights',
		'plugins_HuElectronicInvoiceCenter_queue', 'plugins_ilCreditGuard_transactions',
		'plugins_nsRail_parsedFiles', 'plugins_nsRail_services', 'plugins_orangeIntegration_confirmOrderFields', 'plugins_paymentsBorgun', 'plugins_RadiusReport_exportedRows',
		'plugins_saFaturahPayments_transactions', 'plugins_saHyperpay_transactions', 'plugins_saSadadPayments_transactions',
		'plugins_tamara_exportedRows', 'plugins_irixServicePaymentsStatus', 'plugins_tripReservations', 'plugins_tripReservationServices', 'plugins_TungstenReports_exportedRows',
		'plugins_QuickBooks_entities'
	];

	private $tablesTruncatePatterns = [
		'amadeus_(.*)', 'apollo_.*', 'autoProcess_logs', 'bsp.*', 'calendarEvents', 'cashBook_.*',
		'corporatesBalance', 'corporatesBalanceHistory', 'corporatesImpDocBalance', 'cronJobsLogs',
		'customersBalance', 'customersBalanceHistory', 'customersImpDocBalance', 'deduplicateCustomer_.*',
		'emailBookings', 'errorLogs', 'errorLogs_archive', 'exportData_logs', 'galileo_.*',
		'importedDocuments_documents', 'importedDocuments_documentsData', 'importedDocuments_documentsRemarks',
		'importedOrders_orders', 'importedOrders_ordersData', 'importedOrders_services', 'importedOrders_servicesRemarks', 'importedOrders_tickets',
		'invoiceBalanceNumber', 'kamSalesTargets', 'loginSessions', 'pivotTablesConfigs', 'pivotTablesData_.*', 'queryReturnDate',
		'rdParams', 'rdQueueFast', 'rdQueueMain', 'rd_.*',
		'reservationNumber', 'sabre_.*', 'serverStats', 'servicesBalancesSuggestions',
		'suppliersBalance', 'suppliersBalanceHistory', 'suppliersImpDocBalance', 'tasks',
		'updaterVars', 'worldspan_.*',
	];

	/**
	 * Other SQLs that need to be executed.
	 * @var array
	 */
	private $otherSqls = [
		'creditCardsClean' => "DELETE FROM `creditCards` WHERE entityType IN ('importedServiceId', 'importedServiceSystemId', 'offerFoc', 'offerFop')",
	];


	public function __construct()
	{
		$this->initFullListOfTables();
	}

	private function initFullListOfTables()
	{

		$db = \DB::getInstance();
		foreach($db->GetAll("SHOW TABLES") as $tbl) {
			$this->tablesFullList [reset($tbl)] = null;
		}

	}


	public function checkTablesCleaningStatus()
	{

		foreach($this->tablesFullList as $tableName=>$nada) {
			foreach($this->tablesDropPatterns as $dropTblPattern) {
				$matches = [];
				$regexp = '/^'.$dropTblPattern.'$/';
				if (preg_match($regexp, $tableName, $matches)) {
					$this->tablesFullList[$tableName] = 'DROP';
					break ; // stop current regexp is already matched
				}
			}

			foreach($this->tablesTruncatePatterns as $truncateTblPattern) {
				$matches = [];
				$regexp = '/^'.$truncateTblPattern.'$/';
				if (preg_match($regexp, $tableName, $matches)) {
					$this->tablesFullList[$tableName] = 'TRUNCATE';
					break ; // stop current regexp is already matched
				}
			}

		}

	}


	public function getTablesListFull()
	{
		return $this->tablesFullList;
	}

	public function returnSQLs()
	{

		$sqls = [];

		foreach ($this->tablesFullList as $tbl=>$status) {

			if ($status=='DROP') {
				$sqls[$tbl] = "DROP TABLE IF EXISTS `$tbl`";
			} elseif ($status=='TRUNCATE') {
				$sqls[$tbl] = "TRUNCATE TABLE `$tbl`";
			} else {
				$sqls[$tbl] = "-- DO NOT TOUCH `$tbl`";
			}

		}

		foreach($this->otherSqls as $idx=>$sql) {
			if (key_exists($idx, $sqls)) {
				throw new \Exception('Invalid other SQL index - check the code.');
			}
			$sqls[$idx] = $sql . ';';
		}

		return $sqls;

	}


}




/*
DO NOT TOUCH THESE:
autoProcess_cache
autoProcess_rules
bankAccounts
bankOffices
banks
calendarEvents
cashBook_documents
cashBook_totals
cities
contactPersons
contactPersonsRemarks
corporateGdsProfile
corporateGroups
corporates
corporatesCollections
corporatesContacts
corporatesContracts
corporatesCreditLimitsDetails
corporatesCreditLimitsEmailTemplates
corporatesDomains
corporatesDomainsCategories
corporatesOffices
corporatesOfficesBankAccounts
corporatesOfficesRemarks
corporatesPreferences
corporatesRemarks
corporatesSegments
countries
cronJobs
cronJobsConfig
currencyExchangeRates
currencyMarkets
currencyParities
customerGdsProfile
customers
customersPassports
customersPreferences
customersSegments
departments
documentsNumbers
documentsNumbersCurrencies
documentsNumbersDocumentTypes
documentsNumbersTemplates
documentsNumbersUsers
documentsTemplates
documentsTemplatesUsers
exportData_cashings
exportData_clientInvoices
exportData_payments
exportData_supplierInvoices
fluxInstances
frequentBuyerCards
frequentBuyerCardsSuppliers
gdsProfile_fields
gdsProfile_queue
gdsProfile_templates
gdsProfile_templatesFields
gds_agencyCreditCards
importedDocuments_matches
importedDocuments_systems
importedOrders_defaultServiceCalculations
importedOrders_matches
importedOrders_systems
mice_projects
mice_projectsPreferences
mice_projectsRemarks
mice_projectsTypes
offerProfileRules
offerProfileRulesCache
offerProfileRulesCorporates
offerProfileRulesRemarks
officeBankAccounts
offices
officesRemarks
pluginVars
qcRules
qcRulesCache
reports
reportsAccess
reportsCategories
reportsGenerating
reportsGenHistory
stations
supplierCodes
supplierGroups
suppliers
suppliersBankAccounts
suppliersContracts
suppliersPreferences
suppliersProducts
suppliersProductsAssoc
suppliersProductsPreferences
systemVars
tasks
tasksCategories
tasksOperationTypes
trusts
userProfiles
users
usersAccess
usersDashboard
usersPreferences
usersProfilesAccess
usersRemarks

plugins_chartisFiles
plugins_cityInsuranceFiles
plugins_clientSupplierVatAssoc
plugins_CorporatePortal_companies
plugins_CorporatePortal_companyGroups
plugins_CorporatePortal_users
plugins_crm_kamTargets
plugins_dcsAppSendOrdersRules
plugins_ergoFiles
plugins_gro_exportFields
plugins_invoiceMassGeneration
plugins_QuickBooks_entities
plugins_ru_commissionServiceFee_supplierRules
plugins_sendGdsFiles_definedQueues
plugins_servCalcsSuppInvRowsVats
plugins_servicesTypes
plugins_TCHFiles
plugins_travelAssistExport_customerCodes
plugins_travelGuardFiles
plugins_usersUnavailableStatus

*/