<?php
/*
 * Story Importer Script
 * Use this script on your other WordPress websites to import stories from your main site
 * 
 * Usage:
 * 1. Include this file in your theme's functions.php or create a custom plugin
 * 2. Call the import function: import_stories_from_source('https://kaveh.moeinwp.com/1');
 * 3. Or use the admin interface by adding ?import_stories=1 to your admin URL
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class StoryImporter {
    
    private $source_url;
    private $api_endpoint;
    
    public function __construct($source_url) {
        $this->source_url = rtrim($source_url, '/');
        $this->api_endpoint = $this->source_url . '/wp-json/wp/v2/story_shop';
    }
    
    /**
     * Import all stories from source website
     */
    public function import_stories($per_page = 10, $page = 1) {
        $stories = $this->fetch_stories($per_page, $page);
        
        if (empty($stories)) {
            return array('success' => false, 'message' => 'No stories found or API error');
        }
        
        $imported = 0;
        $errors = array();
        
        foreach ($stories as $story) {
            $result = $this->import_single_story($story);
            if ($result['success']) {
                $imported++;
            } else {
                $errors[] = $result['message'];
            }
        }
        
        return array(
            'success' => true,
            'imported' => $imported,
            'total' => count($stories),
            'errors' => $errors
        );
    }
    
    /**
     * Fetch stories from source API
     */
    private function fetch_stories($per_page = 10, $page = 1) {
        $url = $this->api_endpoint . '?per_page=' . $per_page . '&page=' . $page;
        
        $response = wp_remote_get($url, array(
            'timeout' => 30,
            'headers' => array(
                'Accept' => 'application/json'
            )
        ));
        
        if (is_wp_error($response)) {
            error_log('Story Import Error: ' . $response->get_error_message());
            return false;
        }
        
        $body = wp_remote_retrieve_body($response);
        $stories = json_decode($body, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            error_log('Story Import JSON Error: ' . json_last_error_msg());
            return false;
        }
        
        return $stories;
    }
    
    /**
     * Import a single story
     */
    private function import_single_story($story_data) {
        try {
            // Check if story already exists
            $existing = get_posts(array(
                'post_type' => 'story_shop',
                'meta_query' => array(
                    array(
                        'key' => '_source_story_id',
                        'value' => $story_data['id'],
                        'compare' => '='
                    )
                ),
                'posts_per_page' => 1
            ));
            
            if (!empty($existing)) {
                return array('success' => false, 'message' => 'Story already exists: ' . $story_data['title']['rendered']);
            }
            
            // Create the post
            $post_data = array(
                'post_title' => $story_data['title']['rendered'],
                'post_content' => $story_data['content']['rendered'],
                'post_status' => 'publish',
                'post_type' => 'story_shop',
                'comment_status' => $story_data['comment_status']
            );
            
            $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());
            }
            
            // Store source story ID for future reference
            update_post_meta($post_id, '_source_story_id', $story_data['id']);
            update_post_meta($post_id, '_source_url', $this->source_url);
            
            // Import meta fields
            $this->import_story_meta($post_id, $story_data);
            
            // Import media files
            $this->import_story_media($post_id, $story_data);
            
            return array('success' => true, 'message' => 'Story imported successfully: ' . $story_data['title']['rendered']);
            
        } catch (Exception $e) {
            return array('success' => false, 'message' => 'Error importing story: ' . $e->getMessage());
        }
    }
    
    /**
     * Import story meta fields
     */
    private function import_story_meta($post_id, $story_data) {
        // Story details
        if (isset($story_data['story_description'])) {
            update_post_meta($post_id, '_story_description', $story_data['story_description']);
        }
        
        if (isset($story_data['enable_badge'])) {
            update_post_meta($post_id, '_enable_badge', $story_data['enable_badge'] ? 1 : 0);
        }
        
        if (isset($story_data['story_badge'])) {
            update_post_meta($post_id, '_story_badge', $story_data['story_badge']);
        }
        
        if (isset($story_data['enable_comments'])) {
            update_post_meta($post_id, '_enable_comments', $story_data['enable_comments'] ? 1 : 0);
        }
        
        if (isset($story_data['enable_products'])) {
            update_post_meta($post_id, '_enable_products', $story_data['enable_products'] ? 1 : 0);
        }
        
        // Style fields
        $style_fields = array(
            'gradient_start', 'gradient_middle', 'gradient_end',
            'container_width', 'container_height', 'image_width', 'image_height',
            'badge_gradient_start', 'badge_gradient_middle', 'badge_gradient_end',
            'badge_font_size', 'badge_margin_top', 'badge_border_radius',
            'badge_padding', 'badge_font_weight'
        );
        
        foreach ($style_fields as $field) {
            if (isset($story_data[$field])) {
                update_post_meta($post_id, '_' . $field, $story_data[$field]);
            }
        }
        
        // Media type
        if (isset($story_data['media_type'])) {
            update_post_meta($post_id, '_media_type', $story_data['media_type']);
        }
        
        // Attached products (store as reference, actual products need to be mapped manually)
        if (isset($story_data['attached_products']) && is_array($story_data['attached_products'])) {
            update_post_meta($post_id, '_source_attached_products', $story_data['attached_products']);
            // Note: You'll need to manually map these to your local product IDs
        }
    }
    
    /**
     * Import and download media files
     */
    private function import_story_media($post_id, $story_data) {
        // Import story image
        if (isset($story_data['story_image']) && !empty($story_data['story_image']['url'])) {
            $image_id = $this->download_and_attach_media($story_data['story_image']['url'], $post_id, 'story_image');
            if ($image_id) {
                update_post_meta($post_id, '_story_image', $image_id);
            }
        }
        
        // Import story video
        if (isset($story_data['story_video']) && !empty($story_data['story_video']['url'])) {
            $video_id = $this->download_and_attach_media($story_data['story_video']['url'], $post_id, 'story_video');
            if ($video_id) {
                update_post_meta($post_id, '_story_video', $video_id);
            }
        }
        
        // Import story thumbnail
        if (isset($story_data['story_thumbnail']) && !empty($story_data['story_thumbnail']['url'])) {
            $thumbnail_id = $this->download_and_attach_media($story_data['story_thumbnail']['url'], $post_id, 'story_thumbnail');
            if ($thumbnail_id) {
                update_post_meta($post_id, '_story_thumbnail', $thumbnail_id);
            }
        }
    }
    
    /**
     * Download media file and attach to post
     */
    private function download_and_attach_media($url, $post_id, $type = 'image') {
        if (empty($url)) {
            return false;
        }
        
        // Get file info
        $file_info = pathinfo($url);
        $filename = $file_info['basename'];
        
        // Download file
        $response = wp_remote_get($url, array(
            'timeout' => 60
        ));
        
        if (is_wp_error($response)) {
            error_log('Failed to download media: ' . $response->get_error_message());
            return false;
        }
        
        $file_content = wp_remote_retrieve_body($response);
        
        if (empty($file_content)) {
            error_log('Empty file content for: ' . $url);
            return false;
        }
        
        // Upload to WordPress
        $upload = wp_upload_bits($filename, null, $file_content);
        
        if ($upload['error']) {
            error_log('Upload error: ' . $upload['error']);
            return false;
        }
        
        // Create attachment
        $attachment = array(
            'post_mime_type' => wp_check_filetype($filename)['type'],
            'post_title' => sanitize_file_name($filename),
            'post_content' => '',
            'post_status' => 'inherit'
        );
        
        $attachment_id = wp_insert_attachment($attachment, $upload['file'], $post_id);
        
        if (is_wp_error($attachment_id)) {
            error_log('Attachment creation error: ' . $attachment_id->get_error_message());
            return false;
        }
        
        // Generate metadata
        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;
    }
    
    /**
     * Get total number of stories available
     */
    public function get_total_stories() {
        $response = wp_remote_head($this->api_endpoint);
        
        if (is_wp_error($response)) {
            return 0;
        }
        
        $headers = wp_remote_retrieve_headers($response);
        return isset($headers['x-wp-total']) ? (int) $headers['x-wp-total'] : 0;
    }
}

/**
 * Helper function to import stories
 */
function import_stories_from_source($source_url, $per_page = 10, $page = 1) {
    $importer = new StoryImporter($source_url);
    return $importer->import_stories($per_page, $page);
}

/**
 * Admin interface for importing stories
 */
function add_story_import_admin_page() {
    add_management_page(
        'Import Stories',
        'Import Stories',
        'manage_options',
        'import-stories',
        'story_import_admin_page'
    );
}
add_action('admin_menu', 'add_story_import_admin_page');

function story_import_admin_page() {
    if (isset($_POST['import_stories']) && wp_verify_nonce($_POST['_wpnonce'], 'import_stories')) {
        $source_url = sanitize_url($_POST['source_url']);
        $per_page = intval($_POST['per_page']) ?: 10;
        
        if (!empty($source_url)) {
            $result = import_stories_from_source($source_url, $per_page);
            
            if ($result['success']) {
                echo '<div class="notice notice-success"><p>Successfully imported ' . $result['imported'] . ' out of ' . $result['total'] . ' stories.</p></div>';
                if (!empty($result['errors'])) {
                    echo '<div class="notice notice-warning"><p>Errors: ' . implode('<br>', $result['errors']) . '</p></div>';
                }
            } else {
                echo '<div class="notice notice-error"><p>Import failed: ' . $result['message'] . '</p></div>';
            }
        }
    }
    
    ?>
    <div class="wrap">
        <h1>Import Stories</h1>
        <form method="post">
            <?php wp_nonce_field('import_stories'); ?>
            <table class="form-table">
                <tr>
                    <th scope="row">Source Website URL</th>
                    <td>
                        <input type="url" name="source_url" value="https://kaveh.moeinwp.com/1" class="regular-text" required />
                        <p class="description">Enter the URL of the website you want to import stories from</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">Stories per batch</th>
                    <td>
                        <input type="number" name="per_page" value="10" min="1" max="100" />
                        <p class="description">Number of stories to import in one batch</p>
                    </td>
                </tr>
            </table>
            <?php submit_button('Import Stories', 'primary', 'import_stories'); ?>
        </form>
        
        <h2>Usage Instructions</h2>
        <ol>
            <li>Make sure the kstory plugin is installed and activated on this website</li>
            <li>Enter the source website URL (the site you want to import stories from)</li>
            <li>Click "Import Stories" to start the import process</li>
            <li>Media files (images/videos) will be automatically downloaded and attached</li>
            <li>You may need to manually map attached products to your local products</li>
        </ol>
        
        <h2>Programmatic Usage</h2>
        <p>You can also import stories programmatically using:</p>
        <code>$result = import_stories_from_source('https://kaveh.moeinwp.com/1', 10, 1);</code>
    </div>
    <?php
}

/**
 * AJAX handler for importing stories
 */
function handle_ajax_story_import() {
    check_ajax_referer('story_import_nonce', 'nonce');
    
    if (!current_user_can('manage_options')) {
        wp_die('Unauthorized');
    }
    
    $source_url = sanitize_url($_POST['source_url']);
    $per_page = intval($_POST['per_page']) ?: 10;
    $page = intval($_POST['page']) ?: 1;
    
    $result = import_stories_from_source($source_url, $per_page, $page);
    
    wp_send_json($result);
}
add_action('wp_ajax_import_stories', 'handle_ajax_story_import');