<?php
/**
 * Promotion Service
 *
 * @package EasyInvoice
 * @subpackage Services
 */

namespace EasyInvoice\Services;

/**
 * PromotionService Class
 *
 * Handles promotional banner display logic for Easy Invoice Pro upgrades
 */
class PromotionService {
    
    /**
     * Promotion banner dismissed option key
     */
    const DISMISSED_OPTION = 'easy_invoice_promotion_dismissed';
    
    /**
     * Promotion banner last shown timestamp option key
     */
    const LAST_SHOWN_OPTION = 'easy_invoice_promotion_last_shown';
    
    /**
     * Promotion banner permanently hidden option key
     */
    const PERMANENTLY_HIDDEN_OPTION = 'easy_invoice_promotion_permanently_hidden';
    
    /**
     * Minimum invoices required to show promotion
     */
    const MIN_INVOICES = 1;
    
    /**
     * Days to wait before showing again if dismissed once
     */
    const RESHOW_AFTER_DAYS = 15;
    
    /**
     * Easy Invoice Pro pricing URL
     */
    const PRO_PRICING_URL = 'https://matrixaddons.com/plugins/easy-invoice#pricing';
    
    /**
     * Initialize the promotion service
     */
    public static function init() {
        add_action('admin_notices', [__CLASS__, 'maybeShowPromotionBanner']);
        add_action('wp_ajax_easy_invoice_dismiss_promotion', [__CLASS__, 'handleDismissPromotion']);
        add_action('admin_enqueue_scripts', [__CLASS__, 'enqueueScripts']);
        add_action('admin_menu', [__CLASS__, 'addUpgradeToProMenu']);
        
        // Add plugin row action
        add_filter('plugin_action_links_' . plugin_basename(EASY_INVOICE_PLUGIN_FILE), [__CLASS__, 'addPluginRowAction']);
    }
    
    /**
     * Enqueue admin scripts for promotion functionality
     */
    public static function enqueueScripts() {
        wp_enqueue_script('easy-invoice-promotion', EASY_INVOICE_PLUGIN_URL . 'assets/js/promotion.js', ['jquery'], EASY_INVOICE_VERSION, true);
        wp_localize_script('easy-invoice-promotion', 'easyInvoicePromotion', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('easy_invoice_promotion_nonce')
        ]);
        
        // Add plain text CSS for plugin row action
        wp_add_inline_style('easy-invoice-promotion', '
            .plugin-action-links a[href*="easy-invoice#pricing"] {
                color: #ff9500 !important;
                font-weight: 600 !important;
                text-decoration: none !important;
                font-size: 12px !important;
                transition: all 0.3s ease !important;
            }
            
            .plugin-action-links a[href*="easy-invoice#pricing"]:hover {
                color: #e67e00 !important;
                text-decoration: underline !important;
            }
        ');
    }
    
    /**
     * Check if Easy Invoice Pro is active
     */
    public static function isProActive() {
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        return is_plugin_active('easy-invoice-pro/easy-invoice-pro.php');
    }
    
    /**
     * Get the count of invoices created by the user
     */
    public static function getInvoiceCount() {
        $args = [
            'post_type' => 'easy_invoice',
            'post_status' => ['publish', 'draft', 'pending'],
            'posts_per_page' => -1,
            'fields' => 'ids'
        ];
        
        $query = new \WP_Query($args);
        return $query->found_posts;
    }
    
    /**
     * Check if promotion should be shown
     */
    public static function shouldShowPromotion() {
        // Don't show if Pro is active
        if (self::isProActive()) {
            return false;
        }
        
        // Don't show if permanently hidden
        if (get_option(self::PERMANENTLY_HIDDEN_OPTION)) {
            return false;
        }
        
        // Check if user has created enough invoices
        $invoice_count = self::getInvoiceCount();
        if ($invoice_count < self::MIN_INVOICES) {
            return false;
        }
        
        // Check if banner was dismissed
        $dismissed = get_option(self::DISMISSED_OPTION);
        if ($dismissed) {
            // Check if enough time has passed to show again
            $last_shown = get_option(self::LAST_SHOWN_OPTION);
            if ($last_shown) {
                $days_since_shown = (current_time('timestamp') - strtotime($last_shown)) / DAY_IN_SECONDS;
                if ($days_since_shown < self::RESHOW_AFTER_DAYS) {
                    return false;
                }
            }
        }
        
        return true;
    }
    
    /**
     * Display the promotion banner if conditions are met
     */
    public static function maybeShowPromotionBanner() {
        if (!self::shouldShowPromotion()) {
            return;
        }
        
        // Update last shown timestamp
        update_option(self::LAST_SHOWN_OPTION, current_time('mysql'));
        
        $invoice_count = self::getInvoiceCount();
        ?>
        <div id="easy-invoice-promotion-notice" class="notice is-dismissible" style="background: linear-gradient(135deg, #fdf6f0 0%, #f8f9fa 50%, #fff5ee 100%); border: 1px solid #f0e6d8; border-left: 4px solid #ff9500; border-radius: 6px; margin: 15px 0; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08); position: relative;">
            <div style="position: absolute; top: 8px; right: 80px; background: #ff9500; color: white; padding: 2px 8px; border-radius: 10px; font-size: 10px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.3px;">
                ⚡ Limited Time
            </div>
            <div class="easy-invoice-promotion-content" style="padding: 18px;">
                <div style="display: flex; align-items: flex-start; gap: 15px;">
                    <div style="flex: 1;">
                        <h3 style="margin: 0 0 10px 0; color: #2c3e50; font-size: 17px; font-weight: 600;">
                            🚀 Upgrade to Easy Invoice Pro - Save 20%!
                        </h3>
                        <p style="margin: 0 0 12px 0; font-size: 14px; line-height: 1.5; color: #495057;">
                            You've created <strong style="color: #ff9500;"><?php echo esc_html($invoice_count); ?></strong> invoice(s)! 
                            Get <strong style="color: #ff9500;">20% OFF</strong> on Easy Invoice Pro. Unlock recurring invoices, advanced reporting, multiple payment gateways, and priority support.
                        </p>
                        <div style="background: rgba(255, 149, 0, 0.08); padding: 10px; border-radius: 4px; margin-bottom: 15px; border-left: 3px solid #ff9500;">
                            <p style="margin: 0; font-size: 13px; color: #495057; font-weight: 600;">
                                🎉 <strong>Special Offer:</strong> Save 20% on your Pro upgrade with advanced features and priority support!
                            </p>
                        </div>
                        <div style="display: flex; align-items: center; gap: 12px;">
                            <a href="<?php echo esc_url(self::PRO_PRICING_URL); ?>" 
                               target="_blank" 
                               class="button button-primary" 
                               style="background-color: #ff9500; border-color: #ff9500; color: white; padding: 8px 20px; font-weight: 600; font-size: 14px; border-radius: 4px; text-decoration: none; box-shadow: 0 2px 6px rgba(255, 149, 0, 0.3); transition: all 0.3s ease;">
                                ⚡ Save 20% - Upgrade to Pro
                            </a>
                            <a href="#" 
                               id="easy-invoice-promotion-dismiss" 
                               style="color: #6c757d; text-decoration: none; font-size: 13px; transition: color 0.3s ease;">
                                Maybe later
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <style>
        #easy-invoice-promotion-notice .button:hover {
            background-color: #e67e00 !important;
            border-color: #e67e00 !important;
            transform: translateY(-1px);
            box-shadow: 0 4px 10px rgba(255, 149, 0, 0.4) !important;
        }
        
        #easy-invoice-promotion-dismiss:hover {
            color: #495057 !important;
        }
        
        @media (max-width: 768px) {
            #easy-invoice-promotion-notice .easy-invoice-promotion-content {
                padding: 15px !important;
            }
            #easy-invoice-promotion-notice .easy-invoice-promotion-content > div {
                flex-direction: column !important;
                align-items: flex-start !important;
            }
            #easy-invoice-promotion-notice .button {
                width: 100% !important;
                text-align: center !important;
            }
        }
        </style>
        <?php
    }
    
    /**
     * Handle AJAX request to dismiss promotion
     */
    public static function handleDismissPromotion() {
        check_ajax_referer('easy_invoice_promotion_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.', 'easy-invoice'));
        }
        
        $dismiss_count = get_option('easy_invoice_promotion_dismiss_count', 0);
        $dismiss_count++;
        
        update_option('easy_invoice_promotion_dismiss_count', $dismiss_count);
        update_option(self::DISMISSED_OPTION, true);
        
        // If dismissed more than once, hide permanently
        if ($dismiss_count >= 2) {
            update_option(self::PERMANENTLY_HIDDEN_OPTION, true);
        }
        
        wp_send_json_success();
    }
    
    /**
     * Add "Upgrade to Pro" action in plugin row
     */
    public static function addPluginRowAction($links) {
        // Don't show if Pro is active
        if (self::isProActive()) {
            return $links;
        }
        
        $upgrade_link = sprintf(
            '<a href="%s" target="_blank" style="color: #ff9500; font-weight: 600; text-decoration: none; font-size: 12px; transition: all 0.3s ease;">%s</a>',
            esc_url(self::PRO_PRICING_URL),
            __('Upgrade to Pro', 'easy-invoice')
        );
        
        // Add to the beginning of the links array
        array_unshift($links, $upgrade_link);
        
        return $links;
    }
    
    /**
     * Add "Upgrade to Pro" menu item to main admin menu
     */
    public static function addUpgradeToProMenu() {
        // Only show if Pro is not active
        if (self::isProActive()) {
            return;
        }
        
        global $submenu;
        
        // Add the submenu item directly to the submenu array
        $submenu['easy-invoice'][] = array(
            __('Upgrade to Pro', 'easy-invoice'),
            'manage_options',
            self::PRO_PRICING_URL,
            __('Upgrade to Pro', 'easy-invoice'),
            999
        );
        
        // Add inline style to the submenu
        add_action('admin_head', function() {
            ?>
            <style>
            .wp-submenu a[href*="matrixaddons.com"] {
                color: #fff !important;
                font-weight: 700 !important;
                background: linear-gradient(45deg, #ff6b35, #ff9500) !important;
                border-radius: 4px !important;
                margin: 2px 8px 2px 0 !important;
                transition: all 0.3s ease !important;
                text-shadow: 0 1px 2px rgba(0,0,0,0.2) !important;
                box-shadow: 0 2px 6px rgba(255, 107, 53, 0.3) !important;
                display: inline-block !important;
                padding: 6px 12px !important;
            }
            
            .wp-submenu a[href*="matrixaddons.com"]:hover {
                background: linear-gradient(45deg, #e55a2b, #e67e00) !important;
                transform: translateX(2px) !important;
                box-shadow: 0 4px 12px rgba(255, 107, 53, 0.5) !important;
            }
            </style>
            <?php
        });
    }
    
    /**
     * Display the Upgrade to Pro page
     */
    public static function displayUpgradeToProPage() {
        ?>
        <div class="wrap">
            <h1 style="color: #ff9500; margin-bottom: 20px;">
                🚀 Upgrade to Easy Invoice Pro
            </h1>
            
            <div style="background: linear-gradient(135deg, #fdf6f0 0%, #f8f9fa 50%, #fff5ee 100%); border: 1px solid #f0e6d8; border-left: 4px solid #ff9500; border-radius: 6px; padding: 25px; margin-bottom: 25px; box-shadow: 0 2px 8px rgba(255, 149, 0, 0.15);">
                <h2 style="color: #2c3e50; margin-bottom: 15px;">Get 20% OFF Your Pro Upgrade!</h2>
                <p style="font-size: 16px; line-height: 1.6; color: #495057; margin-bottom: 20px;">
                    Unlock powerful features including recurring invoices, advanced reporting, multiple payment gateways, and priority support.
                </p>
                
                <div style="background: rgba(255, 149, 0, 0.08); padding: 15px; border-radius: 4px; margin-bottom: 20px; border-left: 3px solid #ff9500;">
                    <p style="margin: 0; font-size: 14px; color: #495057; font-weight: 600;">
                        🎉 <strong>Special Offer:</strong> Save 20% on your Pro upgrade with advanced features and priority support!
                    </p>
                </div>
                
                <div style="text-align: center; margin: 30px 0;">
                    <a href="<?php echo esc_url(self::PRO_PRICING_URL); ?>" 
                       target="_blank" 
                       class="button button-primary" 
                       style="background: linear-gradient(45deg, #ff9500, #ffaa00); border: none; color: white; padding: 12px 30px; font-weight: 700; font-size: 16px; border-radius: 6px; text-decoration: none; box-shadow: 0 3px 10px rgba(255, 149, 0, 0.4); transition: all 0.3s ease;">
                        ⚡ Save 20% - Upgrade to Pro Now
                    </a>
                </div>
            </div>
            
            <div style="background: white; border: 1px solid #e1e5e9; border-radius: 6px; padding: 25px;">
                <h3 style="color: #2c3e50; margin-bottom: 15px;">Why Upgrade to Pro?</h3>
                <ul style="list-style: none; padding: 0;">
                    <li style="margin-bottom: 12px; padding-left: 25px; position: relative;">
                        <span style="position: absolute; left: 0; color: #28a745;">✓</span>
                        <strong>Recurring Invoices</strong> - Set up automatic recurring billing
                    </li>
                    <li style="margin-bottom: 12px; padding-left: 25px; position: relative;">
                        <span style="position: absolute; left: 0; color: #28a745;">✓</span>
                        <strong>Advanced Reporting</strong> - Detailed financial reports and analytics
                    </li>
                    <li style="margin-bottom: 12px; padding-left: 25px; position: relative;">
                        <span style="position: absolute; left: 0; color: #28a745;">✓</span>
                        <strong>Multiple Payment Gateways</strong> - Stripe, PayPal, and more
                    </li>
                    <li style="margin-bottom: 12px; padding-left: 25px; position: relative;">
                        <span style="position: absolute; left: 0; color: #28a745;">✓</span>
                        <strong>Invoice & Quote Builder</strong> - Advanced drag-and-drop builder
                    </li>
                    <li style="margin-bottom: 12px; padding-left: 25px; position: relative;">
                        <span style="position: absolute; left: 0; color: #28a745;">✓</span>
                        <strong>Priority Support</strong> - Faster response times for help
                    </li>
                </ul>
            </div>
        </div>
        <?php
    }
}
