<?php
/**
 * Plugin settings class
 *
 * @since      1.0.0
 * @package    Yoast_Bulk_Update
 */

if (!defined('WPINC')) {
    die;
}

/**
 * Plugin settings class
 */
class Yoast_Bulk_Update_Settings {

    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        // Check if Yoast SEO is active
        if (!defined('WPSEO_VERSION')) {
            add_options_page(
                __('Yoast Bulk Update', 'yoast-bulk-update'),
                __('Yoast Bulk Update', 'yoast-bulk-update'),
                'manage_options',
                YBU_PLUGIN_NAME,
                array($this, 'display_settings_page')
            );
        } else {
            // Add as submenu under Yoast SEO
            add_submenu_page(
                'wpseo_dashboard',
                __('Bulk Update', 'yoast-bulk-update'),
                __('Bulk Update', 'yoast-bulk-update'),
                'manage_options',
                YBU_PLUGIN_NAME,
                array($this, 'display_settings_page')
            );
        }
    }

    /**
     * Register settings
     */
    public function register_settings() {
        register_setting(YBU_PLUGIN_NAME, YBU_PLUGIN_NAME);

        // Add AJAX actions for export
        add_action('wp_ajax_ybu_export_csv', array($this, 'export_csv_ajax'));
    }

    /**
     * Export CSV via AJAX
     */
    public function export_csv_ajax() {
        // Check nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ybu_ajax_nonce')) {
            wp_send_json_error(array('message' => __('Security check failed.', 'yoast-bulk-update')));
        }
        
        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('You do not have permission to perform this action.', 'yoast-bulk-update')));
        }
        
        // Get post types to export
        $post_types = isset($_POST['post_types']) ? (array) $_POST['post_types'] : array('post', 'page');
        
        // Validate post types
        $available_post_types = $this->get_available_post_types();
        $post_types = array_intersect($post_types, array_keys($available_post_types));
        
        if (empty($post_types)) {
            wp_send_json_error(array('message' => __('No valid post types selected.', 'yoast-bulk-update')));
        }
        
        // Generate CSV data
        $csv_data = $this->generate_csv_data($post_types);
        
        if (empty($csv_data)) {
            wp_send_json_error(array('message' => __('No data to export.', 'yoast-bulk-update')));
        }
        
        // Return CSV data
        wp_send_json_success(array(
            'csv_data' => $csv_data,
            'filename' => 'yoast-seo-export-' . date('Y-m-d') . '.csv'
        ));
    }

    /**
     * Generate CSV data
     *
     * @param array $post_types Post types to export
     * @return string CSV data
     */
    private function generate_csv_data($post_types) {
        // Get posts
        $args = array(
            'post_type' => $post_types,
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'orderby' => 'ID',
            'order' => 'ASC'
        );
        
        $posts = get_posts($args);
        
        if (empty($posts)) {
            return '';
        }
        
        // Start output buffer
        ob_start();
        
        // Create CSV file pointer
        $output = fopen('php://output', 'w');
        
        // Add CSV header
        fputcsv($output, array('Post Type', 'ID', 'Title', 'URL', 'Meta Title', 'Meta Description'));
        
        // Add posts to CSV
        foreach ($posts as $post) {
            $post_id = $post->ID;
            $post_type = $post->post_type;
            $post_title = $post->post_title;
            $post_url = get_permalink($post_id);
            
            // Get Yoast SEO meta
            $meta_title = get_post_meta($post_id, '_yoast_wpseo_title', true);
            $meta_desc = get_post_meta($post_id, '_yoast_wpseo_metadesc', true);
            
            // Add row to CSV
            fputcsv($output, array(
                $post_type,
                $post_id,
                $post_title,
                $post_url,
                $meta_title,
                $meta_desc
            ));
        }
        
        // Get buffer content
        $csv_data = ob_get_clean();
        
        return $csv_data;
    }

    /**
     * Get available post types for export
     */
    private function get_available_post_types() {
        $post_types = get_post_types(array(
            'public' => true
        ), 'objects');
        
        $available_post_types = array();
        
        foreach ($post_types as $post_type) {
            // Skip attachments
            if ($post_type->name === 'attachment') {
                continue;
            }
            
            $available_post_types[$post_type->name] = $post_type->label;
        }
        
        return $available_post_types;
    }

    /**
     * Display settings page
     */
    public function display_settings_page() {
        // Get available post types
        $available_post_types = $this->get_available_post_types();
        ?>
        <div class="wrap">
            <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
            
            <div class="ybu-container">
                <div class="ybu-card">
                    <h2><?php _e('Export Current SEO Data', 'yoast-bulk-update'); ?></h2>
                    <p><?php _e('Export your current Yoast SEO data to a CSV file for editing.', 'yoast-bulk-update'); ?></p>
                    
                    <div class="ybu-card-content">
                        <form id="ybu-export-form" method="post">
                            <div class="ybu-form-group">
                                <label for="post_types"><?php _e('Post Types to Export', 'yoast-bulk-update'); ?></label>
                                <div class="ybu-checkbox-group">
                                    <?php foreach ($available_post_types as $name => $label) : ?>
                                        <label>
                                            <input type="checkbox" name="post_types[]" value="<?php echo esc_attr($name); ?>" <?php checked($name === 'post' || $name === 'page'); ?>>
                                            <?php echo esc_html($label); ?>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            
                            <div class="ybu-form-group">
                                <input type="hidden" name="action" value="ybu_export_csv">
                                <input type="hidden" name="nonce" value="<?php echo wp_create_nonce('ybu_ajax_nonce'); ?>">
                                <button type="submit" class="button button-primary"><?php _e('Export CSV', 'yoast-bulk-update'); ?></button>
                            </div>
                        </form>
                        
                        <div id="ybu-export-progress" style="display: none;">
                            <p class="ybu-progress-message"><?php _e('Generating CSV...', 'yoast-bulk-update'); ?></p>
                            <div class="ybu-progress-bar">
                                <div class="ybu-progress-bar-inner"></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="ybu-card">
                    <h2><?php _e('Import CSV File', 'yoast-bulk-update'); ?></h2>
                    <p><?php _e('Upload a CSV file to bulk update Yoast SEO meta titles and descriptions.', 'yoast-bulk-update'); ?></p>
                    
                    <div class="ybu-card-content">
                        <form id="ybu-import-form" method="post" enctype="multipart/form-data">
                            <div class="ybu-form-group">
                                <label for="csv_file"><?php _e('CSV File', 'yoast-bulk-update'); ?></label>
                                <input type="file" name="csv_file" id="csv_file" accept=".csv" required>
                                <p class="description"><?php _e('CSV file must include the following columns: Post Type, ID, Title, URL, Meta Title, Meta Description', 'yoast-bulk-update'); ?></p>
                            </div>
                            
                            <div class="ybu-form-group">
                                <input type="hidden" name="action" value="ybu_process_csv">
                                <input type="hidden" name="nonce" value="<?php echo wp_create_nonce('ybu_ajax_nonce'); ?>">
                                <button type="submit" class="button button-primary"><?php _e('Import', 'yoast-bulk-update'); ?></button>
                            </div>
                        </form>
                        
                        <div id="ybu-import-progress" style="display: none;">
                            <p class="ybu-progress-message"></p>
                            <div class="ybu-progress-bar">
                                <div class="ybu-progress-bar-inner"></div>
                            </div>
                        </div>
                        
                        <div id="ybu-import-results" style="display: none;">
                            <h3><?php _e('Import Results', 'yoast-bulk-update'); ?></h3>
                            <div class="ybu-results-content"></div>
                        </div>
                    </div>
                </div>
                
                <div class="ybu-card">
                    <h2><?php _e('Recommended Workflow', 'yoast-bulk-update'); ?></h2>
                    <div class="ybu-card-content">
                        <ol>
                            <li><?php _e('Use the "Export CSV" button to download your current SEO data.', 'yoast-bulk-update'); ?></li>
                            <li><?php _e('Open the CSV file in your preferred spreadsheet application (Excel, Google Sheets, etc.).', 'yoast-bulk-update'); ?></li>
                            <li><?php _e('Update the "Meta Title" and "Meta Description" columns with your optimized values.', 'yoast-bulk-update'); ?></li>
                            <li><?php _e('Save the file as CSV.', 'yoast-bulk-update'); ?></li>
                            <li><?php _e('Upload the updated CSV file using the Import form.', 'yoast-bulk-update'); ?></li>
                            <li><?php _e('Review the import results.', 'yoast-bulk-update'); ?></li>
                        </ol>
                    </div>
                </div>
                
                <div class="ybu-card">
                    <h2><?php _e('CSV Format', 'yoast-bulk-update'); ?></h2>
                    <div class="ybu-card-content">
                        <p><?php _e('Your CSV file should have the following columns:', 'yoast-bulk-update'); ?></p>
                        <ul>
                            <li><strong>Post Type</strong>: <?php _e('The post type (e.g. page, post, product, etc.)', 'yoast-bulk-update'); ?></li>
                            <li><strong>ID</strong>: <?php _e('The post ID', 'yoast-bulk-update'); ?></li>
                            <li><strong>Title</strong>: <?php _e('The post title (for reference only)', 'yoast-bulk-update'); ?></li>
                            <li><strong>URL</strong>: <?php _e('The post URL (for reference only)', 'yoast-bulk-update'); ?></li>
                            <li><strong>Meta Title</strong>: <?php _e('The meta title to set in Yoast SEO', 'yoast-bulk-update'); ?></li>
                            <li><strong>Meta Description</strong>: <?php _e('The meta description to set in Yoast SEO', 'yoast-bulk-update'); ?></li>
                        </ul>
                        
                        <p><?php _e('Example CSV format:', 'yoast-bulk-update'); ?></p>
                        <pre>Post Type,ID,Title,URL,Meta Title,Meta Description
page,5,Home,https://example.com/,"Home Page | My Website","Welcome to my website where you can find information about our products and services."
post,42,My Blog Post,https://example.com/my-blog-post/,"Amazing Blog Post | My Website","Read our latest blog post about amazing things and discover why it matters to you."</pre>
                    </div>
                </div>
                
                <div class="ybu-card">
                    <h2><?php _e('Notes', 'yoast-bulk-update'); ?></h2>
                    <div class="ybu-card-content">
                        <p><?php _e('Important information about using this plugin:', 'yoast-bulk-update'); ?></p>
                        <ul>
                            <li><?php _e('The plugin will only update posts that exist in your WordPress site.', 'yoast-bulk-update'); ?></li>
                            <li><?php _e('If a post ID is not found, that row will be skipped.', 'yoast-bulk-update'); ?></li>
                            <li><?php _e('Empty meta titles or descriptions will not overwrite existing values.', 'yoast-bulk-update'); ?></li>
                            <li><?php _e('Post Type, ID, Title, and URL columns are required but only Post Type and ID are used for processing.', 'yoast-bulk-update'); ?></li>
                            <li><?php _e('The Title and URL columns are for reference only.', 'yoast-bulk-update'); ?></li>
                        </ul>
                    </div>
                </div>
                
                <div class="ybu-card">
                    <h2><?php _e('About', 'yoast-bulk-update'); ?></h2>
                    <div class="ybu-card-content">
                        <p><?php _e('Yoast Bulk Update is a plugin that allows you to bulk update Yoast SEO meta titles and descriptions using a CSV file.', 'yoast-bulk-update'); ?></p>
                        <p><?php _e('Version:', 'yoast-bulk-update'); ?> <?php echo YBU_PLUGIN_VERSION; ?></p>
                        <p><?php _e('Author:', 'yoast-bulk-update'); ?> <a href="https://adipramono.com" target="_blank">Adi Pramono</a></p>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }
}