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

class Dima_Reward {
    
    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, 'award_points_for_purchase'), 10, 2);
        add_action('dima_after_review_approved', array($this, 'award_points_for_review'), 10, 2);
    }
    
    /**
     * اعطای امتیاز برای خرید
     */
    public function award_points_for_purchase($order_id, $user_id) {
        if ($user_id <= 0) return;
        
        $points_per_purchase = intval(get_option('dima_rewards_per_purchase', 100));
        $order = Dima_Checkout::get_instance()->get_order($order_id);
        
        if (!$order) return;
        
        $points = intval($order->final_amount / 10000) * $points_per_purchase;
        
        if ($points > 0) {
            $this->add_points($user_id, $points, 'purchase', $order_id, "امتیاز خرید سفارش #{$order_id}");
            
            global $wpdb;
            $wpdb->update(
                $wpdb->prefix . 'dima_orders',
                array('reward_points_earned' => $points),
                array('id' => $order_id)
            );
        }
    }
    
    /**
     * اعطای امتیاز برای ثبت نظر
     */
    public function award_points_for_review($review_id, $user_id) {
        if ($user_id <= 0) return;
        
        $this->add_points($user_id, 50, 'review', $review_id, 'امتیاز ثبت نظر');
    }
    
    /**
     * افزودن امتیاز
     */
    public function add_points($user_id, $points, $type, $reference_id = null, $description = '') {
        global $wpdb;
        
        return $wpdb->insert($wpdb->prefix . 'dima_reward_points', array(
            'user_id' => absint($user_id),
            'points' => intval($points),
            'type' => sanitize_text_field($type),
            'reference_id' => $reference_id ? absint($reference_id) : null,
            'description' => sanitize_text_field($description),
            'created_at' => current_time('mysql')
        ));
    }
    
    /**
     * دریافت مجموع امتیازات کاربر
     */
    public function get_user_points($user_id) {
        global $wpdb;
        
        $total = $wpdb->get_var($wpdb->prepare(
            "SELECT SUM(points) FROM {$wpdb->prefix}dima_reward_points WHERE user_id = %d",
            $user_id
        ));
        
        return intval($total);
    }
    
    /**
     * تاریخچه امتیازات
     */
    public function get_user_history($user_id, $limit = 20) {
        global $wpdb;
        
        return $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}dima_reward_points 
             WHERE user_id = %d 
             ORDER BY created_at DESC 
             LIMIT %d",
            $user_id, $limit
        ));
    }
    
    /**
     * تبدیل امتیاز به کوپن
     */
    public function redeem_points($user_id, $points) {
        $current_points = $this->get_user_points($user_id);
        
        if ($points > $current_points) {
            return new WP_Error('insufficient_points', 'امتیاز کافی نیست');
        }
        
        $min_points = 1000;
        if ($points < $min_points) {
            return new WP_Error('min_points', "حداقل {$min_points} امتیاز نیاز است");
        }
        
        $reward_value = intval(get_option('dima_reward_value', 1000));
        $discount = ($points / $min_points) * $reward_value;
        
        // ایجاد کوپن
        global $wpdb;
        $coupon_code = 'REWARD-' . strtoupper(wp_generate_password(8, false));
        
        $wpdb->insert($wpdb->prefix . 'dima_coupons', array(
            'code' => $coupon_code,
            'type' => 'fixed',
            'value' => $discount,
            'min_amount' => 0,
            'max_uses' => 1,
            'status' => 'active',
            'created_at' => current_time('mysql')
        ));
        
        // کسر امتیاز
        $this->add_points($user_id, -$points, 'redeem', null, "تبدیل {$points} امتیاز به کوپن {$coupon_code}");
        
        return array(
            'coupon_code' => $coupon_code,
            'discount' => $discount,
            'remaining_points' => $this->get_user_points($user_id)
        );
    }
}