<?php

// Exit if accessed directly
if (!defined('ABSPATH'))
    exit;

define('APPOINTEE_PARENT_TEMPLATE_DIR_URI', get_template_directory_uri());
define('APPOINTEE_TEMPLATE_DIR_URI', get_stylesheet_directory_uri());
define('APPOINTEE_TEMPLATE_DIR', trailingslashit(get_stylesheet_directory()));

function appointee_setup() {
    require( APPOINTEE_TEMPLATE_DIR . '/function/header-widget.php' );
    require( APPOINTEE_TEMPLATE_DIR . '/function/functions.php' );
    load_theme_textdomain('appointee', APPOINTEE_TEMPLATE_DIR . '/languages');

    //About Theme
    $theme = wp_get_theme(); // gets the current theme
    if ('Appointee' == $theme->name) {
        if (is_admin()) {
            require APPOINTEE_TEMPLATE_DIR . '/admin/admin-init.php';
        }
    }
    add_theme_support('title-tag');
    add_theme_support('automatic-feed-links');
}
add_action('after_setup_theme', 'appointee_setup');

if (!function_exists('appointee_parent_css')):

    function appointee_parent_css() {
        wp_enqueue_style('appointee_parent', trailingslashit(APPOINTEE_PARENT_TEMPLATE_DIR_URI) . 'style.css', array());
        wp_style_add_data('appointee_parent', 'rtl', 'replace');
    }

endif;
add_action('wp_enqueue_scripts', 'appointee_parent_css', 10);

if (!function_exists('appointee_default_css')):

    function appointee_default_css() {

        $appointee_options = theme_setup_data();
        $current_options = wp_parse_args(  get_option( 'appointment_options', array() ), $appointee_options );

        if($current_options['link_color_enable'] == true) {
            appointment_custom_light();
        }
        else {
            wp_enqueue_style('appointee_skin', trailingslashit(APPOINTEE_TEMPLATE_DIR_URI) . 'css/skin.css', array());
        }

        wp_enqueue_style('appointee_default', trailingslashit(APPOINTEE_TEMPLATE_DIR_URI) . 'css/default.css', array());
        wp_enqueue_script('appointee_custom', trailingslashit(APPOINTEE_TEMPLATE_DIR_URI) . 'js/customjs.js', array());
    }

endif;
add_action('wp_enqueue_scripts', 'appointee_default_css', 12);

if (!function_exists('wp_body_open')) {

    function wp_body_open() {
        /**
         * Triggered after the opening <body> tag.
         */
        do_action('wp_body_open');
    }
}
 function appointee_remove_slider(){
     $appointee_options = appointment_theme_setup_data();
         $slider_setting = wp_parse_args(get_option('appointment_options', array()), $appointee_options);
         if ($slider_setting['home_banner_enabled'] == 1) {?>
             <style>
                .header {
                   position: relative;
                    background: #242526;
                }
            </style>

    <?php }
 }
 add_action('wp_head','appointee_remove_slider');

 function appointee_default_data() {

    return $theme_data = array(
        // general settings
        'footer_copyright_text' => __('Proudly powered by <a href="https://wordpress.org">WordPress</a>', 'appointee'),
        'footer_menu_bar_enabled' => 0,
        'footer_social_media_enabled' => 0,
        'footer_social_media_facebook_link' => '',
        'footer_facebook_media_enabled' => 0,
        'footer_social_media_twitter_link' => '',
        'footer_twitter_media_enabled' => 0,
        'footer_social_media_linkedin_link' => '',
        'footer_linkedin_media_enabled' => 0,
        'footer_social_media_skype_link' => '',
        'footer_skype_media_enabled' => 0,
        'social_media_facebook_link' => '',
        'social_media_twitter_link' => '',
        'social_media_linkedin_link' => '',
        'header_social_media_enabled' => 0,
        'facebook_media_enabled' => 0,
        'twitter_media_enabled' => 0,
        'linkedin_media_enabled' => 0,

    );
}
$appointee_theme = wp_get_theme();
if( $appointee_theme->name == 'Appointee' || $appointee_theme->name == 'Appointee child' || $appointee_theme->name == 'Appointee Child' ) {
    // Notice to add required plugin
    function appointee_admin_plugin_notice_warn() {
        $screen = get_current_screen();
        if( $screen->id == 'themes'){
            $theme_name = wp_get_theme();
            if ( get_option( 'dismissed-appointee_comanion_plugin', false ) ) {
               return;
            }
            if ( function_exists('webriti_companion_activate')) {
                return;
            }?>

            <div class="updated notice is-dismissible appointee-theme-notice">

                <div class="owc-header">
                    <h2 class="theme-owc-title">               
                        <svg height="60" width="60" id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 70 70"><defs><style>.cls-1{font-size:33px;font-family:Verdana-Bold, Verdana;font-weight:700;}</style></defs><title>Artboard 1</title><text class="cls-1" transform="translate(-0.56 51.25)">WC</text></svg>
                        <?php echo esc_html('Webriti Companion','appointee');?>
                    </h2>
                </div>

                <div class="appointee-theme-content">
                    <h3><?php printf (esc_html__('Thank you for installing the %1$s theme.', 'appointee'), esc_html($theme_name)); ?></h3>

                    <p><?php esc_html_e( 'We highly recommend you to install and activate the', 'appointee' ); ?>
                        <b><?php esc_html_e( 'Webriti Companion', 'appointee' ); ?></b> plugin.
                        <br>
                        <?php esc_html_e( 'This plugin will unlock enhanced features to build a beautiful website.', 'appointee' ); ?>
                    </p>
                    <button class="install-plugin-button-welcome-page" data-plugin-url="<?php echo esc_url( 'https://webriti.com/extensions/webriti-companion.zip');?>" data-plugin-slug="<?php esc_attr_e( 'webriti-companion','appointee');?>"><?php echo esc_html__( 'Install', 'appointee' ); ?></button>
                </div>
            </div>
            
            <script type="text/javascript">
                jQuery(function($) {
                $( document ).on( 'click', '.appointee-theme-notice .notice-dismiss', function () {
                    var type = $( this ).closest( '.appointee-theme-notice' ).data( 'notice' );
                    $.ajax( ajaxurl,
                      {
                        type: 'POST',
                        data: {
                          action: 'dismissed_notice_handler',
                          type: type,
                        }
                      } );
                  } );
              });
            </script>
            <?php
        }
    }
    add_action( 'admin_notices', 'appointee_admin_plugin_notice_warn' );
    add_action( 'wp_ajax_dismissed_notice_handler', 'appointee_ajax_notice_handler');

    function appointee_ajax_notice_handler() {
        update_option( 'dismissed-appointee_comanion_plugin', TRUE );
    }

    function appointee_notice_style(){?>
        <style type="text/css">
            label.tg-label.breadcrumbs img {
                width: 6%;
                padding: 0;
            }
            .appointee-theme-notice .theme-owc-title{
                display: flex;
                align-items: center;
                height: 100%;
                margin: 0;
                font-size: 1.5em;
            }
            .appointee-theme-notice p{
                font-size: 14px;
            }
            .updated.notice.appointee-theme-notice h3{
                margin: 0;
            }
            div.appointee-theme-notice.updated {
                border-left-color: #ee591f;
            }
            .appointee-theme-content{
                padding: 0 0 1.2rem 3.57rem;
            }
        </style>
    <?php
    }
    add_action('admin_enqueue_scripts','appointee_notice_style');
}

// Hook the AJAX action for logged-in users
add_action('wp_ajax_appointee_check_plugin_status', 'appointee_check_plugin_status');

function appointee_check_plugin_status() {
    if (!current_user_can('install_plugins')) {
        wp_send_json_error('You do not have permission to manage plugins.');
        return;
    }

    if (!isset($_POST['plugin_slug'])) {
        wp_send_json_error('No plugin slug provided.');
        return;
    }

    $plugin_slug = sanitize_text_field($_POST['plugin_slug']);
    $plugin_main_file = $plugin_slug . '/' . $plugin_slug . '.php'; // Adjust this based on your plugin structure

    // Check if the plugin exists
    $plugins = get_plugins();
    if (isset($plugins[$plugin_main_file])) {
        if (is_plugin_active($plugin_main_file)) {
            wp_send_json_success(array('status' => 'activated'));
        } else {
            wp_send_json_success(array('status' => 'installed'));
        }
    } else {
        wp_send_json_success(array('status' => 'not_installed'));
    }
}

// Existing AJAX installation function for installing and activating
add_action('wp_ajax_appointee_install_activate_plugin', 'appointee_install_and_activate_plugin');

function appointee_install_and_activate_plugin() {
    if (!current_user_can('install_plugins')) {
        wp_send_json_error('You do not have permission to install plugins.');
        return;
    }

    if (!isset($_POST['plugin_url'])) {
        wp_send_json_error('No plugin URL provided.');
        return;
    }

    // Include necessary WordPress files for plugin installation
    include_once(ABSPATH . 'wp-admin/includes/file.php');
    include_once(ABSPATH . 'wp-admin/includes/misc.php');
    include_once(ABSPATH . 'wp-admin/includes/class-wp-upgrader.php');
    include_once(ABSPATH . 'wp-admin/includes/plugin.php');

    $plugin_url = esc_url($_POST['plugin_url']);
    $plugin_slug = sanitize_text_field($_POST['plugin_slug']);
    $plugin_main_file = $plugin_slug . '/' . $plugin_slug . '.php'; // Ensure this matches your plugin structure

    // Download the plugin file
    WP_Filesystem();
    $temp_file = download_url($plugin_url);

    if (is_wp_error($temp_file)) {
        wp_send_json_error($temp_file->get_error_message());
        return;
    }

    // Unzip the plugin to the plugins folder
    $plugin_folder = WP_PLUGIN_DIR;
    $result = unzip_file($temp_file, $plugin_folder);
    
    // Clean up temporary file
    unlink($temp_file);

    if (is_wp_error($result)) {
        wp_send_json_error($result->get_error_message());
        return;
    }

    // Activate the plugin if it was installed
    $activate_result = activate_plugin($plugin_main_file);

    

    // Return success with redirect URL
    wp_send_json_success(array('redirect_url' => admin_url('admin.php?page=appointee-welcome')));
}

// Enqueue JavaScript for the button functionality
add_action('admin_enqueue_scripts', 'appointee_enqueue_plugin_installer_script',11);

function appointee_enqueue_plugin_installer_script(){
    global $hook_suffix;
    wp_dequeue_script('appointment-plugin-installer-js');
    wp_enqueue_script('appointee-plugin-installer-js',  APPOINTEE_TEMPLATE_DIR_URI . '/admin/assets/js/plugin-installer.js', array('jquery'), null, true);
    wp_localize_script('appointee-plugin-installer-js', 'pluginInstallerAjax', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'hook_suffix' => $hook_suffix,
        'nonce' => wp_create_nonce('plugin_installer_nonce'),

    ));
}