<?php
/**
 * API Publisher Class
 * Handles fetching and publishing posts from external API
 */

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

class GBX_API_Publisher {
    
    private $api_endpoint = 'http://stg.globexportal.net/api/v1/blog/article';
    
    public function __construct() {
        add_action('init', array($this, 'init'));
        add_action('wp_ajax_rpp_fetch_post', array($this, 'ajax_fetch_post'));
        add_action('wp_ajax_rpp_enable_schedule', array($this, 'ajax_enable_schedule'));
        add_action('wp_ajax_rpp_disable_schedule', array($this, 'ajax_disable_schedule'));
        add_action('wp_ajax_rpp_update_status', array($this, 'ajax_update_status'));
        add_action('rpp_daily_event', array($this, 'scheduled_fetch_post'));
        add_action('admin_notices', array($this, 'aioseo_admin_notice'));
    }
    
    public function init() {
        if (get_option('rpp_daily_enabled', false) && !wp_next_scheduled('rpp_daily_event')) {
            wp_schedule_event(time(), 'daily', 'rpp_daily_event');
        }
    }
    
    public function aioseo_admin_notice() {
        if (!current_user_can('install_plugins')) {
            return;
        }
        
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        
        $plugin_file = 'all-in-one-seo-pack/all_in_one_seo_pack.php';
        
        if (!is_plugin_active($plugin_file)) {
            echo '<div class="notice notice-error"><p>';
            echo '<strong>GBX Blog Suite</strong> requires <strong>All in One SEO</strong> plugin to be installed and active.</p>';
            
            $installed_plugins = get_plugins();
            if (isset($installed_plugins[$plugin_file])) {
                $activate_url = wp_nonce_url(
                    admin_url('plugins.php?action=activate&plugin=' . $plugin_file),
                    'activate-plugin_' . $plugin_file
                );
                echo '<p><a class="button button-primary" href="' . esc_url($activate_url) . '">Activate AIOSEO</a></p>';
            } else {
                $install_url = wp_nonce_url(
                    admin_url('update.php?action=install-plugin&plugin=all-in-one-seo-pack'),
                    'install-plugin_all-in-one-seo-pack'
                );
                echo '<p><a class="button button-primary" href="' . esc_url($install_url) . '">Install AIOSEO</a></p>';
            }
            
            echo '</div>';
        }
    }
    
    public function ajax_fetch_post() {
        if (!wp_verify_nonce($_POST['nonce'], 'rpp_fetch_nonce') || !current_user_can('manage_options')) {
            wp_die('Security check failed');
        }
        
        $result = $this->fetch_and_publish_post();
        
        if ($result['success']) {
            wp_send_json_success($result['message']);
        } else {
            wp_send_json_error($result['message']);
        }
    }
    
    public function ajax_enable_schedule() {
        if (!wp_verify_nonce($_POST['nonce'], 'rpp_schedule_nonce') || !current_user_can('manage_options')) {
            wp_die('Security check failed');
        }
        
        update_option('rpp_daily_enabled', true);
        if (!wp_next_scheduled('rpp_daily_event')) {
            wp_schedule_event(time(), 'daily', 'rpp_daily_event');
        }
        
        wp_send_json_success('Daily scheduling enabled successfully.');
    }
    
    public function ajax_update_status() {
        if (!wp_verify_nonce($_POST['nonce'], 'rpp_status_nonce') || !current_user_can('manage_options')) {
            wp_die('Security check failed');
        }
        
        $status = sanitize_text_field($_POST['status']);
        if (in_array($status, array('draft', 'publish'))) {
            update_option('rpp_publish_status', $status);
            wp_send_json_success('Status updated successfully.');
        } else {
            wp_send_json_error('Invalid status.');
        }
    }
    
    public function ajax_disable_schedule() {
        if (!wp_verify_nonce($_POST['nonce'], 'rpp_schedule_nonce') || !current_user_can('manage_options')) {
            wp_die('Security check failed');
        }
        
        update_option('rpp_daily_enabled', false);
        wp_clear_scheduled_hook('rpp_daily_event');
        
        wp_send_json_success('Daily scheduling disabled successfully.');
    }
    
    public function scheduled_fetch_post() {
        if (get_option('rpp_daily_enabled', false)) {
            $this->fetch_and_publish_post();
        }
    }
    
    private function fetch_and_publish_post() {
        $current_domain = parse_url(home_url(), PHP_URL_HOST);
        $response = wp_remote_post($this->api_endpoint, array(
            'timeout' => 30,
            'headers' => array(
                'Content-Type' => 'application/json',
            ),
            'body' => json_encode(array(
                'domain_name' => $current_domain,
            )),
        ));
        
        if (is_wp_error($response)) {
            return array('success' => false, 'message' => 'API request failed: ' . $response->get_error_message());
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (!$data || !isset($data['title'])) {
            return array('success' => false, 'message' => 'No Post Data Found at API');
        }
        
        $publish_status = get_option('rpp_publish_status', 'publish');
        $post_data = array(
            'post_title' => sanitize_text_field($data['title']),
            'post_content' => wp_kses_post($data['description']),
            'post_name' => sanitize_title($data['slug']),
            'post_status' => 'draft',
            'post_type' => 'post'
        );
        
        $post_id = wp_insert_post($post_data);
        
        if (is_wp_error($post_id)) {
            return array('success' => false, 'message' => 'Failed to create post: ' . $post_id->get_error_message());
        }
        
        if (!empty($data['feature_img'])) {
            $this->set_featured_image($post_id, $data['feature_img']);
        }
        
        if (!empty($data['category']) && is_array($data['category'])) {
            $this->assign_categories($post_id, $data['category']);
        }
        
        if (!empty($data['meta_title']) || !empty($data['meta_description']) || !empty($data['keywords'])) {
            $this->set_seo_meta($post_id, $data['meta_title'], $data['meta_description'], $data['keywords']);
        }
        
        wp_update_post(array('ID' => $post_id, 'post_status' => $publish_status));
        
        $article = $data['article'];
        $response = wp_remote_post($this->api_endpoint . '/' . $article, array(
            'timeout' => 30,
            'headers' => array(
                'Content-Type' => 'application/json',
            ),
            'body' => json_encode(array(
                'domain_name' => $current_domain,
                'wordpress_post_id' => $post_id
            )),
        ));
        
        return array(
            'success' => true,
            'message' => 'Post published successfully!',
            'domain_name' => $current_domain,
            'wordpress_post_id' => $post_id,
            'edit_link' => get_edit_post_link($post_id),
            'permalink' => get_permalink($post_id)
        );
    }
    
    private function download_image_to_wp_media($image_url, $slug) {
        $response = wp_remote_get($image_url, array('timeout' => 30));
        
        if (is_wp_error($response)) {
            return false;
        }
        
        $image_data = wp_remote_retrieve_body($response);
        $filename = $slug . '.jpg';
        
        $upload = wp_upload_bits($filename, null, $image_data);
        
        if ($upload['error']) {
            return false;
        }
        
        $attachment = array(
            'post_mime_type' => 'image/jpeg',
            'post_title' => $filename,
            'post_content' => '',
            'post_status' => 'inherit'
        );
        
        $attachment_id = wp_insert_attachment($attachment, $upload['file']);
        
        if (!is_wp_error($attachment_id)) {
            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $attachment_data = wp_generate_attachment_metadata($attachment_id, $upload['file']);
            wp_update_attachment_metadata($attachment_id, $attachment_data);
            return $attachment_id;
        }
        
        return false;
    }
    
    private function set_featured_image($post_id, $image_url) {
        $post = get_post($post_id);
        $slug = $post ? sanitize_title($post->post_name) : 'image';
        $attachment_id = $this->download_image_to_wp_media($image_url, $slug);
        
        if ($attachment_id) {
            set_post_thumbnail($post_id, $attachment_id);
            return true;
        }
        
        return false;
    }
    
    private function assign_categories($post_id, $categories) {
        $category_ids = array();
        
        foreach ($categories as $category_name) {
            $category_name = sanitize_text_field($category_name);
            $category = get_term_by('name', $category_name, 'category');
            
            if (!$category) {
                $category_data = wp_insert_term($category_name, 'category');
                if (!is_wp_error($category_data)) {
                    $category_ids[] = $category_data['term_id'];
                }
            } else {
                $category_ids[] = $category->term_id;
            }
        }
        
        if (!empty($category_ids)) {
            wp_set_post_categories($post_id, $category_ids);
        }
    }
    
    private function set_seo_meta($post_id, $meta_title, $meta_description, $keywords = '') {
        $meta_title = sanitize_text_field($meta_title);
        $meta_description = sanitize_textarea_field($meta_description);
        $keywords = sanitize_text_field($keywords);
        
        if (defined('AIOSEO_VERSION')) {
            global $wpdb;
            
            $table_name = $wpdb->prefix . 'aioseo_posts';
            
            $existing = $wpdb->get_row($wpdb->prepare(
                "SELECT * FROM {$table_name} WHERE post_id = %d",
                $post_id
            ));
            
            $seo_data = array(
                'title' => $meta_title,
                'description' => $meta_description,
                'keyphrases' => json_encode(array(
                    'focus' => array(
                        'keyphrase' => $keywords,
                        'score' => 0
                    )
                ))
            );
            
            if ($existing) {
                $wpdb->update(
                    $table_name,
                    $seo_data,
                    array('post_id' => $post_id)
                );
            } else {
                $seo_data['post_id'] = $post_id;
                $seo_data['created'] = current_time('mysql');
                $seo_data['updated'] = current_time('mysql');
                
                $wpdb->insert($table_name, $seo_data);
            }
        }
    }
}
