<?php
/**
 * کلاس نظرات و امتیازدهی
 */
if (!defined('ABSPATH')) exit;

class Dima_Review {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        add_action('dima_after_order_completed', array($this, 'request_review_email'), 10, 2);
    }
    
    /**
     * افزودن نظر
     */
    public function add_review($product_id, $rating, $title, $content) {
        global $wpdb;
        
        $product_id = absint($product_id);
        $rating = max(1, min(5, absint($rating)));
        
        if ($product_id <= 0) {
            return new WP_Error('invalid_product', 'محصول نامعتبر است');
        }
        
        if (strlen($content) < 10) {
            return new WP_Error('short_content', 'نظر باید حداقل ۱۰ کاراکتر باشد');
        }
        
        // بررسی خرید واقعی
        $verified = 0;
        $user_id = get_current_user_id();
        
        if ($user_id > 0) {
            $checkout = Dima_Checkout::get_instance();
            $verified = $checkout->has_purchased($user_id, $product_id) ? 1 : 0;
        }
        
        $user = wp_get_current_user();
        $author_name = $user->ID > 0 ? $user->display_name : (isset($_POST['author_name']) ? sanitize_text_field($_POST['author_name']) : 'مهمان');
        $author_email = $user->ID > 0 ? $user->user_email : (isset($_POST['author_email']) ? sanitize_email($_POST['author_email']) : '');
        
        $result = $wpdb->insert($wpdb->prefix . 'dima_reviews', array(
            'product_id' => $product_id,
            'user_id' => $user_id,
            'author_name' => $author_name,
            'author_email' => $author_email,
            'rating' => $rating,
            'title' => sanitize_text_field($title),
            'content' => sanitize_textarea_field($content),
            'status' => 'pending',
            'verified_purchase' => $verified,
            'created_at' => current_time('mysql')
        ));
        
        if (!$result) {
            return new WP_Error('db_error', 'خطا در ذخیره نظر');
        }
        
        $this->update_product_rating($product_id);
        
        do_action('dima_after_review_submitted', $wpdb->insert_id, $user_id);
        
        return $wpdb->insert_id;
    }
    
    /**
     * بروزرسانی میانگین امتیاز
     */
    private function update_product_rating($product_id) {
        global $wpdb;
        
        $stats = $wpdb->get_row($wpdb->prepare(
            "SELECT AVG(rating) as avg_rating, COUNT(*) as review_count 
             FROM {$wpdb->prefix}dima_reviews 
             WHERE product_id = %d AND status = 'approved'",
            $product_id
        ));
        
        update_post_meta($product_id, '_dima_avg_rating', $stats ? round($stats->avg_rating, 1) : 0);
        update_post_meta($product_id, '_dima_review_count', $stats ? intval($stats->review_count) : 0);
    }
    
    /**
     * دریافت نظرات محصول
     */
    public function get_product_reviews($product_id, $limit = 10, $offset = 0) {
        global $wpdb;
        
        return $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}dima_reviews 
             WHERE product_id = %d AND status = 'approved' 
             ORDER BY created_at DESC 
             LIMIT %d OFFSET %d",
            $product_id, $limit, $offset
        ));
    }
    
    /**
     * تایید نظر
     */
    public function approve_review($review_id) {
        global $wpdb;
        
        $wpdb->update(
            $wpdb->prefix . 'dima_reviews',
            array('status' => 'approved'),
            array('id' => absint($review_id))
        );
        
        $review = $wpdb->get_row($wpdb->prepare(
            "SELECT product_id, user_id FROM {$wpdb->prefix}dima_reviews WHERE id = %d",
            $review_id
        ));
        
        if ($review) {
            $this->update_product_rating($review->product_id);
            do_action('dima_after_review_approved', $review_id, $review->user_id);
        }
    }
    
    /**
     * رد نظر
     */
    public function reject_review($review_id) {
        global $wpdb;
        
        $wpdb->update(
            $wpdb->prefix . 'dima_reviews',
            array('status' => 'rejected'),
            array('id' => absint($review_id))
        );
    }
    
    /**
     * حذف نظر
     */
    public function delete_review($review_id) {
        global $wpdb;
        
        $review = $wpdb->get_row($wpdb->prepare(
            "SELECT product_id FROM {$wpdb->prefix}dima_reviews WHERE id = %d",
            $review_id
        ));
        
        $wpdb->delete($wpdb->prefix . 'dima_reviews', array('id' => absint($review_id)));
        
        if ($review) {
            $this->update_product_rating($review->product_id);
        }
    }
    
    /**
     * دریافت تمام نظرات (برای ادمین)
     */
    public function get_all_reviews($status = null, $limit = 50) {
        global $wpdb;
        
        $where = $status ? $wpdb->prepare("WHERE status = %s", $status) : '';
        
        return $wpdb->get_results("
            SELECT r.*, p.post_title as product_title 
            FROM {$wpdb->prefix}dima_reviews r
            LEFT JOIN {$wpdb->posts} p ON r.product_id = p.ID
            $where
            ORDER BY r.created_at DESC 
            LIMIT $limit
        ");
    }
    
    /**
     * ارسال ایمیل درخواست نظر
     */
    public function request_review_email($order_id, $user_id) {
        if (!get_option('dima_notification_email')) return;
        
        $user = get_user_by('id', $user_id);
        if (!$user) return;
        
        $items = Dima_Checkout::get_instance()->get_order_items($order_id);
        
        foreach ($items as $item) {
            $review_url = add_query_arg('review_product', $item->product_id, get_permalink($item->product_id));
            
            Dima_Notification::get_instance()->send_email(
                $user->user_email,
                'نظر خود را درباره خریدتان ثبت کنید',
                "سلام {$user->display_name} عزیز،\n\nامیدواریم از خریدتان راضی بوده باشید. لطفاً نظر خود را درباره محصول ثبت کنید:\n\n{$review_url}"
            );
        }
    }
}