<?php
/**
 * Main plugin class
 *
 * @since      1.0.0
 * @package    Yoast_Bulk_Update
 */

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

/**
 * Main plugin class
 */
class Yoast_Bulk_Update {

    /**
     * Plugin settings
     *
     * @var Yoast_Bulk_Update_Settings
     */
    protected $settings;

    /**
     * Initialize the plugin
     */
    public function __construct() {
        $this->load_dependencies();
        $this->set_locale();
        $this->define_admin_hooks();
    }

    /**
     * Load the required dependencies
     */
    private function load_dependencies() {
        $this->settings = new Yoast_Bulk_Update_Settings();
    }

    /**
     * Set the locale for internationalization
     */
    private function set_locale() {
        add_action('plugins_loaded', array($this, 'load_plugin_textdomain'));
    }

    /**
     * Load the plugin text domain for translation
     */
    public function load_plugin_textdomain() {
        load_plugin_textdomain(
            'yoast-bulk-update',
            false,
            dirname(dirname(plugin_basename(__FILE__))) . '/languages/'
        );
    }

    /**
     * Register all of the hooks related to the admin area functionality
     */
    private function define_admin_hooks() {
        // Add admin menu
        add_action('admin_menu', array($this->settings, 'add_admin_menu'));
        
        // Register settings
        add_action('admin_init', array($this->settings, 'register_settings'));
        
        // Add admin scripts and styles
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_styles'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        
        // Add AJAX handlers
        add_action('wp_ajax_ybu_process_csv', array($this, 'process_csv_ajax'));
    }

    /**
     * Enqueue admin styles
     */
    public function enqueue_admin_styles($hook) {
        if ('seo_page_yoast-bulk-update' !== $hook && 'settings_page_yoast-bulk-update' !== $hook) {
            return;
        }
        
        wp_enqueue_style(
            'yoast-bulk-update-admin',
            YBU_PLUGIN_URL . 'assets/css/admin.css',
            array(),
            YBU_PLUGIN_VERSION
        );
    }

    /**
     * Enqueue admin scripts
     */
    public function enqueue_admin_scripts($hook) {
        if ('seo_page_yoast-bulk-update' !== $hook && 'settings_page_yoast-bulk-update' !== $hook) {
            return;
        }
        
        wp_enqueue_script(
            'yoast-bulk-update-admin',
            YBU_PLUGIN_URL . 'assets/js/admin.js',
            array('jquery'),
            YBU_PLUGIN_VERSION,
            true
        );
        
        wp_localize_script(
            'yoast-bulk-update-admin',
            'ybu_ajax',
            array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('ybu_ajax_nonce'),
                'processing_text' => __('Processing...', 'yoast-bulk-update'),
                'success_text' => __('CSV processed successfully!', 'yoast-bulk-update'),
                'error_text' => __('Error processing CSV.', 'yoast-bulk-update')
            )
        );
    }

    /**
     * Process CSV file via AJAX
     */
    public function process_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')));
        }
        
        // Check file
        if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
            wp_send_json_error(array('message' => __('No file uploaded or upload error.', 'yoast-bulk-update')));
        }
        
        // Get file
        $file = $_FILES['csv_file']['tmp_name'];
        
        // Process CSV
        $result = $this->process_csv($file);
        
        if (is_wp_error($result)) {
            wp_send_json_error(array('message' => $result->get_error_message()));
        }
        
        wp_send_json_success(array(
            'message' => __('CSV processed successfully!', 'yoast-bulk-update'),
            'updated' => $result['updated'],
            'skipped' => $result['skipped']
        ));
    }

    /**
     * Process CSV file
     *
     * @param string $file Path to CSV file
     * @return array|WP_Error Results or error
     */
    public function process_csv($file) {
        // Check if file exists
        if (!file_exists($file)) {
            return new WP_Error('file_not_found', __('CSV file not found.', 'yoast-bulk-update'));
        }
        
        // Open file
        $handle = fopen($file, 'r');
        if (!$handle) {
            return new WP_Error('file_open_error', __('Could not open CSV file.', 'yoast-bulk-update'));
        }
        
        // Get header row
        $header = fgetcsv($handle);
        if (!$header) {
            fclose($handle);
            return new WP_Error('csv_error', __('Could not read CSV header.', 'yoast-bulk-update'));
        }
        
        // Check required columns
        $required_columns = array('Post Type', 'ID', 'Title', 'URL', 'Meta Title', 'Meta Description');
        $missing_columns = array();
        
        foreach ($required_columns as $column) {
            if (!in_array($column, $header)) {
                $missing_columns[] = $column;
            }
        }
        
        if (!empty($missing_columns)) {
            fclose($handle);
            return new WP_Error('missing_columns', sprintf(
                __('Missing required columns: %s', 'yoast-bulk-update'),
                implode(', ', $missing_columns)
            ));
        }
        
        // Get column indexes
        $column_indexes = array(
            'post_type' => array_search('Post Type', $header),
            'id' => array_search('ID', $header),
            'title' => array_search('Title', $header),
            'url' => array_search('URL', $header),
            'meta_title' => array_search('Meta Title', $header),
            'meta_desc' => array_search('Meta Description', $header)
        );
        
        // Process rows
        $updated = 0;
        $skipped = 0;
        $row_num = 1; // Header row is row 1
        
        while (($row = fgetcsv($handle)) !== false) {
            $row_num++;
            
            // Skip empty rows
            if (empty($row)) {
                $skipped++;
                continue;
            }
            
            // Get row data
            $post_id = isset($row[$column_indexes['id']]) ? intval($row[$column_indexes['id']]) : 0;
            $meta_title = isset($row[$column_indexes['meta_title']]) ? sanitize_text_field($row[$column_indexes['meta_title']]) : '';
            $meta_desc = isset($row[$column_indexes['meta_desc']]) ? sanitize_textarea_field($row[$column_indexes['meta_desc']]) : '';
            
            // Skip if required fields are missing
            if (empty($post_id) || (empty($meta_title) && empty($meta_desc))) {
                $skipped++;
                continue;
            }
            
            // Check if post exists
            $post = get_post($post_id);
            if (!$post) {
                $skipped++;
                continue;
            }
            
            // Update post meta
            $updated_meta = false;
            
            if (!empty($meta_title)) {
                update_post_meta($post_id, '_yoast_wpseo_title', $meta_title);
                $updated_meta = true;
            }
            
            if (!empty($meta_desc)) {
                update_post_meta($post_id, '_yoast_wpseo_metadesc', $meta_desc);
                $updated_meta = true;
            }
            
            if ($updated_meta) {
                $updated++;
            } else {
                $skipped++;
            }
        }
        
        fclose($handle);
        
        return array(
            'updated' => $updated,
            'skipped' => $skipped
        );
    }

    /**
     * Run the plugin
     */
    public function run() {
        // Plugin is running
    }
}