<?php
/**
 * Plugin Name: Maintenance Mode
 * Plugin URI: https://www.connectamerica.com
 * Description: Place site in maintenance
 * Version: 1.0
 * Author: Anthony Volpe
 * Author URI: https://www.connectamerica.com
 */



add_action('admin_menu', 'plugin_admin_settings_tab');
function plugin_admin_settings_tab() {
    add_options_page('Maintenance Mode', 'Maintenance Mode', 'manage_options', 'maintenance_mode', 'plugin_maint_mode');
    add_action('admin_init', 'plugin_init');
}

function plugin_maint_mode() {
?>
<div>
    <form action="options.php" method="post">
        <?php settings_fields('plugin_options'); ?>
        <?php do_settings_sections('plugin'); ?>
        <?php submit_button(); ?>
    </form>
</div>
<?php
}

function plugin_init(){

register_setting( 'plugin_options', 'plugin_options' );
add_settings_section('plugin_main', 'Maintenance Mode', 'plugin_maint_section_text', 'plugin');
add_settings_field('Checkbox Element', 'Enable', 'checkbox_element_callback', 'plugin', 'plugin_main' );

}

function checkbox_element_callback() {

$options = get_option( 'plugin_options' );

$checked = ( isset($options['maint_checkbox']) && $options['maint_checkbox'] == 1) ? 1 : 0;

$html = '<input type="checkbox" id="maint_checkbox" name="plugin_options[maint_checkbox]" value="1"' . checked( 1, $checked, false ) . '/>';
$html .= '<label for="maint_checkbox"> Maintenance Active</label>';

echo $html;

}

function plugin_maint_section_text() {
    echo '<p>Set Maintenance Mode</p>';
}


function plugin_maint_options_validate($input) {
$options = get_option('plugin_options');
return $options;
}


add_action('wp_loaded', 'maintenance_mode');
function maintenance_mode(){
$options = get_option( 'plugin_options' );
$checked = ( isset($options['maint_checkbox']) && $options['maint_checkbox'] == 1) ? 1 : 0;
    global $pagenow;

        if( $checked == 1 ){
         define('IN_MAINTENANCE', true);
        } else {
        define('IN_MAINTENANCE', false);
    }

    if(
        defined( 'IN_MAINTENANCE' )
        && IN_MAINTENANCE
        && $pagenow !== 'wp-login.php'
        && ! is_user_logged_in()
    ) {
        if ( file_exists( plugin_dir_path( __FILE__ ) . '/maintenance.php' ) ) {
            require_once( plugin_dir_path( __FILE__ ) . '/maintenance.php' );
        }
        die();
    }
};

