<?php
if (!defined('ABSPATH')) {exit;}

include_once('src/'.KRFSAPP_THEME.'/theme-hooks.php');

function krfsapp_footer_admin() {
    // echo 'Powered By: Keyideas Infotech Pvt. Ltd.';
    echo '';
}

function krfsapp_check_and_enqueue_styles() {
    global $post;
    if (isset($post->post_content) && (has_shortcode($post->post_content, 'KRFS-EngagementBuilder-Listing'))) {
        include_once('src/'.KRFSAPP_THEME.'/ui/krfs_styles_inc.php');
        include_once('src/'.KRFSAPP_THEME.'/ui/krfs_libs_inc.php');
    }
}
add_action('wp_enqueue_scripts', 'krfsapp_check_and_enqueue_styles');

function krfsapp_load() {
    if (!wp_style_is('krfs-base-style', 'registered') || !wp_style_is('krfs-base-style', 'enqueued')) {
        wp_enqueue_style('krfs-base-style', KRFSAPP_PLUGIN_DIR . '/assets/krfs-base.css');
    }

    $primary_color = sanitize_hex_color(krfsapp_getMeta('_setting_primary_color'));
    $accent_color = sanitize_hex_color(krfsapp_getMeta('_setting_accent_color'));
    $primary_color_filter = esc_html(krfsapp_getMeta('_setting_primary_color_filter'));

    // Prepare the dynamic CSS
    $dynamic_css = "
        :root {
            --krfs-primary-color: {$primary_color};
            --krfs-accent-color: {$accent_color};
            --krfs-primary-color-filter: {$primary_color_filter};
        }
        .krfs_highlight_img_btn, .krfs_highlight_svg {
            filter: var(--krfs-primary-color-filter) !important;
        }
    ";

    // Add the dynamic CSS
    wp_add_inline_style('krfs-base-style', $dynamic_css);
}


function krfsapp_listing_shortcode($props) {
    krfsapp_load();
    if (!isset($props['category'])) {
        return "Please provide category in shortcode. Example: [KRFS-EngagementBuilder-Listing category='engagement-rings']";
    } else if (!in_array($props['category'], array_values(KRFSAPP_ALL_CATEGORIES_MAP))) {
        var_dump($props['category']);
        return "Invalid category provided. Valid categories are: " . implode(', ', array_values(KRFSAPP_ALL_CATEGORIES_MAP));
    }

    // Numeral Languages
    wp_enqueue_script('numeral-lang', KRFSAPP_PLUGIN_DIR . '/assets/libs/numeral-languages.js', array(), '1.0.0');
            
    // Numeral JS
    wp_enqueue_script('numeral-js', KRFSAPP_PLUGIN_DIR . '/assets/libs/numeral.min.js', array(), '2.0.6');

    wp_localize_script('numeral-js','KRFS_GLOBALS',
        [
            'ajax_url' => admin_url('admin-ajax.php'),
            'krfs_nonce' => wp_create_nonce('krfs_nonce'),
        ]
    );

    ob_start();
    include_once('src/'.KRFSAPP_THEME.'/ui/ring-listing.php');
    $content = ob_get_clean();
    $content = "<section class=\"krfs_main_section\">" . $content . "</section>";
    return $content;
}

add_shortcode('KRFS-EngagementBuilder-Listing', 'krfsapp_listing_shortcode');

function krfsapp_custom_add_rewrite_rules() {
    // Add a new rewrite rule for specific ring detail pages
    add_rewrite_rule(
        '^product-category/(engagement-rings|wedding-men-rings|wedding-women-rings|wedding-rings)/?$',
        'index.php?pagename=$matches[1]&ring_param=$matches[1]', // Use the captured slug in the redirection
        'top' // Priority of the rule
    );
}
add_action('init', 'krfsapp_custom_add_rewrite_rules');


// Register lifecycle hooks using one handler
register_activation_hook(KRFSAPP_HOME_FILE, 'krfsapp_plugin_activate_handler');
register_deactivation_hook(KRFSAPP_HOME_FILE, 'krfsapp_plugin_deactivate_handler');
register_uninstall_hook(KRFSAPP_HOME_FILE, 'krfsapp_plugin_uninstall_handler');

function krfsapp_plugin_activate_handler() {
    krfsapp_plugin_lifecycle_handler('activate');
}

function krfsapp_plugin_deactivate_handler() {
    krfsapp_plugin_lifecycle_handler('deactivate');
}

function krfsapp_plugin_uninstall_handler() {
    krfsapp_plugin_lifecycle_handler('uninstall');
}

/**
 * Unified plugin lifecycle handler.
 *
 * @param string $mode 'activate' | 'deactivate' | 'uninstall'
 */
function krfsapp_plugin_lifecycle_handler($mode) {
    switch ($mode) {
        case 'activate':
                if (!is_plugin_active('woocommerce/woocommerce.php')) {
                    deactivate_plugins(plugin_basename(KRFSAPP_HOME_FILE));
                    wp_die('Sorry, but this plugin requires WooCommerce. Please install and activate WooCommerce to use this plugin.');
                } else {
                    include_once('admin/plugin_activation_hook.php');
                }
            break;

        case 'deactivate':
            break;

        case 'uninstall':
            krfsapp_plugin_uninstall_email();
            break;
    }
}

/**
 * Admin Review Notice: Show on plugin dashboard with 30-day snooze on dismiss
 */
function krfs_handle_review_notice_dismiss() {
    if(!is_admin() || !current_user_can('manage_options')) return;

    if(isset($_GET['krfs_dismiss_review']) && wp_unslash(esc_html($_GET['krfs_dismiss_review'])) === '1') {
        if(!isset($_GET['_wpnonce']) || !wp_verify_nonce($_GET['_wpnonce'], 'krfs_dismiss_review')) {
            return;
        }

        update_option('krfs_review_notice_dismissed_at', time());

        // Clean the URL and redirect to avoid repeated actions on refresh
        $redirect = remove_query_arg(array('krfs_dismiss_review','_wpnonce'));
        wp_safe_redirect($redirect);
        exit;
    }
}
add_action('admin_init', 'krfs_handle_review_notice_dismiss');

function krfs_should_show_review_notice() {
    $dismissed_at = intval(get_option('krfs_review_notice_dismissed_at', 0));

    if($dismissed_at > 0) {
        // Show again only after one month
        if((time() - $dismissed_at) < MONTH_IN_SECONDS) {
            return false;
        }
    }
    return true;
}

function krfs_render_review_notice() {
    if(!is_admin() || !current_user_can('manage_options') || !krfs_should_show_review_notice()) return;

    $dismiss_url = wp_nonce_url(add_query_arg('krfs_dismiss_review', '1'), 'krfs_dismiss_review');

    echo '<div class="notice notice-info is-dismissible" style="display:block;">'
        . '<p><strong>' . esc_html__( 'Enjoying Keyideas Ring Filter & Search?', 'diamond-ring-builder-jewelry' ) . '</strong></p>'
        . '<p>' . esc_html__( 'If our plugin helps your store, please consider leaving a 5-star review. Your feedback motivates us and helps others discover the plugin.', 'diamond-ring-builder-jewelry' ) . '</p>'
        . '<p>'
            . '<a class="button button-primary" target="_blank" rel="noopener" href="' . esc_url(KRFS_REVIEW_URL) . '">' . esc_html__('Leave a Review', 'diamond-ring-builder-jewelry' ) . '</a> '
            . '<a class="button" href="' . esc_url($dismiss_url) . '">' . esc_html__('Dismiss for 30 days', 'diamond-ring-builder-jewelry' ) . '</a>'
        . '</p>'
    . '</div>';
}
add_action('admin_notices', 'krfs_render_review_notice');