<?php
// Custom htaccess class for Divi Switch

class DiviSwitchHtaccess {
	private static $htaccess, $switchRulesStart, $switchRulesEnd;
	const RULES_START = '# Start Divi Switch - do not modify!';
	const RULES_END = '# End Divi Switch';
	
	private static function read() {
		if (file_exists(ABSPATH.'.htaccess')) {
			$htaccess = file_get_contents(ABSPATH.'.htaccess');
			if ($htaccess === false) {
				return false;
			}
			self::$htaccess = explode("\n", $htaccess);
		} else {
			self::$htaccess = array();
		}
		
		self::$switchRulesStart = false;
		self::$switchRulesEnd = false;
		
		foreach (self::$htaccess as $index => $rule) {
			if (self::$switchRulesStart === false) {
				if (trim($rule) == self::RULES_START) {
					self::$switchRulesStart = $index;
				}
			} else if (trim($rule) == self::RULES_END) {
				self::$switchRulesEnd = $index;
				break;
			}
		}
		
		if (self::$switchRulesStart === false || self::$switchRulesEnd === false) {
			self::$switchRulesStart = count(self::$htaccess);
			self::$switchRulesEnd = self::$switchRulesStart + 1;
			self::$htaccess[] = self::RULES_START;
			self::$htaccess[] = self::RULES_END;
		}
		
		return true;
	}
	
	private static function getSwitchRules() {
		$rules = array();
		if (isset(self::$htaccess) || self::read()) {
			for ($i = self::$switchRulesStart + 1; $i < self::$switchRulesEnd; ++$i) {
				$rules[] = trim(self::$htaccess[$i]);
			}
		}
		return $rules;
	}
	
	public static function addRule($rule) {
		$rule = trim($rule);
		if (!in_array($rule, self::getSwitchRules()) && isset(self::$htaccess)) {
			array_splice(self::$htaccess, self::$switchRulesEnd, 0, $rule);
			++self::$switchRulesEnd;
		}
	}
	
	public static function removeRule($rule) {
		$rule = trim($rule);
		$ruleIndex = array_search($rule, self::getSwitchRules());
		if ($ruleIndex !== false && isset(self::$htaccess)) {
			array_splice(self::$htaccess, self::$switchRulesStart + 1 + $ruleIndex, 1);
			--self::$switchRulesEnd;
		}
	}
	
	public static function toggleRule($rule, $isEnabled) {
		$isEnabled ? self::addRule($rule) : self::removeRule($rule);
	}
	
	public static function write() {
		if (isset(self::$htaccess)) {
			$htaccess = self::$htaccess;
			if (self::$switchRulesEnd - self::$switchRulesStart == 1) { // There are no Switch rules in effect
				array_splice($htaccess, self::$switchRulesStart, 2);
			}
			file_put_contents(ABSPATH.'.htaccess', implode("\n", $htaccess));
		}
	}
	
}