<?php
/**
 * کلاس REST API برای اپلیکیشن موبایل
 */
if (!defined('ABSPATH')) exit;

class Dima_Rest_API {
    
    private static $instance = null;
    private $namespace = 'dima/v1';
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        add_action('rest_api_init', array($this, 'register_routes'));
    }
    
    public function register_routes() {
        // Products
        register_rest_route($this->namespace, '/products', array(
            array(
                'methods' => 'GET',
                'callback' => array($this, 'get_products'),
                'permission_callback' => '__return_true'
            )
        ));
        
        register_rest_route($this->namespace, '/products/(?P<id>\d+)', array(
            array(
                'methods' => 'GET',
                'callback' => array($this, 'get_product'),
                'permission_callback' => '__return_true'
            )
        ));
        
        // Categories
        register_rest_route($this->namespace, '/categories', array(
            array(
                'methods' => 'GET',
                'callback' => array($this, 'get_categories'),
                'permission_callback' => '__return_true'
            )
        ));
        
        // Orders (نیاز به authentication)
        register_rest_route($this->namespace, '/orders', array(
            array(
                'methods' => 'GET',
                'callback' => array($this, 'get_orders'),
                'permission_callback' => array($this, 'check_auth')
            )
        ));
        
        // Cart
        register_rest_route($this->namespace, '/cart', array(
            array(
                'methods' => 'POST',
                'callback' => array($this, 'add_to_cart'),
                'permission_callback' => '__return_true'
            )
        ));
    }
    
    public function check_auth() {
        return is_user_logged_in() || !empty($_SERVER['HTTP_AUTHORIZATION']);
    }
    
    public function get_products($request) {
        $args = array(
            'post_type' => 'dima_product',
            'posts_per_page' => $request->get_param('per_page') ?: 10,
            'paged' => $request->get_param('page') ?: 1,
            'post_status' => 'publish'
        );
        
        $products = new WP_Query($args);
        $result = array();
        
        while ($products->have_posts()) {
            $products->the_post();
            $id = get_the_ID();
            
            $result[] = array(
                'id' => $id,
                'title' => get_the_title(),
                'slug' => get_post_field('post_name', $id),
                'price' => Dima_Product::get_price($id),
                'stock' => Dima_Product::get_stock($id),
                'sku' => Dima_Product::get_sku($id),
                'image' => get_the_post_thumbnail_url($id, 'medium'),
                'permalink' => get_permalink($id),
                'description' => get_the_excerpt(),
                'categories' => wp_get_post_terms($id, 'dima_product_cat', array('fields' => 'names')),
                'rating' => get_post_meta($id, '_dima_avg_rating', true),
                'review_count' => get_post_meta($id, '_dima_review_count', true)
            );
        }
        wp_reset_postdata();
        
        return new WP_REST_Response(array(
            'products' => $result,
            'total' => $products->found_posts,
            'pages' => $products->max_num_pages
        ), 200);
    }
    
    public function get_product($request) {
        $id = $request->get_param('id');
        $product = get_post($id);
        
        if (!$product || $product->post_type !== 'dima_product') {
            return new WP_Error('not_found', 'محصول یافت نشد', array('status' => 404));
        }
        
        return array(
            'id' => $id,
            'title' => $product->post_title,
            'content' => $product->post_content,
            'excerpt' => $product->post_excerpt,
            'price' => Dima_Product::get_price($id),
            'stock' => Dima_Product::get_stock($id),
            'sku' => Dima_Product::get_sku($id),
            'image' => get_the_post_thumbnail_url($id, 'large'),
            'categories' => wp_get_post_terms($id, 'dima_product_cat'),
            'attributes' => wp_get_post_terms($id, 'dima_attribute'),
            'rating' => get_post_meta($id, '_dima_avg_rating', true),
            'reviews' => Dima_Review::get_instance()->get_product_reviews($id, 10),
            'flash_sale' => Dima_Flash_Sale::get_instance()->get_flash_price($id)
        );
    }
    
    public function get_categories($request) {
        $terms = get_terms(array(
            'taxonomy' => 'dima_product_cat',
            'hide_empty' => false
        ));
        
        $result = array();
        foreach ($terms as $term) {
            $data = Dima_Product::get_category_data($term->term_id);
            $result[] = array(
                'id' => $term->term_id,
                'name' => $term->name,
                'slug' => $term->slug,
                'description' => $term->description,
                'count' => $term->count,
                'image' => $data['image_url'],
                'icon' => $data['icon'],
                'color' => $data['color']
            );
        }
        
        return $result;
    }
    
    public function get_orders($request) {
        $user_id = get_current_user_id();
        $orders = Dima_Checkout::get_instance()->get_customer_orders($user_id);
        
        return array('orders' => $orders);
    }
    
    public function add_to_cart($request) {
        $product_id = $request->get_param('product_id');
        $quantity = $request->get_param('quantity') ?: 1;
        
        $cart = Dima_Cart::get_instance();
        $cart->add_item($product_id, $quantity);
        
        return array(
            'success' => true,
            'cart_count' => $cart->get_item_count(),
            'cart_total' => $cart->get_total()
        );
    }
}