# KStory Plugin with REST API Support

This enhanced version of the KStory plugin includes full REST API support, allowing you to easily share and import stories between multiple WordPress websites.

## Features

- **Complete REST API Integration**: All story meta fields are exposed via WordPress REST API
- **Media Support**: Images, videos, and thumbnails are included in API responses with multiple sizes
- **Product Integration**: WooCommerce products attached to stories are included with full details
- **Story Importer**: Automated tool to import stories from other websites
- **Bulk Import**: Import multiple stories with media files automatically downloaded
- **Admin Interface**: Easy-to-use admin page for importing stories

## REST API Endpoints

### Get All Stories
```
GET /wp-json/wp/v2/story_shop
```

### Get Single Story
```
GET /wp-json/wp/v2/story_shop/{id}
```

### Create New Story
```
POST /wp-json/wp/v2/story_shop
```

### Update Story
```
PUT /wp-json/wp/v2/story_shop/{id}
```

## Available Meta Fields in REST API

### Story Details
- `story_description` (string): Story description text
- `enable_badge` (boolean): Whether badge is enabled
- `story_badge` (string): Badge text
- `enable_comments` (boolean): Whether comments are enabled
- `enable_products` (boolean): Whether products are enabled

### Style Settings
- `gradient_start` (string): Gradient start color
- `gradient_middle` (string): Gradient middle color  
- `gradient_end` (string): Gradient end color
- `container_width` (string): Container width in pixels
- `container_height` (string): Container height in pixels
- `image_width` (string): Image width in pixels
- `image_height` (string): Image height in pixels
- `badge_gradient_start` (string): Badge gradient start color
- `badge_gradient_middle` (string): Badge gradient middle color
- `badge_gradient_end` (string): Badge gradient end color
- `badge_font_size` (string): Badge font size
- `badge_margin_top` (string): Badge margin top
- `badge_border_radius` (string): Badge border radius
- `badge_padding` (string): Badge padding
- `badge_font_weight` (string): Badge font weight

### Media Fields
- `media_type` (string): 'image' or 'video'
- `story_image` (object): Image attachment with sizes
  ```json
  {
    "id": 123,
    "url": "https://example.com/image.jpg",
    "sizes": {
      "thumbnail": "https://example.com/image-150x150.jpg",
      "medium": "https://example.com/image-300x300.jpg",
      "large": "https://example.com/image-1024x1024.jpg",
      "full": "https://example.com/image.jpg"
    }
  }
  ```
- `story_video` (object): Video attachment
  ```json
  {
    "id": 124,
    "url": "https://example.com/video.mp4"
  }
  ```
- `story_thumbnail` (object): Custom thumbnail with sizes

### Product Integration
- `attached_products` (array): Array of attached WooCommerce products
  ```json
  [
    {
      "id": 456,
      "name": "Product Name",
      "price": "29.99",
      "regular_price": "39.99",
      "sale_price": "29.99",
      "permalink": "https://example.com/product/product-name",
      "image": "https://example.com/product-image.jpg"
    }
  ]
  ```

## Using the Story Importer

### Method 1: Admin Interface

1. Go to **Tools > Import Stories** in your WordPress admin
2. Enter the source website URL (e.g., `https://kaveh.moeinwp.com/1`)
3. Set the number of stories per batch
4. Click "Import Stories"

### Method 2: Programmatic Import

```php
// Include the importer
require_once 'path/to/story-importer.php';

// Import stories
$result = import_stories_from_source('https://kaveh.moeinwp.com/1', 10, 1);

if ($result['success']) {
    echo 'Imported ' . $result['imported'] . ' stories';
} else {
    echo 'Import failed: ' . $result['message'];
}
```

### Method 3: Bulk Import All Stories

```php
function bulk_import_all_stories($source_url) {
    $importer = new StoryImporter($source_url);
    $total_stories = $importer->get_total_stories();
    $per_page = 10;
    $total_pages = ceil($total_stories / $per_page);
    
    for ($page = 1; $page <= $total_pages; $page++) {
        $result = $importer->import_stories($per_page, $page);
        if ($result['success']) {
            echo 'Page ' . $page . ': Imported ' . $result['imported'] . ' stories\n';
        }
        sleep(2); // Prevent server overload
    }
}
```

## Installation

### On Source Website (where stories are created)

1. The plugin is already installed and configured
2. Stories are automatically available via REST API at `/wp-json/wp/v2/story_shop`
3. No additional setup required

### On Target Websites (where you want to import stories)

1. Install the KStory plugin (copy the entire `kstory` folder)
2. Include the story importer:
   ```php
   // In your theme's functions.php
   require_once get_template_directory() . '/path/to/kstory/story-importer.php';
   ```
3. Use the admin interface or programmatic methods to import stories

## Example API Response

```json
{
  "id": 16276,
  "date": "2025-08-09T11:00:13",
  "title": {
    "rendered": "برای تو"
  },
  "content": {
    "rendered": ""
  },
  "story_description": "This is a sample story description",
  "enable_badge": true,
  "story_badge": "New",
  "enable_comments": true,
  "enable_products": true,
  "media_type": "image",
  "gradient_start": "#833AB4",
  "gradient_middle": "#FD1D1D",
  "gradient_end": "#FCB045",
  "container_width": "90",
  "container_height": "90",
  "story_image": {
    "id": 123,
    "url": "https://example.com/story-image.jpg",
    "sizes": {
      "thumbnail": "https://example.com/story-image-150x150.jpg",
      "medium": "https://example.com/story-image-300x300.jpg",
      "large": "https://example.com/story-image-1024x1024.jpg",
      "full": "https://example.com/story-image.jpg"
    }
  },
  "attached_products": [
    {
      "id": 456,
      "name": "Sample Product",
      "price": "29.99",
      "regular_price": "39.99",
      "sale_price": "29.99",
      "permalink": "https://example.com/product/sample-product",
      "image": "https://example.com/product-image.jpg"
    }
  ]
}
```

## Advanced Usage

### Custom Filtering During Import

```php
// Only import stories with badges
function only_badge_stories($story) {
    return isset($story['enable_badge']) && $story['enable_badge'] === true;
}

$importer = new StoryImporter('https://kaveh.moeinwp.com/1');
$stories = $importer->fetch_stories(100, 1);

foreach ($stories as $story) {
    if (only_badge_stories($story)) {
        $importer->import_single_story($story);
    }
}
```

### Scheduled Imports

```php
// Schedule daily imports
function schedule_story_import() {
    if (!wp_next_scheduled('daily_story_import')) {
        wp_schedule_event(time(), 'daily', 'daily_story_import');
    }
}
add_action('wp', 'schedule_story_import');

function handle_daily_story_import() {
    $result = import_stories_from_source('https://kaveh.moeinwp.com/1', 5, 1);
    error_log('Daily story import: ' . json_encode($result));
}
add_action('daily_story_import', 'handle_daily_story_import');
```

## Important Notes

1. **Media Files**: Images and videos are automatically downloaded and stored locally during import
2. **Product Mapping**: Attached products are imported as references. You'll need to manually map them to your local products
3. **Duplicate Prevention**: The importer checks for existing stories to prevent duplicates
4. **Performance**: Use reasonable batch sizes (10-20 stories) to prevent timeouts
5. **Authentication**: For private sites, you may need to add authentication headers

## Troubleshooting

### Common Issues

1. **Import Fails**: Check if the source URL is accessible and the REST API is enabled
2. **Media Not Downloading**: Verify file permissions and available disk space
3. **Timeouts**: Reduce batch size or increase PHP execution time
4. **Missing Products**: Products need to exist on the target site or be manually mapped

### Debug Mode

Enable WordPress debug mode to see detailed error messages:

```php
// In wp-config.php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
```

Check the debug log at `/wp-content/debug.log` for import errors.

## Support

For issues or questions:
1. Check the debug logs
2. Verify REST API accessibility
3. Test with a small batch first
4. Ensure proper file permissions

## Version History

- **v2.1**: Added complete REST API support and story importer
- **v2.0**: Original KStory plugin functionality