<?php

if (!defined('ABSPATH')) {
    exit;
}

class WPDD_Setup {
    
    public static function init() {
        add_action('admin_notices', array(__CLASS__, 'show_setup_notice'));
        add_action('wp_ajax_wpdd_dismiss_setup', array(__CLASS__, 'dismiss_setup_notice'));
        add_action('wp_ajax_wpdd_create_pages', array(__CLASS__, 'create_default_pages'));
    }
    
    public static function show_setup_notice() {
        if (!get_option('wpdd_show_setup_notice') || get_option('wpdd_setup_completed')) {
            return;
        }
        
        if (!current_user_can('manage_options')) {
            return;
        }
        
        $screen = get_current_screen();
        if ($screen && strpos($screen->id, 'wpdd_product') === false && $screen->id !== 'dashboard') {
            return;
        }
        
        ?>
        <div class="notice notice-info wpdd-setup-notice" style="position: relative;">
            <h3><?php _e('🎉 WP Digital Download Setup', 'wp-digital-download'); ?></h3>
            <p><?php _e('Thank you for installing WP Digital Download! To get started, you can create the default pages or set them up manually.', 'wp-digital-download'); ?></p>
            
            <div class="wpdd-setup-actions" style="margin-bottom: 10px;">
                <button type="button" class="button button-primary" id="wpdd-create-pages">
                    <?php _e('Create Default Pages', 'wp-digital-download'); ?>
                </button>
                
                <button type="button" class="button button-secondary" id="wpdd-skip-setup">
                    <?php _e('Skip - I\'ll Set Up Manually', 'wp-digital-download'); ?>
                </button>
                
                <a href="<?php echo admin_url('edit.php?post_type=wpdd_product&page=wpdd-settings'); ?>" class="button">
                    <?php _e('Go to Settings', 'wp-digital-download'); ?>
                </a>
            </div>
            
            <div class="wpdd-pages-preview" style="background: #f9f9f9; padding: 15px; margin: 10px 0; border-radius: 4px;">
                <h4><?php _e('Default Pages to be Created:', 'wp-digital-download'); ?></h4>
                <ul style="columns: 2; margin: 0;">
                    <li><strong><?php _e('Shop', 'wp-digital-download'); ?></strong> - <?php _e('Product catalog with filtering', 'wp-digital-download'); ?></li>
                    <li><strong><?php _e('My Purchases', 'wp-digital-download'); ?></strong> - <?php _e('Customer purchase history', 'wp-digital-download'); ?></li>
                    <li><strong><?php _e('Checkout', 'wp-digital-download'); ?></strong> - <?php _e('Payment and order form', 'wp-digital-download'); ?></li>
                    <li><strong><?php _e('Thank You', 'wp-digital-download'); ?></strong> - <?php _e('Order confirmation page', 'wp-digital-download'); ?></li>
                </ul>
            </div>
            
            <div class="wpdd-setup-status" id="wpdd-setup-status" style="display: none; padding: 10px; margin: 10px 0; border-radius: 4px;">
            </div>
        </div>
        
        <script type="text/javascript">
        jQuery(document).ready(function($) {
            $('#wpdd-create-pages').on('click', function() {
                var $button = $(this);
                var $status = $('#wpdd-setup-status');
                
                $button.prop('disabled', true).text('<?php _e('Creating Pages...', 'wp-digital-download'); ?>');
                $status.show().removeClass().addClass('notice notice-info').html('<p><?php _e('Creating default pages...', 'wp-digital-download'); ?></p>');
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'wpdd_create_pages',
                        nonce: '<?php echo wp_create_nonce('wpdd_setup_nonce'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            $status.removeClass().addClass('notice notice-success').html(
                                '<p><strong><?php _e('Success!', 'wp-digital-download'); ?></strong> ' + response.data.message + '</p>' +
                                '<ul>' + response.data.pages.map(function(page) {
                                    return '<li><a href="' + page.edit_url + '">' + page.title + '</a> - <a href="' + page.view_url + '" target="_blank"><?php _e('View', 'wp-digital-download'); ?></a></li>';
                                }).join('') + '</ul>'
                            );
                            $('.wpdd-setup-actions').hide();
                            setTimeout(function() {
                                $('.wpdd-setup-notice').fadeOut();
                            }, 5000);
                        } else {
                            $status.removeClass().addClass('notice notice-error').html('<p><strong><?php _e('Error:', 'wp-digital-download'); ?></strong> ' + (response.data || '<?php _e('Unknown error occurred', 'wp-digital-download'); ?>') + '</p>');
                            $button.prop('disabled', false).text('<?php _e('Create Default Pages', 'wp-digital-download'); ?>');
                        }
                    },
                    error: function() {
                        $status.removeClass().addClass('notice notice-error').html('<p><strong><?php _e('Error:', 'wp-digital-download'); ?></strong> <?php _e('Failed to create pages. Please try again.', 'wp-digital-download'); ?></p>');
                        $button.prop('disabled', false).text('<?php _e('Create Default Pages', 'wp-digital-download'); ?>');
                    }
                });
            });
            
            $('#wpdd-skip-setup').on('click', function() {
                var $button = $(this);
                $button.prop('disabled', true).text('<?php _e('Dismissing...', 'wp-digital-download'); ?>');
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'wpdd_dismiss_setup',
                        nonce: '<?php echo wp_create_nonce('wpdd_setup_nonce'); ?>'
                    },
                    success: function(response) {
                        $('.wpdd-setup-notice').fadeOut();
                    }
                });
            });
        });
        </script>
        <?php
    }
    
    public static function create_default_pages() {
        check_ajax_referer('wpdd_setup_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Permission denied.', 'wp-digital-download'));
        }
        
        $created_pages = WPDD_Install::create_pages_optional();
        
        if (!empty($created_pages)) {
            $pages_info = array();
            foreach ($created_pages as $page_id) {
                $page = get_post($page_id);
                if ($page) {
                    $pages_info[] = array(
                        'title' => $page->post_title,
                        'edit_url' => admin_url('post.php?post=' . $page_id . '&action=edit'),
                        'view_url' => get_permalink($page_id)
                    );
                }
            }
            
            update_option('wpdd_setup_completed', true);
            delete_option('wpdd_show_setup_notice');
            
            wp_send_json_success(array(
                'message' => sprintf(__('%d pages created successfully!', 'wp-digital-download'), count($pages_info)),
                'pages' => $pages_info
            ));
        } else {
            wp_send_json_error(__('No pages were created. They may already exist.', 'wp-digital-download'));
        }
    }
    
    public static function dismiss_setup_notice() {
        check_ajax_referer('wpdd_setup_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Permission denied.', 'wp-digital-download'));
        }
        
        update_option('wpdd_setup_completed', true);
        delete_option('wpdd_show_setup_notice');
        
        wp_send_json_success();
    }
}