<?php
if (!defined('ABSPATH')) {
    exit;
}
/**
 * Getting started Page
 */

/**
 * Redirect to start page when Mharty is activated.
 */
function mh_start_redirect() {
    global $pagenow;

    // Verify that the theme was activated
    if (is_admin() && isset($_GET['activated']) && $pagenow == 'themes.php') {

        // Do not redirect if network site
        if (is_network_admin() || isset($_GET['activate-multi'])) {
            return;
        }
        // Redirect
        wp_safe_redirect(add_query_arg(['page' => 'mh_start'], admin_url('admin.php')));

    }

}
add_action('after_switch_theme', 'mh_start_redirect');

/**
 * Add page content.
 */
function mh_start_page() {
    $tasks = [];

    $tasks[] = [
        'title' => esc_html__('Activate your theme', 'mharty'),
        'desc' => ('valid' === get_option('mharty_activation_key_status')) ? esc_html__('Congratulations! Your Licence is active.', 'mharty') : sprintf(
            __('Go to %sMy websites%s to find your Licence Key. Activation gives you access to Mharty theme and all premium features, exclusive plugins, layouts, sections, and important updates.', 'mharty'),
            '<a href="https://mharty.com/vip/activate" target="_blank">',
            '</a>'
        ),
        'done_class' => '' !== get_option('mharty_activation_key', '') ? 'mh-start-todo-li-done' : '',
        'function' => 'mh_key_activation_form',
    ];
    $tasks[] = [
        'title' => esc_html__('Install required plugins', 'mharty'),
        'desc' => esc_html__('Before you can enjoy the theme and its funcionality, it is essential to install required plugins.', 'mharty'),
        'done_class' => (in_array('composer', mharty_active_plugins()) && in_array('classiceditor', mharty_active_plugins()) && in_array('classicwidgets', mharty_active_plugins())) ? 'mh-start-todo-li-done' : '',
    ];
    $tasks[] = [
        'title' => esc_html__('Upload your logo', 'mharty'),
        'desc' => mh_wp_kses(__('Go to Mharty > Theme Customiser > Site Identity (Logo Image).', 'mharty') . ' <a href="https://mharty.com/learn/theme/add-your-logo" target="_blank">' . __('Watch Video', 'mharty') . '</a>'),
        'done_class' => ('' !== get_theme_mod('mharty_logo', '') || true === get_theme_mod('use_logo_text', false)) ? 'mh-start-todo-li-done' : '',
    ];
    $tasks[] = [
        'title' => esc_html__('Choose your accent colour', 'mharty'),
        'desc' => esc_html__('Go to Mharty > Theme Customiser > Colours > Accent Colours.', 'mharty'),
        'done_class' => '#4FD4FF' !== get_theme_mod('accent_color', '#4FD4FF') ? 'mh-start-todo-li-done' : '',
    ];
    $tasks[] = [
        'title' => esc_html__('Create your homepage', 'mharty'),
        'desc' => esc_html__('Go to Settings > Reading (Your homepage displays), Select "A static page" and next to "Homepage" select your home page, and Save Changes. If you do not have a homepage Go to Pages and create a new page first.', 'mharty'),
        'done_class' => 'page' == get_option('show_on_front') ? 'mh-start-todo-li-done' : '',
    ];
    $tasks[] = [
        'title' => esc_html__('Create your menu', 'mharty'),
        'desc' => mh_wp_kses(__('Go to Appearnce > Menus.', 'mharty') . ' <a href="https://mharty.com/learn/theme/theme-menus" target="_blank">' . __('Watch Video', 'mharty') . '</a>'),
        'done_class' => has_nav_menu('primary-menu') ? 'mh-start-todo-li-done' : '',
    ];
    $tasks[] = [
        'title' => esc_html__('Allow search engines to index your site', 'mharty'),
        'desc' => esc_html__('Go to Settings > Reading (Search engine visibility ).', 'mharty'),
        'done_class' => '1' == get_option('blog_public') ? 'mh-start-todo-li-done' : '',
    ];

    //plugins array
    $plugins = [];
    $plugins[] = [
        'name' => esc_html__('Mharty Composer', 'mharty'),
        'desc' => esc_html__('Allows you to compose pages in a beautiful way.', 'mharty'),
        'slug' => 'composer',
        'required' => true,
    ];
    $plugins[] = [
        'name' => esc_html__('Classic Editor', 'mharty'),
        'desc' => esc_html__('An official WordPress plugin restores the previous classic editor.', 'mharty'),
        'slug' => 'classiceditor',
        'required' => true,
    ];
    $plugins[] = [
        'name' => esc_html__('Classic Widgets', 'mharty'),
        'desc' => esc_html__('An official WordPress plugin restores the previous classic widgets.', 'mharty'),
        'slug' => 'classicwidgets',
        'required' => true,
    ];
    $plugins[] = [
        'name' => esc_html__('Mharty Loveit', 'mharty'),
        'desc' => esc_html__('Add likes and sharing icons to your Pages.', 'mharty'),
        'slug' => 'loveit',
        'required' => false,
    ];
    $plugins[] = [
        'name' => esc_html__('Mharty Magazine', 'mharty'),
        'desc' => esc_html__('Adds magazine components to the Page Composer.', 'mharty'),
        'slug' => 'magazine',
        'required' => false,
    ];
    $plugins[] = [
        'name' => esc_html__('Mharty Shop', 'mharty'),
        'desc' => esc_html__('Adds support to WooCommerce via the Page Composer.', 'mharty'),
        'slug' => 'shop',
        'required' => false,
    ];
    $plugins[] = [
        'name' => esc_html__('Mharty Icons', 'mharty'),
        'desc' => esc_html__('Offers more than 1200 icons to use in MH Page Composer.', 'mharty'),
        'slug' => 'icons',
        'required' => false,
    ];
    $plugins[] = [
        'name' => esc_html__('Mharty Reviews', 'mharty'),
        'desc' => esc_html__('Easily add reviews and ratings and display stars, points or score.', 'mharty'),
        'slug' => 'reviews',
        'required' => false,
    ];
    $plugins[] = [
        'name' => esc_html__('Mharty Author Cover', 'mharty'),
        'desc' => esc_html__("Adds covers to author's page, also adds an author box after posts.", 'mharty'),
        'slug' => 'author',
        'required' => false,
    ];
    $plugins[] = [
        'name' => esc_html__('Mharty Shortcodes', 'mharty'),
        'desc' => esc_html__('Add buttons, dividers, marker, info boxes via easy to use shortcodes.', 'mharty'),
        'slug' => 'shortcodes',
        'required' => false,
    ];

    $plugins[] = [
        'name' => esc_html__('Mharty Social Proof', 'mharty'),
        'desc' => esc_html__('Show real-time customer activity notifications on your site.', 'mharty'),
        'slug' => 'socialproof',
        'required' => false,
    ];

    $mharty_url = 'https://mharty.com';
    ?>
<div class="mh-start-wrapper">
  <?php echo mh_welcome_panel();  ?>
  <div class ="mh-start-header">
    <h1 class="mh-start-title"><?php echo esc_html__('Start Here', 'mharty'); ?></h1>
  </div>
  <div class="mh-start-container">
    <div class="mh-start-container-inner">
      <div class="mh-start-blocks">
        <div class="mh-start-block mh-start-block-docs">
          <div class="mh-start-block-inner"> <a href="<?php echo esc_url($mharty_url . '/learn/theme'); ?>" target="_blank"><?php echo esc_html__('Documentation', 'mharty'); ?></a> </div>
        </div>
        <div class="mh-start-block mh-start-block-support">
          <div class="mh-start-block-inner"> <a href="<?php echo esc_url($mharty_url . '/help'); ?>" target="_blank"><?php echo esc_html__('Friendly Support', 'mharty'); ?></a> </div>
        </div>
        <div class="mh-start-block mh-start-block-blog">
          <div class="mh-start-block-inner"> <a href="<?php echo esc_url($mharty_url . '/blog'); ?>" target="_blank"><?php echo esc_html__("What's New?", 'mharty'); ?></a> </div>
        </div>
      </div>
      <!--mh-start-blocks-->
      <div class="mh-start-todo mh-start-column">
        <div class="mh-start-column-inner">
          <h3><?php echo esc_html__('Getting Started', 'mharty'); ?></h3>
          <p><?php echo esc_html__('Follow these interactive steps to get your website ready in no time. Have fun!', 'mharty'); ?></p>
          <ul class="mh-start-todo-ul">
            <?php foreach ($tasks as $task) : ?>
            <li class="mh-start-todo-li <?php echo esc_html($task['done_class']); ?>">
              <div class="mh-start-todo-li-check"></div>
              <div class="mh-start-todo-li-content">
                <h4><?php echo esc_html($task['title']); ?></h4>
                <?php
                  if (!empty($task['function'])) {
                      do_action($task['function'] . '_hook');
                  }
                ?>
                <p><?php echo wp_kses_post($task['desc']); ?></p>
              </div>
            </li>
            <?php endforeach; ?>
            <li class="mh-start-todo-li mh-start-todo-li-more">
              <div class="mh-start-todo-li-check"></div>
              <div class="mh-start-todo-li-content">
                <h3><?php echo esc_html__('Recommended', 'mharty'); ?></h3>
                <ul>
                  <li>
                    <h4><?php echo esc_html__('Apply your first layout', 'mharty'); ?></h4>
                    <p> <?php echo mh_wp_kses(__('While editing a page, activate the composer, click "Layouts, then apply the desired layout.', 'mharty') . ' <a href="https://mharty.com/learn/theme/apply-layout" target="_blank">' . __('Watch Video', 'mharty') . '</a>'); ?></p>
                  </li>
                  <li>
                    <h4><?php echo esc_html__('Choose fonts', 'mharty'); ?></h4>
                    <p><?php echo esc_html__('Go to Mharty > Theme Customiser > Fonts', 'mharty'); ?></p>
                  </li>
                  <li>
                    <h4><?php echo esc_html__('Edit copyrights in the footer', 'mharty'); ?></h4>
                    <p><?php echo esc_html__('Go to Mharty > Theme Customiser > Footer (Website Copyrights)', 'mharty'); ?></p>
                  </li>
                  <li>
                    <h4><?php echo esc_html__('Pick a colour pallete', 'mharty'); ?></h4>
                    <p><?php echo esc_html__('Go to Mharty > Theme Panel', 'mharty'); ?></p>
                  </li>
                  <li>
                    <h4><?php echo esc_html__('More ideas and steps', 'mharty'); ?></h4>
                    <p><?php echo mh_wp_kses('<a href="https://mharty.com/learn/theme" target="_blank">' . __('Vist Mharty Documentation Hub', 'mharty') . '</a>'); ?></p>
                  </li>
                </ul>
              </div>
            </li>
          </ul>
        </div>
      </div>
      <!--mh-start-todo-->
      <div class="mh-start-plugins mh-start-column">
        <div class="mh-start-column-inner">
          <h3><?php echo esc_html__('Install Plugins', 'mharty'); ?></h3>
          <p><?php echo esc_html__('Start Installing required plugins. For best experience choose and install only the plugins you need.', 'mharty'); ?></p>
          <ul class="mh-start-plugins-ul">
            <?php foreach ($plugins as $plugin) : ?>
            <li class="mh-start-plugins-li mh-start-plugin-<?php echo esc_html($plugin['slug']); ?>">
              <div class="mh-start-plugins-li-inner">
                <h4 class="mh-start-plugins-li-name"><?php echo esc_html($plugin['name']); ?> <?php echo mh_plugin_version(esc_html($plugin['slug'])); ?></h4>
                <p class="mh-start-plugins-li-desc"><?php echo esc_html($plugin['desc']); ?></p>
                <div class="mh-start-plugins-li-action"><?php echo mh_install_plugin(esc_html($plugin['slug'])); ?></div>
                <?php if ($plugin['required']) {
                    echo '<div class="mh-start-plugins-li-required">' . esc_html__('Required', 'mharty') . '</div>';
                } ?>
              </div>
            </li>
            <?php endforeach; ?>
          </ul>
        </div>
      </div>
      <!--mh-start-plugins--> 
    </div>
    <?php do_action('mh_after_start_page'); ?>
  </div>
  <!--mh-start-container--> 
  <p class="mh-start-data-notice"><?php echo __('To keep your licence and updates accurate, this theme contacts mharty.com. It only shares your site domain, licence key, and version details — never personal data.', 'mharty'); ?></p>
</div>
<?php
}

/**
 * classic_editor Activation hook
 */
function mh_classic_editor_activate() {

    update_option('mh_classic_editor_activated', true);

}
register_activation_hook('classic-editor/classic-editor.php', 'mh_classic_editor_activate');

function mh_classic_editor_load_plugin() {

    if (is_admin() && get_option('mh_classic_editor_activated')) {

        delete_option('mh_classic_editor_activated');
        wp_safe_redirect(add_query_arg(['page' => 'mh_start'], admin_url('admin.php')));
    }
}
add_action('admin_init', 'mh_classic_editor_load_plugin');

/**
 * classic_widgets Activation hook
 */

function mh_classic_widgets_activate() {

    update_option('mh_classic_widgets_activated', true);

}
register_activation_hook('classic-widgets/classic-widgets.php', 'mh_classic_widgets_activate');

function mh_classic_widgets_load_plugin() {

    if (is_admin() && get_option('mh_classic_widgets_activated')) {

        delete_option('mh_classic_widgets_activated');
        wp_safe_redirect(add_query_arg(['page' => 'mh_start'], admin_url('admin.php')));
    }
}
add_action('admin_init', 'mh_classic_widgets_load_plugin');

function mh_register_key_option() {
    // creates our settings in the options table
    register_setting('mharty_activation', 'mharty_activation_key', 'mh_sanitize_key_option');
}
add_action('admin_init', 'mh_register_key_option');

function mh_sanitize_key_option($new) {
    $old = get_option('mharty_activation_key');
    if ($old && $old != $new) {
        delete_option('mharty_activation_key_status'); // new license has been entered, so must reactivate
        delete_site_transient('mh_captured_updates_data'); //to avoid caching wrong data when a new license has been entered
    }
    return $new;
}

/**
 * Key Activation Form
 */
function mh_key_activation_form() {
    $license = get_option('mharty_activation_key');
    $status = get_option('mharty_activation_key_status');
    ?>
<form method="post" action="" class="mh_key_activate_form">
  <?php //settings_fields('mharty_activation');?>
  <input id="mharty_activation_key_saved" name="mharty_activation_key_saved" type="password" class="mharty_activation_key_saved" value="<?php echo $license; ?>" />
  <?php submit_button(_x('Submit', 'Start Here Button.', 'mharty'), 'mh_submit_key_button', 'mharty_activation_submit', false); ?>
  <?php
    if (false !== $license && !empty($license)) {

        $data = '';
        $login = 'https://mharty.com/vip';
        if ($status !== false) {
            switch ($status) {
                case 'valid':
                    // Our message is diaplayed in a popup.
                    break;

                case 'expired':
                    $data = '<div class="mh_key_activate_status mh_key_activate_status_expired">' . sprintf(
                        __('Your subscription has expired. Please %s and renew it today to access updates and all premium features.', 'mharty'),
                        '<a href="' . esc_url($login) . '" target="_blank">' . esc_html__('login', 'mharty') . '</a>'
                    ) . '</div>';
                    break;

                default:
                    $data = '<div class="mh_key_activate_status mh_key_activate_status_invalid">' . esc_html__('Your Licence Key could not be verified. Please input a valid Key then click Submit.', 'mharty') . '</div>';
                    break;
            }

            if ('expired' === $status) {
                ?>
  <?php
            }

        } else {
            ?>
  <div class="mh_key_activate_status mh_key_activate_status_reactivate"> <?php echo esc_html__('Please click Submit to activate your Licence Key.', 'mharty'); ?></div>
  <?php
        }

        echo $data;
    }
    ?>
</form>
<?php
}
add_action('mh_key_activation_form_hook', 'mh_key_activation_form');

function mh_validate_license_key_inline() {
    if (isset($_POST['mharty_activation_submit']) && isset($_POST['mharty_activation_key_saved'])) {
        $append_arg = ['page' => 'mh_start'];
        $status = get_option('mharty_activation_key_status');
        $old_key = trim(get_option('mharty_activation_key'));
        $new_key = trim($_POST['mharty_activation_key_saved']);
        //if ( !empty($new_key) ){
        if ($old_key === $new_key && ('valid' === $status || 'invalid' === $status)) {
            //do nothing if key is valid or invalid and has not changed.
        } elseif (empty($new_key)) {
            //do nothing if key is cleared.
            update_option('mharty_activation_key', $new_key);
        } else {
            $append_arg = ['page' => 'mh_start', 'mh_key_activate' => $new_key];
            update_option('mharty_activation_key', $new_key);
        }
        //}
        wp_safe_redirect(add_query_arg($append_arg, admin_url('admin.php')));
        exit();
    }
}
add_action('admin_init', 'mh_validate_license_key_inline');

function mh_validate_license_key() {

    if (isset($_POST['mh_activation_key_button'])) {
        $append_arg = ['page' => 'mh_start'];

        if (!check_admin_referer('key_activate_nonce', 'key_activate_nonce')) {
            return;
        } // get out if we didn't click the Activate button

        $key = trim(get_option('mharty_activation_key'));
        if (empty($key)) {
            return;
        }

        $remote_url = add_query_arg(['repositories' => 'all', 'check_key' => 'get'], 'https://mharty.com');

        $response = wp_remote_post($remote_url, ['timeout' => 15, 'sslverify' => false, 'body' => ['key' => $key], 'user-agent' => 'WordPress; ' . home_url()]);

        if (is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) {
            if (is_wp_error($response)) {
                $data = $response->get_error_message();
            } else {

                $data = esc_html__('An error occurred, please try again or contact support.', 'mharty');
            }
            //save latest error message with date and time for status report
            $data = $data . '—' . date('m-d-Y H:i');
            set_site_transient('mharty_activation_key_error', $data);

        } else {
            $data = json_decode(wp_remote_retrieve_body($response));

            update_option('mharty_activation_key_status', urlencode($data));

            if ('valid' === $data) {
                $append_arg = ['page' => 'mh_start', 'mh_key_activation' => 'true'];
            }
        }

        //send install data
        mh_send_install_data($key);

        //lets clear update data when activate button is clicked.
        delete_site_transient('mh_captured_updates_data'); //to avoid caching wrong data
        wp_safe_redirect(add_query_arg($append_arg, admin_url('admin.php')));
        exit();
    }
}
add_action('admin_init', 'mh_validate_license_key');

//get status from updates data and update status.
function mh_get_status_from_captured_data() {
    $cached = '';
    $cache = mh_request_updates_data();

    if (empty($cache)) {
        $cached = '';
    } elseif (is_array($cache)) {

        $cached = $cache['status'];

    }
    if ('expired' === $cached) {
        update_option('mharty_activation_key_status', 'expired');
    }
}

function mh_valid_license_key_message() {
    if (!isset($_GET['mh_key_activation'])) {
        return;
    } // get out if key is not valid

    echo '<div id="mh-popup-box" class="mh-keybox"><div class="box-desc"><div class="box-desc-top">Mharty Activation Key</div><div class="box-desc-content">' . esc_html__('Great! Your Licence Key is valid.', 'mharty') . '</div><div class="box-desc-bottom"><a class="mh-keybox-button" href="' . admin_url('admin.php?page=mh_start') . '">' . esc_html__('Thanks', 'mharty') . '</a></div></div></div>';
}
add_action('mh_after_start_page', 'mh_valid_license_key_message');

function mh_activate_license_key_message() {
    if (!isset($_GET['mh_key_activate'])) {
        return;
    } // get out if key is not valid

    echo '<div id="mh-popup-box" class="mh-keybox"><div class="box-desc"><form method="post" action="options.php" class="mh_key_activate_form"><div class="box-desc-top">Mharty Activation Key</div><div class="box-desc-content">' . settings_fields('mharty_activation') . '<input id="mharty_activation_key" name="mharty_activation_key" type="hidden" class="mharty_activation_key" value="' . $_GET['mh_key_activate'] . '" /></div><div class="box-desc-bottom"><input type="submit" class="mh_activation_key_button mh-keybox-button" name="mh_activation_key_button" value="' . esc_html__('Activate Licence', 'mharty') . '"/>' . wp_nonce_field('key_activate_nonce', 'key_activate_nonce') . '</div></form></div></div>';

}
add_action('mh_after_start_page', 'mh_activate_license_key_message');

function mh_updatetd_tag() {
    $updated = get_theme_mod('mh_updatetd_6_0', 'no');
    if ('yes' !== $updated) {
        set_theme_mod('mh_updatetd_6_0', 'yes');
    }

}
add_action('mh_after_start_page', 'mh_updatetd_tag');

/**
 * Dismiss update notice and redirect to start here
 */

function mharty_dismiss_update_notice() {
    delete_transient('mharty_updated_welcome');
}
add_action('wp_ajax_nopriv_mharty_dismiss_update_notice', 'mharty_dismiss_update_notice');
add_action('wp_ajax_mharty_dismiss_update_notice', 'mharty_dismiss_update_notice');

function mh_plugin_version($plugin) {
    $output = '';
    //get the slug
    switch ($plugin) {
        case 'composer':
            $plugin_slug = 'mh-composer';
            break;
        case 'classiceditor':
            $plugin_slug = 'classic-editor';
            break;
        case 'classicwidgets':
            $plugin_slug = 'classic-widgets';
            break;
        case 'magazine':
            $plugin_slug = 'mh-magazine';
            break;
        case 'shop':
            $plugin_slug = 'mh-shop';
            break;
        case 'loveit':
            $plugin_slug = 'mh-loveit';
            break;
        case 'icons':
            $plugin_slug = 'mh-more-icons';
            break;
        case 'reviews':
            $plugin_slug = 'mh-reviews';
            break;
        case 'author':
            $plugin_slug = 'mh-author-page-cover';
            break;
        case 'shortcodes':
            $plugin_slug = 'mh-shortcodes';
            break;
        case 'socialproof':
            $plugin_slug = 'mh-social-proof';
            break;

    }
    if (file_exists(WP_PLUGIN_DIR . '/' . $plugin_slug)) {
        $file_path = trailingslashit(WP_PLUGIN_DIR) . $plugin_slug . '/' . $plugin_slug . '.php';

        $get_plugin_data = get_plugin_data($file_path);

        $output = '<span class="mh-start-plugins-li-ver">' . strip_tags($get_plugin_data['Version']) . '</span>';
    }
    return $output;

}
