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

class Dima_Checkout {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * ایجاد سفارش
     */
    public function create_order($customer_data, $items, $coupon_code = null, $discount = 0) {
        global $wpdb;
        
        $cart = Dima_Cart::get_instance();
        $total = $cart->get_total();
        $final_amount = $total - $discount;
        
        if ($final_amount < 0) $final_amount = 0;
        
        $table = $wpdb->prefix . 'dima_orders';
        $result = $wpdb->insert($table, array(
            'user_id' => get_current_user_id(),
            'session_id' => session_id(),
            'total_amount' => $total,
            'discount_amount' => $discount,
            'final_amount' => $final_amount,
            'status' => 'pending',
            'payment_method' => get_option('dima_payment_gateway', 'zarinpal'),
            'coupon_code' => $coupon_code,
            'customer_data' => wp_json_encode($customer_data),
            'ip_address' => Dima_Security::get_instance()->get_client_ip(),
            'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field($_SERVER['HTTP_USER_AGENT']) : '',
            'created_at' => current_time('mysql')
        ));
        
        if (!$result) {
            return new WP_Error('order_creation_failed', 'خطا در ایجاد سفارش');
        }
        
        $order_id = $wpdb->insert_id;
        
        // ذخیره آیتم‌ها
        $items_table = $wpdb->prefix . 'dima_order_items';
        foreach ($items as $item) {
            $wpdb->insert($items_table, array(
                'order_id' => $order_id,
                'product_id' => intval($item['product_id']),
                'quantity' => intval($item['quantity']),
                'price' => floatval($item['price'])
            ));
            
            // افزایش شمارنده فروش
            Dima_Product::increment_sales($item['product_id'], $item['quantity']);
        }
        
        // افزایش استفاده کوپن
        if ($coupon_code) {
            $coupon = Dima_Coupon::get_instance();
            $coupon_data = $wpdb->get_row($wpdb->prepare(
                "SELECT id FROM {$wpdb->prefix}dima_coupons WHERE code = %s",
                $coupon_code
            ));
            if ($coupon_data) {
                $coupon->increment_usage($coupon_data->id);
            }
        }
        
        // هوک
        do_action('dima_after_order_created', $order_id, get_current_user_id());
        
        return $order_id;
    }
    
    /**
     * دریافت سفارش
     */
    public function get_order($order_id) {
        global $wpdb;
        $table = $wpdb->prefix . 'dima_orders';
        return $wpdb->get_row($wpdb->prepare("SELECT * FROM $table WHERE id = %d", $order_id));
    }
    
    /**
     * دریافت آیتم‌های سفارش
     */
    public function get_order_items($order_id) {
        global $wpdb;
        $table = $wpdb->prefix . 'dima_order_items';
        return $wpdb->get_results($wpdb->prepare("SELECT * FROM $table WHERE order_id = %d", $order_id));
    }
    
    /**
     * بروزرسانی وضعیت سفارش
     */
    public function update_order_status($order_id, $status) {
        global $wpdb;
        $table = $wpdb->prefix . 'dima_orders';
        
        $old_order = $this->get_order($order_id);
        if (!$old_order) return false;
        
        $result = $wpdb->update($table, array('status' => $status), array('id' => $order_id));
        
        // اگر وضعیت به completed تغییر کرد
        if ($status === 'completed' && $old_order->status !== 'completed') {
            do_action('dima_after_order_completed', $order_id, $old_order->user_id);
        }
        
        return $result;
    }
    
    /**
     * سفارشات کاربر
     */
    public function get_customer_orders($user_id = null) {
        global $wpdb;
        
        if (null === $user_id) {
            $user_id = get_current_user_id();
        }
        
        $table = $wpdb->prefix . 'dima_orders';
        return $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM $table WHERE user_id = %d ORDER BY created_at DESC",
            $user_id
        ));
    }
    
    /**
     * دریافت آخرین سفارش کاربر
     */
    public function get_last_order($user_id = null) {
        global $wpdb;
        
        if (null === $user_id) {
            $user_id = get_current_user_id();
        }
        
        $table = $wpdb->prefix . 'dima_orders';
        return $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $table WHERE user_id = %d ORDER BY created_at DESC LIMIT 1",
            $user_id
        ));
    }
    
    /**
     * بررسی اینکه آیا کاربر این محصول را خریده
     */
    public function has_purchased($user_id, $product_id) {
        global $wpdb;
        
        $items_table = $wpdb->prefix . 'dima_order_items';
        $orders_table = $wpdb->prefix . 'dima_orders';
        
        $count = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$items_table} i 
             INNER JOIN {$orders_table} o ON i.order_id = o.id 
             WHERE i.product_id = %d AND o.user_id = %d AND o.status = 'completed'",
            $product_id, $user_id
        ));
        
        return $count > 0;
    }
    
    /**
     * محاسبه آمار کلی
     */
    public function get_stats() {
        global $wpdb;
        $table = $wpdb->prefix . 'dima_orders';
        
        $total_orders = $wpdb->get_var("SELECT COUNT(*) FROM $table");
        $total_revenue = $wpdb->get_var("SELECT SUM(final_amount) FROM $table WHERE status = 'completed'");
        $pending_orders = $wpdb->get_var("SELECT COUNT(*) FROM $table WHERE status = 'pending'");
        
        return array(
            'total_orders' => intval($total_orders),
            'total_revenue' => floatval($total_revenue),
            'pending_orders' => intval($pending_orders)
        );
    }
}