<?php
/*
Plugin Name: Kstory
Description: A plugin for creating and managing stories with products.
Version: 2.0
Author: MoeinWP
*/

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


class StoryLMMain
{

    public function __construct()
    {
        // Include required files
        require_once KSTORY_PATH . 'post-type.php';
        require_once KSTORY_PATH . 'views.php';
        require_once KSTORY_PATH . 'ajaxes.php';
        require_once KSTORY_PATH . 'assets.php';
        require_once KSTORY_PATH . 'story-importer.php';
        // Activation hook
        register_activation_hook(__FILE__, [$this,'story_shop_activation']);
        // Initialize plugin
        add_action('init', [$this, 'story_shop_init']);
    }



    // Plugin activation
    public function story_shop_activation()
    {
        // Register post type
        $this->story_shop_register_post_type();

        // Flush rewrite rules
        flush_rewrite_rules();
    }


    public function story_shop_init()
    {
        // Register post type
        $this->story_shop_register_post_type();

        // Add meta boxes
        add_action('add_meta_boxes', [$this,'story_shop_add_meta_boxes']);

        // Save post meta
        add_action('save_post', 'story_shop_save_meta_boxes');
        
        // Register REST API fields
        add_action('rest_api_init', [$this, 'register_story_rest_fields']);
    }

    // Register custom post type
    public function story_shop_register_post_type()
    {
        $labels = array(
            'name' => __('Stories', 'kavehTheme'),
            'singular_name' => __('Story', 'kavehTheme'),
            'menu_name' => __('Stories', 'kavehTheme'),
            'add_new' => __('Add New Story', 'kavehTheme'),
            'add_new_item' => __('Add New Story', 'kavehTheme'),
            'edit_item' => __('Edit Story', 'kavehTheme'),
            'new_item' => __('New Story', 'kavehTheme'),
            'view_item' => __('View Story', 'kavehTheme'),
            'search_items' => __('Search Stories', 'kavehTheme'),
            'not_found' => __('No stories found', 'kavehTheme'),
            'not_found_in_trash' => __('No stories found in trash', 'kavehTheme'),
        );

        $args = array(
            'labels' => $labels,
            'public' => true,
            'publicly_queryable' => true,
            'show_ui' => true,
            'show_in_menu' => true,
            'query_var' => true,
            'rewrite' => array('slug' => 'story'),
            'capability_type' => 'post',
            'has_archive' => true,
            'hierarchical' => false,
            'menu_position' => 20,
            'menu_icon' => 'dashicons-format-gallery',
            'supports' => array('title', 'editor', 'comments'),
            'show_in_rest' => true,
        );

        register_post_type('story_shop', $args);
    }

    // Add meta boxes
    public function story_shop_add_meta_boxes()
    {
        add_meta_box(
            'story_shop_details',
            __('Story Details', 'kavehTheme'),
            'story_shop_details_callback',
            'story_shop',
            'normal',
            'high'
        );

        add_meta_box(
            'story_shop_style',
            __('Story Style', 'kavehTheme'),
            'story_shop_style_callback',
            'story_shop',
            'normal',
            'high'
        );

        add_meta_box(
            'story_shop_media',
            __('Story Media', 'kavehTheme'),
            'story_shop_media_callback',
            'story_shop',
            'normal',
            'high'
        );

        add_meta_box(
            'story_shop_products',
            __('Attached Products', 'kavehTheme'),
            'story_shop_products_callback',
            'story_shop',
            'side',
            'default'
        );
    }

    // Register REST API fields for story meta
    public function register_story_rest_fields()
    {
        // Story details fields
        register_rest_field('story_shop', 'story_description', array(
            'get_callback' => function($post) {
                return get_post_meta($post['id'], '_story_description', true);
            },
            'update_callback' => function($value, $post) {
                return update_post_meta($post->ID, '_story_description', sanitize_textarea_field($value));
            },
            'schema' => array(
                'description' => 'Story description',
                'type' => 'string',
                'context' => array('view', 'edit')
            )
        ));

        register_rest_field('story_shop', 'enable_badge', array(
            'get_callback' => function($post) {
                return (bool) get_post_meta($post['id'], '_enable_badge', true);
            },
            'update_callback' => function($value, $post) {
                return update_post_meta($post->ID, '_enable_badge', $value ? 1 : 0);
            },
            'schema' => array(
                'description' => 'Enable badge on story',
                'type' => 'boolean',
                'context' => array('view', 'edit')
            )
        ));

        register_rest_field('story_shop', 'story_badge', array(
            'get_callback' => function($post) {
                return get_post_meta($post['id'], '_story_badge', true);
            },
            'update_callback' => function($value, $post) {
                return update_post_meta($post->ID, '_story_badge', sanitize_text_field($value));
            },
            'schema' => array(
                'description' => 'Badge text',
                'type' => 'string',
                'context' => array('view', 'edit')
            )
        ));

        register_rest_field('story_shop', 'enable_comments', array(
            'get_callback' => function($post) {
                return (bool) get_post_meta($post['id'], '_enable_comments', true);
            },
            'update_callback' => function($value, $post) {
                return update_post_meta($post->ID, '_enable_comments', $value ? 1 : 0);
            },
            'schema' => array(
                'description' => 'Enable comments on story',
                'type' => 'boolean',
                'context' => array('view', 'edit')
            )
        ));

        register_rest_field('story_shop', 'enable_products', array(
            'get_callback' => function($post) {
                return (bool) get_post_meta($post['id'], '_enable_products', true);
            },
            'update_callback' => function($value, $post) {
                return update_post_meta($post->ID, '_enable_products', $value ? 1 : 0);
            },
            'schema' => array(
                'description' => 'Enable products in story',
                'type' => 'boolean',
                'context' => array('view', 'edit')
            )
        ));

        // Style fields
        $style_fields = array(
            'gradient_start' => 'Gradient start color',
            'gradient_middle' => 'Gradient middle color',
            'gradient_end' => 'Gradient end color',
            'container_width' => 'Container width',
            'container_height' => 'Container height',
            'image_width' => 'Image width',
            'image_height' => 'Image height',
            'badge_gradient_start' => 'Badge gradient start color',
            'badge_gradient_middle' => 'Badge gradient middle color',
            'badge_gradient_end' => 'Badge gradient end color',
            'badge_font_size' => 'Badge font size',
            'badge_margin_top' => 'Badge margin top',
            'badge_border_radius' => 'Badge border radius',
            'badge_padding' => 'Badge padding',
            'badge_font_weight' => 'Badge font weight'
        );

        foreach ($style_fields as $field => $description) {
            register_rest_field('story_shop', $field, array(
                'get_callback' => function($post) use ($field) {
                    return get_post_meta($post['id'], '_' . $field, true);
                },
                'update_callback' => function($value, $post) use ($field) {
                    return update_post_meta($post->ID, '_' . $field, sanitize_text_field($value));
                },
                'schema' => array(
                    'description' => $description,
                    'type' => 'string',
                    'context' => array('view', 'edit')
                )
            ));
        }

        // Media fields
        register_rest_field('story_shop', 'media_type', array(
            'get_callback' => function($post) {
                return get_post_meta($post['id'], '_media_type', true) ?: 'image';
            },
            'update_callback' => function($value, $post) {
                return update_post_meta($post->ID, '_media_type', sanitize_text_field($value));
            },
            'schema' => array(
                'description' => 'Media type (image or video)',
                'type' => 'string',
                'enum' => array('image', 'video'),
                'context' => array('view', 'edit')
            )
        ));

        register_rest_field('story_shop', 'story_image', array(
            'get_callback' => function($post) {
                $image_id = get_post_meta($post['id'], '_story_image', true);
                if ($image_id) {
                    return array(
                        'id' => (int) $image_id,
                        'url' => wp_get_attachment_url($image_id),
                        'sizes' => array(
                            'thumbnail' => wp_get_attachment_image_url($image_id, 'thumbnail'),
                            'medium' => wp_get_attachment_image_url($image_id, 'medium'),
                            'large' => wp_get_attachment_image_url($image_id, 'large'),
                            'full' => wp_get_attachment_image_url($image_id, 'full')
                        )
                    );
                }
                return null;
            },
            'update_callback' => function($value, $post) {
                return update_post_meta($post->ID, '_story_image', intval($value));
            },
            'schema' => array(
                'description' => 'Story image attachment',
                'type' => 'object',
                'context' => array('view', 'edit')
            )
        ));

        register_rest_field('story_shop', 'story_video', array(
            'get_callback' => function($post) {
                $video_id = get_post_meta($post['id'], '_story_video', true);
                if ($video_id) {
                    return array(
                        'id' => (int) $video_id,
                        'url' => wp_get_attachment_url($video_id)
                    );
                }
                return null;
            },
            'update_callback' => function($value, $post) {
                return update_post_meta($post->ID, '_story_video', intval($value));
            },
            'schema' => array(
                'description' => 'Story video attachment',
                'type' => 'object',
                'context' => array('view', 'edit')
            )
        ));

        register_rest_field('story_shop', 'story_thumbnail', array(
            'get_callback' => function($post) {
                $thumbnail_id = get_post_meta($post['id'], '_story_thumbnail', true);
                if ($thumbnail_id) {
                    return array(
                        'id' => (int) $thumbnail_id,
                        'url' => wp_get_attachment_url($thumbnail_id),
                        'sizes' => array(
                            'thumbnail' => wp_get_attachment_image_url($thumbnail_id, 'thumbnail'),
                            'medium' => wp_get_attachment_image_url($thumbnail_id, 'medium'),
                            'large' => wp_get_attachment_image_url($thumbnail_id, 'large'),
                            'full' => wp_get_attachment_image_url($thumbnail_id, 'full')
                        )
                    );
                }
                return null;
            },
            'update_callback' => function($value, $post) {
                return update_post_meta($post->ID, '_story_thumbnail', intval($value));
            },
            'schema' => array(
                'description' => 'Story custom thumbnail',
                'type' => 'object',
                'context' => array('view', 'edit')
            )
        ));

        // Attached products
        register_rest_field('story_shop', 'attached_products', array(
            'get_callback' => function($post) {
                $product_ids = get_post_meta($post['id'], '_attached_products', true);
                if (!is_array($product_ids)) {
                    return array();
                }
                
                $products = array();
                foreach ($product_ids as $product_id) {
                    $product = wc_get_product($product_id);
                    if ($product) {
                        $products[] = array(
                            'id' => $product_id,
                            'name' => $product->get_name(),
                            'price' => $product->get_price(),
                            'regular_price' => $product->get_regular_price(),
                            'sale_price' => $product->get_sale_price(),
                            'permalink' => get_permalink($product_id),
                            'image' => wp_get_attachment_image_url($product->get_image_id(), 'medium')
                        );
                    }
                }
                return $products;
            },
            'update_callback' => function($value, $post) {
                $product_ids = is_array($value) ? array_map('intval', $value) : array();
                return update_post_meta($post->ID, '_attached_products', $product_ids);
            },
            'schema' => array(
                'description' => 'Attached products',
                'type' => 'array',
                'items' => array(
                    'type' => 'object'
                ),
                'context' => array('view', 'edit')
            )
        ));
    }
}


new StoryLMMain();