<?php
/**
 * Super Agency functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package Super Agency
 * @since 1.0.0
 */

if ( ! defined( 'SUPER_AGENCY_VERSION' ) ) {
	// Defines the theme version.
	define( 'SUPER_AGENCY_VERSION', '1.0.7.2' );
}

/**
 * Enqueues the theme's frontend scripts and styles.
 *
 * @since 1.0.0
 */
function super_agency_scripts() {
	// Enqueue the theme's main stylesheet. In block themes, this is for block-specific styles and overrides.
	wp_enqueue_style( 'super-agency-style', get_template_directory_uri() . '/assets/css/style.css', array( 'wp-block-library', 'wp-block-library-theme' ), SUPER_AGENCY_VERSION );
	
	// Enqueue the theme's primary JavaScript file.
	wp_enqueue_script( 'super-agency-theme', trailingslashit( get_template_directory_uri() ) . 'assets/js/theme.js', array(), SUPER_AGENCY_VERSION, true );
}
add_action( 'wp_enqueue_scripts', 'super_agency_scripts' );

/**
 * Clears the global styles cache to ensure changes from theme.json and the Site Editor are applied.
 *
 * This is hooked into various actions to ensure the cache is cleared at the appropriate times,
 * preventing issues with stale CSS, especially after saving global styles.
 *
 * @since 1.0.6
 */
function super_agency_clear_global_styles_cache() {
    if (function_exists('wp_clean_theme_json_cache')) {
        wp_clean_theme_json_cache();
    }
    
    delete_transient('global_styles_' . get_stylesheet());
    delete_transient('global_styles_svg_filters_' . get_stylesheet());
}
// Clear cache on theme activation or update to apply default theme.json changes.
add_action('after_switch_theme', 'super_agency_clear_global_styles_cache');
add_action('wp_update_themes', 'super_agency_clear_global_styles_cache');
// Clear cache when global styles are updated in the Site Editor.
// Multiple hooks cover different WordPress versions and save paths.
add_action('wp_save_global_styles_post', 'super_agency_clear_global_styles_cache');    // WP 6.3+
add_action('save_post_wp_global_styles', 'super_agency_clear_global_styles_cache');    // All versions
add_action('rest_after_insert_wp_global_styles', 'super_agency_clear_global_styles_cache'); // REST API saves (Site Editor)


/**
 * Sets up theme defaults and registers support for various WordPress features.
 *
 * @since 1.0.0
 */
function super_agency_setup() {
	// Add support for block styles.
	add_theme_support( 'wp-block-styles' );
	
	// Add support for editor styles.
	add_theme_support( 'editor-styles' );
	
	// Add support for responsive embedded content.
	add_theme_support( 'responsive-embeds' );
	
	// Add support for custom line height controls.
	add_theme_support( 'custom-line-height' );
	
	// Add support for custom units.
	add_theme_support( 'custom-units' );
	
	// Add support for custom spacing.
	add_theme_support( 'custom-spacing' );
	
	// Add support for custom logo.
	add_theme_support( 'custom-logo', array(
		'height'      => 60,
		'width'       => 200,
		'flex-height' => true,
		'flex-width'  => true,
	) );
    
    // Disable Core Block Patterns.
	remove_theme_support( 'core-block-patterns' );

	// Enqueue editor styles.
	add_editor_style( 'assets/css/editor-style.css' );
}
add_action( 'after_setup_theme', 'super_agency_setup' );

/**
 * Registers custom block pattern categories.
 *
 * @since 1.0.0
 */
function super_agency_register_block_pattern_category() {
	$pattern_categories = array(
		'banner'       => __( 'Banner', 'super-agency' ),
		'featured'     => __( 'Featured', 'super-agency' ),
		'portfolio'    => __( 'Portfolio', 'super-agency' ),
		'services'     => __( 'Services', 'super-agency' ),
		'team'         => __( 'Team', 'super-agency' ),
		'testimonials' => __( 'Testimonials', 'super-agency' ),
	);

	foreach ( $pattern_categories as $slug => $label ) {
		register_block_pattern_category(
			$slug,
			array(
				'label' => $label,
			)
		);
	}
}
add_action( 'init', 'super_agency_register_block_pattern_category' );

/**
 * Registers custom block styles.
 *
 * @since 1.0.0
 */
if ( ! function_exists( 'super_agency_register_block_styles' ) ) :
	function super_agency_register_block_styles() {
		if ( function_exists( 'register_block_style' ) ) :
			// Outline Button Style
			register_block_style(
				'core/button',
				array(
					'name'         => 'super-agency-outline',
					'label'        => __( 'Outline', 'super-agency' ),
					'inline_style' => '
						.wp-block-button.is-style-super-agency-outline .wp-block-button__link {
							background-color: transparent;
							border: 2px solid var(--wp--preset--color--primary);
							color: var(--wp--preset--color--primary);
						}
						.wp-block-button.is-style-super-agency-outline .wp-block-button__link:hover {
							background-color: var(--wp--preset--color--primary);
							color: var(--wp--preset--color--background);
						}
					',
				)
			);
			
			// Card Group Style
			register_block_style(
				'core/group',
				array(
					'name'         => 'super-agency-card',
					'label'        => __( 'Card', 'super-agency' ),
					'inline_style' => '
						.wp-block-group.is-style-super-agency-card {
							background: var(--wp--preset--color--background);
							border-radius: 16px;
							padding: var(--wp--preset--spacing--large);
							box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
							transition: transform 0.3s ease;
						}
						.wp-block-group.is-style-super-agency-card:hover {
							transform: translateY(-4px);
						}
					',
				)
			);
		endif;
	}
endif;
add_action( 'init', 'super_agency_register_block_styles' );

/**
 * Adds body class for sticky header when the option is enabled (default: yes).
 *
 * @since 1.0.8
 */
function super_agency_body_classes( $classes ) {
    if ( get_option( 'super_agency_sticky_header', 'yes' ) === 'yes' ) {
        $classes[] = 'super-agency-sticky-header';
    }
    return $classes;
}
add_filter( 'body_class', 'super_agency_body_classes' );

/**
 * Include Theme Settings Page.
 */
require_once get_template_directory() . '/inc/admin/theme-settings.php';

/**
 * Creates the /inc/admin directory upon theme activation if it doesn't exist.
 *
 * @since 1.0.5
 */
function super_agency_create_admin_directory() {
    $admin_dir = get_template_directory() . '/inc/admin';
    if ( ! file_exists( $admin_dir ) ) {
        wp_mkdir_p( $admin_dir );
    }
}
add_action('after_switch_theme', 'super_agency_create_admin_directory');

/**
 * Adds a custom CSS class to the body tag on the theme settings page.
 *
 * @since 1.0.5
 * @param string $classes The existing body classes.
 * @return string The modified body classes.
 */
function super_agency_admin_body_class($classes) {
    $screen = get_current_screen();
    if ($screen && 'appearance_page_super-agency-settings' === $screen->id) {
        $classes .= ' super-agency-admin-page';
    }
    return $classes;
}
add_filter('admin_body_class', 'super_agency_admin_body_class');

/**
 * Adds a "Settings" link to the theme actions on the Appearance > Themes page.
 *
 * @since 1.0.5
 * @param array $links The existing theme action links.
 * @return array The modified theme action links.
 */
function super_agency_theme_action_links($links) {
    $settings_link = sprintf(
        '<a href="%s">%s</a>',
        esc_url(admin_url('themes.php?page=super-agency-settings')),
        esc_html__('Settings', 'super-agency')
    );
    array_unshift($links, $settings_link);
    return $links;
}
add_filter('theme_action_links_' . get_template(), 'super_agency_theme_action_links');

/**
 * Adds a custom dashboard widget for the theme.
 *
 * @since 1.0.5
 */
function super_agency_dashboard_widget() {
    wp_add_dashboard_widget(
        'super_agency_dashboard_widget',
        __('Super Agency Theme', 'super-agency'),
        'super_agency_dashboard_widget_content'
    );
}
add_action('wp_dashboard_setup', 'super_agency_dashboard_widget');

/**
 * Renders the content for the custom dashboard widget.
 *
 * @since 1.0.5
 */
function super_agency_dashboard_widget_content() {
    $theme = wp_get_theme();
    $settings_url = admin_url('themes.php?page=super-agency-settings');
    $customizer_url = admin_url('customize.php');
    $site_editor_url = admin_url('site-editor.php');
    ?>
    <div class="super-agency-dashboard-widget">
        <p style="margin-bottom: 15px;">
            <strong><?php esc_html_e('Welcome to Super Agency!', 'super-agency'); ?></strong><br>
            <?php printf(esc_html__('Version %s is active and ready to use.', 'super-agency'), esc_html($theme->get('Version'))); ?>
        </p>
        
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin: 15px 0;">
            <a href="<?php echo esc_url($settings_url); ?>" class="button button-primary" style="text-align: center;">
                <?php esc_html_e('Theme Settings', 'super-agency'); ?>
            </a>
            <a href="<?php echo esc_url($customizer_url); ?>" class="button" style="text-align: center;">
                <?php esc_html_e('Customize', 'super-agency'); ?>
            </a>
        </div>
        
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin: 15px 0;">
            <a href="<?php echo esc_url($site_editor_url); ?>" class="button" style="text-align: center;">
                <?php esc_html_e('Site Editor', 'super-agency'); ?>
            </a>
            <a href="https://wordpress.org/support/theme/super-agency/" class="button" style="text-align: center;" target="_blank">
                <?php esc_html_e('Get Help', 'super-agency'); ?>
            </a>
        </div>
        
        <hr style="margin: 15px 0;">
        <p style="margin: 0; font-size: 12px; color: #666;">
            <?php esc_html_e('Need help getting started? Check out the theme documentation and support forums.', 'super-agency'); ?>
        </p>
    </div>
    <?php
}

/**
 * Sets a transient flag on theme activation for the welcome notice.
 *
 * @since 1.0.5
 */
function super_agency_theme_activation() {
    super_agency_create_admin_directory();
    set_transient('super_agency_theme_activated', true, 60);
    super_agency_clear_global_styles_cache();
}
add_action('after_switch_theme', 'super_agency_theme_activation');

/**
 * Handles the dismissal of the welcome notice via AJAX.
 *
 * @since 1.0.5
 */
function super_agency_dismiss_welcome_notice() {
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'super_agency_dismiss_welcome')) {
        wp_send_json_error('Invalid nonce');
    }
    
    update_user_meta(get_current_user_id(), 'super_agency_welcome_dismissed', true);
    delete_transient('super_agency_theme_activated');
    
    wp_send_json_success('Notice dismissed successfully');
}
add_action('wp_ajax_super_agency_dismiss_welcome', 'super_agency_dismiss_welcome_notice');

/**
 * Customizes the admin footer text on the theme settings page.
 *
 * @since 1.0.5
 * @param string $text The existing footer text.
 * @return string The modified footer text.
 */
function super_agency_admin_footer_text($text) {
    $screen = get_current_screen();
    if ($screen && 'appearance_page_super-agency-settings' === $screen->id) {
        $text = sprintf(
            __('Super Agency Theme v%s by <a href="%s" target="_blank">Jose Varghese</a>', 'super-agency'),
            esc_html(wp_get_theme()->get('Version')),
            'https://profiles.wordpress.org/josevarghese/'
        );
    }
    return $text;
}
add_filter('admin_footer_text', 'super_agency_admin_footer_text');

/**
 * Enqueues inline styles for the dashboard widget.
 *
 * @since 1.0.5
 */
function super_agency_admin_styles() {
    $screen = get_current_screen();
    if ($screen && 'dashboard' === $screen->id) {
        $widget_styles = '
            .super-agency-dashboard-widget {
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            }
            .super-agency-dashboard-widget .button {
                text-decoration: none !important;
                display: inline-block;
                padding: 6px 12px;
                box-shadow: none;
                border-radius: 3px;
            }
            .super-agency-dashboard-widget .button-primary {
                background: #2271b1;
                border-color: #2271b1;
                color: #fff;
            }
        ';
        wp_add_inline_style('dashboard', $widget_styles);
    }
}
add_action('admin_enqueue_scripts', 'super_agency_admin_styles');

/**
 * Displays an admin notice on theme activation.
 *
 * @since 1.0.5
 */
function super_agency_welcome_notice() {
    if (!current_user_can('manage_options')) {
        return;
    }
    
    $is_activated = get_transient('super_agency_theme_activated');
    $is_dismissed = get_user_meta(get_current_user_id(), 'super_agency_welcome_dismissed', true);
    
    if (!$is_activated || $is_dismissed) {
        return;
    }
    
    $settings_url = admin_url('themes.php?page=super-agency-settings');
    $customizer_url = admin_url('customize.php');
    ?>
    <div class="notice notice-success super-agency-welcome-notice is-dismissible" style="border-left-color: #2563EB;">
        <div style="display: flex; align-items: center; padding: 10px 0;">
            <div style="margin-right: 15px;">
                <span style="font-size: 32px;">🚀</span>
            </div>
            <div style="flex: 1;">
                <h3 style="margin: 0 0 8px 0; font-size: 16px;">
                    <?php esc_html_e('Welcome to Super Agency!', 'super-agency'); ?>
                </h3>
                <p style="margin: 0; font-size: 14px;">
                    <?php esc_html_e('Thank you for choosing Super Agency theme! Get started by customizing your site or exploring the theme settings.', 'super-agency'); ?>
                </p>
                <div style="margin-top: 12px;">
                    <a href="<?php echo esc_url($settings_url); ?>" class="button button-primary" style="margin-right: 8px;">
                        <?php esc_html_e('Theme Settings', 'super-agency'); ?>
                    </a>
                    <a href="<?php echo esc_url($customizer_url); ?>" class="button">
                        <?php esc_html_e('Customize Site', 'super-agency'); ?>
                    </a>
                </div>
            </div>
        </div>
    </div>
    
    <script>
    jQuery(document).ready(function($) {
        $('.super-agency-welcome-notice .notice-dismiss').on('click', function() {
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'super_agency_dismiss_welcome',
                    nonce: '<?php echo wp_create_nonce('super_agency_dismiss_welcome'); ?>'
                }
            });
        });
    });
    </script>
    <?php
}
add_action('admin_notices', 'super_agency_welcome_notice');