<?php
if (!defined('ABSPATH')) exit;

class Dima_Export {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * خروجی محصولات به CSV
     */
    public function export_products() {
        $upload_dir = wp_upload_dir();
        $export_dir = $upload_dir['basedir'] . '/dima-shop/exports/';
        
        if (!file_exists($export_dir)) {
            wp_mkdir_p($export_dir);
        }
        
        $filename = 'products-' . date('Ymd-His') . '.csv';
        $filepath = $export_dir . $filename;
        
        $products = get_posts(array(
            'post_type' => 'dima_product',
            'posts_per_page' => -1,
            'post_status' => 'any'
        ));
        
        $fp = fopen($filepath, 'w');
        
        // BOM برای UTF-8
        fprintf($fp, chr(0xEF).chr(0xBB).chr(0xBF));
        
        // هدر
        fputcsv($fp, array(
            'ID', 'عنوان', 'SKU', 'قیمت', 'موجودی', 'وزن',
            'دسته‌بندی', 'ویژگی‌ها', 'توضیح کوتاه', 'توضیحات', 'تصویر'
        ), ',');
        
        foreach ($products as $product) {
            $categories = wp_get_post_terms($product->ID, 'dima_product_cat', array('fields' => 'names'));
            $attributes = wp_get_post_terms($product->ID, 'dima_attribute', array('fields' => 'names'));
            
            fputcsv($fp, array(
                $product->ID,
                $product->post_title,
                get_post_meta($product->ID, '_dima_sku', true),
                get_post_meta($product->ID, '_dima_price', true),
                get_post_meta($product->ID, '_dima_stock', true),
                get_post_meta($product->ID, '_dima_weight', true),
                implode(' | ', $categories),
                implode(' | ', $attributes),
                $product->post_excerpt,
                wp_strip_all_tags($product->post_content),
                get_the_post_thumbnail_url($product->ID, 'full')
            ), ',');
        }
        
        fclose($fp);
        
        $file_url = $upload_dir['baseurl'] . '/dima-shop/exports/' . $filename;
        
        return array(
            'path' => $filepath,
            'url' => $file_url,
            'filename' => $filename,
            'count' => count($products)
        );
    }
    
    /**
     * ورودی محصولات از CSV
     */
    public function import_products($file_path) {
        if (!file_exists($file_path)) {
            return new WP_Error('file_not_found', 'فایل یافت نشد');
        }
        
        $fp = fopen($file_path, 'r');
        
        // رد کردن BOM
        $bom = fread($fp, 3);
        if ($bom !== chr(0xEF).chr(0xBB).chr(0xBF)) {
            rewind($fp);
        }
        
        $header = fgetcsv($fp, 0, ',');
        if (!$header) {
            fclose($fp);
            return new WP_Error('invalid_csv', 'فایل CSV نامعتبر است');
        }
        
        $imported = 0;
        $errors = array();
        
        while (($row = fgetcsv($fp, 0, ',')) !== false) {
            if (count($row) < 3) continue;
            
            $data = array_combine($header, $row);
            
            $product_id = wp_insert_post(array(
                'post_title' => $data['عنوان'] ?? '',
                'post_content' => $data['توضیحات'] ?? '',
                'post_excerpt' => $data['توضیح کوتاه'] ?? '',
                'post_status' => 'publish',
                'post_type' => 'dima_product'
            ));
            
            if (is_wp_error($product_id)) {
                $errors[] = $data['عنوان'] . ': ' . $product_id->get_error_message();
                continue;
            }
            
            update_post_meta($product_id, '_dima_sku', $data['SKU'] ?? '');
            update_post_meta($product_id, '_dima_price', floatval($data['قیمت'] ?? 0));
            update_post_meta($product_id, '_dima_stock', intval($data['موجودی'] ?? 0));
            update_post_meta($product_id, '_dima_weight', intval($data['وزن'] ?? 0));
            
            // دسته‌بندی‌ها
            if (!empty($data['دسته‌بندی'])) {
                $cats = array_map('trim', explode('|', $data['دسته‌بندی']));
                wp_set_object_terms($product_id, $cats, 'dima_product_cat');
            }
            
            $imported++;
        }
        
        fclose($fp);
        
        return array(
            'imported' => $imported,
            'errors' => $errors
        );
    }
    
    /**
     * خروجی سفارشات
     */
    public function export_orders($date_from = null, $date_to = null) {
        global $wpdb;
        
        $upload_dir = wp_upload_dir();
        $export_dir = $upload_dir['basedir'] . '/dima-shop/exports/';
        
        if (!file_exists($export_dir)) {
            wp_mkdir_p($export_dir);
        }
        
        $filename = 'orders-' . date('Ymd-His') . '.csv';
        $filepath = $export_dir . $filename;
        
        $where = "WHERE 1=1";
        if ($date_from) $where .= $wpdb->prepare(" AND created_at >= %s", $date_from);
        if ($date_to) $where .= $wpdb->prepare(" AND created_at <= %s", $date_to);
        
        $orders = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}dima_orders {$where} ORDER BY created_at DESC");
        
        $fp = fopen($filepath, 'w');
        fprintf($fp, chr(0xEF).chr(0xBB).chr(0xBF));
        
        fputcsv($fp, array('شناسه', 'کاربر', 'مبلغ کل', 'تخفیف', 'نهایی', 'وضعیت', 'درگاه', 'تاریخ', 'نام', 'موبایل', 'آدرس'), ',');
        
        foreach ($orders as $order) {
            $customer = json_decode($order->customer_data, true);
            
            fputcsv($fp, array(
                $order->id,
                $order->user_id,
                $order->total_amount,
                $order->discount_amount,
                $order->final_amount,
                $order->status,
                $order->payment_method,
                $order->created_at,
                $customer['name'] ?? '',
                $customer['phone'] ?? '',
                $customer['address'] ?? ''
            ), ',');
        }
        
        fclose($fp);
        
        return array(
            'path' => $filepath,
            'url' => $upload_dir['baseurl'] . '/dima-shop/exports/' . $filename,
            'count' => count($orders)
        );
    }
}