<?php

/*
 * Copyright 2013-2015, Theia Sticky Sidebar, WeCodePixels, http://wecodepixels.com
 */

add_action( 'init', 'TssOptions::init' );

class TssOptions {
	public static function get( $optionId ) {
		$groups = array( 'tss_general' );
		foreach ( $groups as $groupId ) {
			$options = get_option( $groupId );
			if ( array_key_exists( $optionId, $options ) ) {
				return $options[ $optionId ];
			}
		}

		return null;
	}

	// Initialize options
	public static function init() {
		$defaults = array(
			'tss_dashboard' => array(),
			'tss_general'   => array(
				'currentTheme'           => '',
				'isTemplate'             => false,
				'sidebarSelector'        => '',
				'containerSelector'      => '',
				'additionalMarginTop'    => '',
				'additionalMarginBottom' => '',
				'minWidth'               => '0',
				'updateSidebarHeight'    => false,
				'disableOnHomePage'      => false,
				'disableOnCategoryPages' => false,
				'disableOnPages'         => false,
				'disableOnPosts'         => false,
				'customCss'              => ''
			)
		);

		// Reset to defaults.
		$reset_to_defaults = get_option( 'tss_dashboard' );
		$reset_to_defaults = is_array( $reset_to_defaults ) && array_key_exists( 'reset_to_defaults', $reset_to_defaults ) && $reset_to_defaults['reset_to_defaults'];
		if ( $reset_to_defaults ) {
			foreach ( $defaults as $groupId => $groupValues ) {
				delete_option( $groupId );
			}
		}

		foreach ( $defaults as $groupId => $groupValues ) {
			$options = get_option( $groupId );

			if ( ! is_array( $options ) ) {
				$options = array();
				$changed = true;
			} else {
				$changed = false;
			}

			// Add missing options.
			foreach ( $groupValues as $key => $value ) {
				if ( isset( $options[ $key ] ) == false ) {
					$changed         = true;
					$options[ $key ] = $value;
				}
			}

			// Sanitize options.
			foreach ( $options as $key => $value ) {
				if ( is_bool( $defaults[ $groupId ][ $key ] ) ) {
					$options[ $key ] = ( $options[ $key ] === true || $options[ $key ] === 'true' || $options[ $key ] === 'on' ) ? true : false;
					$changed         = true;
				}

				if ( is_array( $defaults[ $groupId ][ $key ] ) ) {
					$options[ $key ] = is_array( $options[ $key ] ) ? $options[ $key ] : $defaults[ $groupId ][ $key ];
					$changed         = true;
				}

				if ( $key == 'customCss' ) {
					$options[ $key ] = self::sanitizeCss( $options[ $key ] );
				}
			}

			// Save options.
			if ( $changed ) {
				update_option( $groupId, $options );
			}
		}

		// Are the current settings for a different theme? If there is a template available, then use it.
		if (
			self::get( 'currentTheme' ) != wp_get_theme()->Name &&
			TssTemplates::getTemplate() !== null
		) {
			TssTemplates::useTemplate();
		}
	}

	public static function sanitizeCss( $css ) {
		$css = trim( $css );
		$css = str_replace( "\r\n", "\n", $css );

		return $css;
	}
}