<?php
defined('ABSPATH') || exit;
/**
 * Plugin Rating Notice
 */
class Termin_Kalender_Rating_Notice {

     private static $ter_kal_instance = null;

    public function __construct() {
        self::$ter_kal_instance = $this;
        add_action('admin_init', array($this, 'check_installation_date'));
        add_action('admin_notices', array($this, 'display_rating_notice'));
        add_action('wp_ajax_tk_dismiss_rating_notice', array($this, 'dismiss_notice'));
        add_action('wp_ajax_tk_rate_plugin', array($this, 'rate_plugin'));
    }


    /**
     * Static helper to render the rating notice manually (e.g. inside tabs)
     */
    public static function render_rating_notice() {
        if ( self::$ter_kal_instance instanceof self ) {
            self::$ter_kal_instance->display_rating_notice_tab();
        }
    }

    private function get_option($key, $default = false) {
        $options = get_option('termin_kalender_options', array());
        $keys = explode('.', $key);
        $value = $options;
        foreach ($keys as $k) {
            if (!isset($value[$k])) {
                return $default;
            }
            $value = $value[$k];
        }
        return $value;
    }

    private function update_option($key, $value) {
        $options = get_option('termin_kalender_options', array());
        $keys = explode('.', $key);
        $current = &$options;
        foreach ($keys as $i => $k) {
            if ($i === count($keys) - 1) {
                $current[$k] = $value;
            } else {
                if (!isset($current[$k]) || !is_array($current[$k])) {
                    $current[$k] = array();
                }
                $current = &$current[$k];
            }
        }
        update_option('termin_kalender_options', $options);
    }

    public function check_installation_date() {
        if (!$this->get_option('install_date')) {
            $this->update_option('install_date', time());
        }
    }

    public function display_rating_notice() {
        if ($this->get_option('rating_notice_dismissed') || !current_user_can('manage_options')) {
            return;
        }

        $install_date = $this->get_option('install_date');
        $days_installed = floor((time() - $install_date) / DAY_IN_SECONDS);

        if ($days_installed < 14) {
            return;
        }

        $rating_url = 'https://wordpress.org/support/plugin/termin-kalender/reviews/#new-post';
        $nonce = wp_create_nonce('tk_rating_nonce');
        ?>
        <div class="notice notice-info is-dismissible" id="tk-rating-notice">
            <div style="display: flex; align-items: center; padding: 10px 0;">
                <span style="font-size: 24px; margin-right: 15px;">🌟</span>
                <div>
                    <p style="margin: 0 0 8px 0; font-weight: 600;">
                        <?php echo esc_html__('Enjoying Termin-Kalender?', 'termin-kalender'); ?>
                    </p>
                    <p style="margin: 0 0 12px 0;">
                        <?php esc_html_e('Your 5-star review helps us improve and reach more users. It takes just 30 seconds!', 'termin-kalender'); ?>
                    </p>
                    <p style="margin: 0;">
                        <a href="<?php echo esc_url($rating_url); ?>" target="_blank" class="button button-primary" id="tk-rate-now">
                            <?php esc_html_e('Rate Now ★★★★★', 'termin-kalender'); ?>
                        </a>
                        <button type="button" class="button" id="tk-maybe-later">
                            <?php esc_html_e('Maybe Later', 'termin-kalender'); ?>
                        </button>
                        <button type="button" class="button" id="tk-already-rated">
                            <?php esc_html_e('Already Rated', 'termin-kalender'); ?>
                        </button>
                    </p>
                </div>
            </div>
        </div>
        <script>
        jQuery(document).ready(function($) {
            $('#tk-rate-now').on('click', function() {
                $.post(ajaxurl, {
                    action: 'tk_rate_plugin',
                    nonce: '<?php echo esc_js($nonce); ?>'
                });
            });

            $('#tk-maybe-later, #tk-already-rated').on('click', function() {
                $.post(ajaxurl, {
                    action: 'tk_dismiss_rating_notice',
                    nonce: '<?php echo esc_js($nonce); ?>'
                });
                $('#tk-rating-notice').fadeOut();
            });

            $('#tk-rating-notice .notice-dismiss').on('click', function() {
                $.post(ajaxurl, {
                    action: 'tk_dismiss_rating_notice',
                    nonce: '<?php echo esc_js($nonce); ?>'
                });
            });
        });
        </script>
        <?php
    }

    public function display_rating_notice_tab() {
        $rating_url = 'https://wordpress.org/support/plugin/termin-kalender/reviews/#new-post';
        
        $wp_version = get_bloginfo('version');
        $php_version = phpversion();
        $site_url = site_url();
        $active_theme = wp_get_theme()->get('Name');
        $active_plugins = count((array) get_option('active_plugins', []));

        $subject = "Support / Feedback: Termin Kalender";
        
        $body = "Hallo Support-Team,\r\n\r\n";
        $body .= "ich benötige Hilfe beim Termin-Kalender:\r\n\r\n";
        // User inserts their message here
        $body .= "--- SYSTEM DATEN ---\r\n";
        $body .= "Website URL: {$site_url}\r\n";
        $body .= "WordPress Version: {$wp_version}\r\n";
        $body .= "PHP Version: {$php_version}\r\n";
        $body .= "Aktives Theme: {$active_theme}\r\n";
        $body .= "Anzahl aktiver Plugins: {$active_plugins}\r\n";

        $support_mailto = "mailto:error-report@termin-kalender.pro?subject=" . rawurlencode($subject) . "&body=" . rawurlencode($body);
        $nonce = wp_create_nonce('tk_rating_nonce');
        ?>
        <style>
            .tk-rating-container { max-width: 600px; margin: 30px auto; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
            .tk-support-card { background: #fffcf5; border: 1px solid #f5c6cb; border-left: 5px solid #d63638; border-radius: 6px; padding: 25px; margin-bottom: 30px; box-shadow: 0 2px 10px rgba(0,0,0,0.03); }
            .tk-support-card h3 { margin: 0 0 10px 0; font-size: 1.25rem; color: #d63638; display: flex; align-items: center; gap: 8px; }
            .tk-support-card p { margin: 0 0 18px 0; font-size: 14px; color: #50575e; line-height: 1.5; }
            .tk-support-card .button { border-color: #d63638; color: #d63638; }
            .tk-support-card .button:hover { background: #d63638; color: #fff; border-color: #d63638; }
            
            .tk-rating-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 35px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.05); }
            .tk-rating-stars { font-size: 42px; line-height: 1; letter-spacing: 2px; margin-bottom: 15px; color: #F59E0B; }
            .tk-rating-card h2 { margin: 0 0 12px 0; font-size: 1.6rem; color: #1e293b; font-weight: 700; }
            .tk-rating-card p { margin: 0 0 25px 0; font-size: 15px; color: #475569; line-height: 1.6; max-width: 450px; margin-left: auto; margin-right: auto; }
            .tk-btn-gold { display: inline-flex; align-items: center; justify-content: center; gap: 8px; background: linear-gradient(135deg, #F59E0B 0%, #D97706 100%); color: #fff !important; border: none; padding: 12px 28px; font-size: 16px; font-weight: 600; border-radius: 30px; text-decoration: none; transition: transform 0.2s, box-shadow 0.2s; box-shadow: 0 4px 15px rgba(245, 158, 11, 0.3); cursor: pointer; }
            .tk-btn-gold:hover, .tk-btn-gold:focus { background: linear-gradient(135deg, #Fcd34d 0%, #F59E0B 100%); color: #fff !important; transform: translateY(-2px); box-shadow: 0 6px 20px rgba(245, 158, 11, 0.4); text-decoration: none; }
            .tk-btn-gold .dashicons { margin-top: -1px; }
        </style>

        <div class="tk-rating-container" id="tk-rating-notice_tab">
            
            <!-- Support Intercept Card -->
            <div class="tk-support-card">
                <h3><span class="dashicons dashicons-sos"></span> <?php esc_html_e('Experiencing an issue?', 'termin-kalender'); ?></h3>
                <p><?php esc_html_e('We want to make sure your experience is flawless. Before leaving a negative review, please reach out so our small team can fix any bugs or help you set things up correctly!', 'termin-kalender'); ?></p>
                <a href="<?php echo esc_attr($support_mailto); ?>" class="button">
                    <span class="dashicons dashicons-external"></span> <?php esc_html_e('Get Support', 'termin-kalender'); ?>
                </a>
            </div>

            <!-- Rating Hero Card -->
            <div class="tk-rating-card">
                <div class="tk-rating-stars">★★★★★</div>
                <h2><?php echo esc_html__('Enjoying Termin-Kalender?', 'termin-kalender'); ?></h2>
                <p><?php esc_html_e('As a small dedicated team, your 5-star review means the world to us. It helps us grow, improve the plugin, and keep supporting users like you for free. It takes just 30 seconds!', 'termin-kalender'); ?></p>
                
                <a href="<?php echo esc_url($rating_url); ?>" target="_blank" class="tk-btn-gold" id="tk-rate-now">
                    <?php esc_html_e('Leave a Review', 'termin-kalender'); ?> <span class="dashicons dashicons-heart"></span>
                </a>
            </div>
        </div>
        
        <script>
        jQuery(document).ready(function($) {
            $('#tk-rate-now').on('click', function() {
                $.post(ajaxurl, {
                    action: 'tk_rate_plugin',
                    nonce: '<?php echo esc_js($nonce); ?>'
                });
            });
        });
        </script>
        <?php
    }


    public function dismiss_notice() {
        check_ajax_referer('tk_rating_nonce', 'nonce');
        $this->update_option('rating_notice_dismissed', true);
        wp_send_json_success();
    }

    public function rate_plugin() {
        check_ajax_referer('tk_rating_nonce', 'nonce');
        $this->update_option('rating_notice_dismissed', true);
        wp_send_json_success();
    }







}

if (is_admin()) {
    new Termin_Kalender_Rating_Notice();
}
