<?php
/**
 * This file contains the setting for exporting post data to other calendar
 * tools using an iCal feed.
 *
 * @package    Nelio_Content
 * @subpackage Nelio_Content/admin/settings
 * @author     Antonio Villegas <antonio.villegas@neliosoftware.com>
 * @since      1.4.2
 */

defined( 'ABSPATH' ) || exit;

/**
 * This class represents the setting for exporting post data to other calendar
 * tools using an iCal feed.
 *
 * @package    Nelio_Content
 * @subpackage Nelio_Content/admin/settings
 * @author     Antonio Villegas <antonio.villegas@neliosoftware.com>
 * @since      1.4.2
 */
class Nelio_Content_ICS_Calendar_Setting extends Nelio_Content_Abstract_Setting {

	/**
	 * Value.
	 *
	 * @var mixed
	 */
	protected $value;

	public function __construct() {
		parent::__construct( 'use_ics_subscription' );
	}

	/**
	 * Sets value.
	 *
	 * @param mixed $value Value.
	 *
	 * @return void
	 */
	public function set_value( $value ) {
		$this->value = $value;
	}

	// @Implements
	public function display() {
		// Preparing data for the partial.
		$id      = $this->option_name . '_' . str_replace( '_', '-', $this->name );
		$name    = $this->option_name . '[' . $this->name . ']';
		$desc    = _x( 'Export your calendar posts to Google Calendar or any other calendar tool', 'command', 'nelio-content' );
		$more    = '';
		$checked = checked( $this->value, true, false );
		include nelio_content()->plugin_path . '/includes/lib/settings/partials/nelio-content-checkbox-setting.php';
	}

	// @Implements
	public function sanitize( $input ) {

		$checked = false;

		if ( isset( $input[ $this->name ] ) ) {

			if ( 'on' === $input[ $this->name ] || '1' === $input[ $this->name ] || 'true' === $input[ $this->name ] ) {
				$checked = true;
			} elseif ( true === $input[ $this->name ] ) {
				$checked = true;
			}
		}

		// Manage key option when needed.
		$ics_secret_key = get_option( 'nc_ics_key', false );
		if ( $checked ) {

			if ( ! $ics_secret_key ) {
				update_option( 'nc_ics_key', wp_generate_password() );
			}
		} else {
			delete_option( 'nc_ics_key' );
		}

		$input[ $this->name ] = $checked;

		return $input;
	}
}
