<?php
/**
 * Maintenance mode handler
 *
 * @package NotifierToSlack
 */

namespace WPNTS\Inc;

use WPNTS\Inc\SlackAttachment;

/**
 * Maintenance mode class
 */
class Maintenance {

	/**
	 * Constructor
	 */
	public function __construct() {
		add_action( 'init', [ $this, 'init' ] );
	}

	/**
	 * Initialize maintenance mode
	 */
	public function init() {
		// Get maintenance mode settings
		$schedules_int = get_option('wpnts_schedules_maintenannotice_settings');
		$schedules_interval = json_decode($schedules_int);
		$maintenance_mode = $schedules_interval->maintenance_mode ?? false;

		// Sales Notifications to Slack.
		if ( true === $maintenance_mode ) {
			// Add action hook.
			add_action('wp', [ $this, 'wpnts_enforce_maintenance_mode' ]);
		}
	}


	private function is_maintenance_mode_enabled() {
		$schedules_int = get_option('wpnts_schedules_maintenannotice_settings');
		$schedules_interval = json_decode($schedules_int);
		$maintenance_mode = $schedules_interval->maintenance_mode ?? 'false';

		return $maintenance_mode;
	}



	/**
	 * WordPress sales notification.
	 *
	 * @since 1.0.0
	 */
	public function wpnts_enforce_maintenance_mode() {

		if ( $this->is_maintenance_mode_enabled() && ! current_user_can('manage_options') ) {

			// Get the selected template
			$schedules_int = get_option('wpnts_schedules_maintenannotice_settings');
			$schedules_interval = json_decode($schedules_int);
			$selected_template = $schedules_interval->maintenance_template ?? 'default';

			// Determine template path based on selection
			switch ($selected_template) {
				case 'template1':
					$maintenance_template_path = WP_NOTIFIER_TO_SLACK_DIR_PATH . 'templates/template1.php';
					break;
				case 'template2':
					$maintenance_template_path = WP_NOTIFIER_TO_SLACK_DIR_PATH . 'templates/template2.php';
					break;
				default:
					$maintenance_template_path = WP_NOTIFIER_TO_SLACK_DIR_PATH . 'templates/maintenance-mode-template.php';
			}

			if ( file_exists($maintenance_template_path) ) {
				// Use the selected maintenance mode template from the plugin .
				include $maintenance_template_path;
				exit();
			} else {
				// If the template file is not found, show a default message.
				wp_die('Maintenance mode template not found. Please check your plugin setup.');
			}
		}
	}
}