<?php
/**
 * Import/Export Class
 * Handles product import/export (CSV/Excel)
 */

require_once __DIR__ . '/Database.php';
require_once __DIR__ . '/Product.php';

class ImportExport {
    private $db;
    private $product;

    public function __construct() {
        $this->db = Database::getInstance();
        $this->product = new Product();
    }

    /**
     * Export products to CSV
     */
    public function exportProductsToCSV($filters = []) {
        $products = $this->product->getProducts($filters);
        
        $filename = 'products_export_' . date('Y-m-d_His') . '.csv';
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');

        $output = fopen('php://output', 'w');
        
        // Headers
        fputcsv($output, [
            'ID', 'SKU', 'Name', 'Slug', 'Description', 'Short Description',
            'Price', 'Sale Price', 'Stock Quantity', 'Category ID', 'Category Name',
            'Supplier ID', 'Image', 'Is Gift', 'Is Active'
        ]);

        // Data
        foreach ($products as $product) {
            fputcsv($output, [
                $product['id'],
                $product['sku'],
                $product['name'],
                $product['slug'],
                $product['description'],
                $product['short_description'],
                $product['price'],
                $product['sale_price'],
                $product['stock_quantity'],
                $product['category_id'],
                $product['category_name'] ?? '',
                $product['supplier_id'],
                $product['image'],
                $product['is_gift'] ? '1' : '0',
                $product['is_active'] ? '1' : '0'
            ]);
        }

        fclose($output);
        exit;
    }

    /**
     * Import products from CSV
     */
    public function importProductsFromCSV($filePath, $adminId = null) {
        $errors = [];
        $successCount = 0;
        $errorCount = 0;
        $recordsCount = 0;

        if (($handle = fopen($filePath, 'r')) !== false) {
            // Skip header row
            $header = fgetcsv($handle);

            while (($data = fgetcsv($handle)) !== false) {
                $recordsCount++;
                
                try {
                    // Map CSV columns to product data
                    $productData = [
                        'sku' => $data[1] ?? '',
                        'name' => $data[2] ?? '',
                        'slug' => $data[3] ?? $this->generateSlug($data[2] ?? ''),
                        'description' => $data[4] ?? '',
                        'short_description' => $data[5] ?? '',
                        'price' => floatval($data[6] ?? 0),
                        'sale_price' => !empty($data[7]) ? floatval($data[7]) : null,
                        'stock_quantity' => intval($data[8] ?? 0),
                        'category_id' => !empty($data[9]) ? intval($data[9]) : null,
                        'supplier_id' => !empty($data[11]) ? intval($data[11]) : null,
                        'image' => $data[12] ?? null,
                        'is_gift' => isset($data[13]) && $data[13] == '1' ? 1 : 0,
                        'is_active' => isset($data[14]) && $data[14] == '1' ? 1 : 0
                    ];

                    // Validate required fields
                    if (empty($productData['name']) || empty($productData['price'])) {
                        throw new Exception("Row {$recordsCount}: Missing required fields (name or price)");
                    }

                    // Check if product exists (by SKU or slug)
                    $existing = null;
                    if (!empty($productData['sku'])) {
                        $existing = $this->db->fetchOne(
                            "SELECT id FROM products WHERE sku = ?",
                            [$productData['sku']]
                        );
                    }
                    
                    if (!$existing && !empty($productData['slug'])) {
                        $existing = $this->db->fetchOne(
                            "SELECT id FROM products WHERE slug = ?",
                            [$productData['slug']]
                        );
                    }

                    if ($existing) {
                        // Update existing product
                        $this->db->execute(
                            "UPDATE products SET 
                                name = ?, slug = ?, description = ?, short_description = ?,
                                price = ?, sale_price = ?, stock_quantity = ?, category_id = ?,
                                supplier_id = ?, image = ?, is_gift = ?, is_active = ?,
                                updated_at = NOW()
                             WHERE id = ?",
                            [
                                $productData['name'],
                                $productData['slug'],
                                $productData['description'],
                                $productData['short_description'],
                                $productData['price'],
                                $productData['sale_price'],
                                $productData['stock_quantity'],
                                $productData['category_id'],
                                $productData['supplier_id'],
                                $productData['image'],
                                $productData['is_gift'],
                                $productData['is_active'],
                                $existing['id']
                            ]
                        );
                    } else {
                        // Insert new product
                        $this->db->execute(
                            "INSERT INTO products (sku, name, slug, description, short_description,
                                                   price, sale_price, stock_quantity, category_id,
                                                   supplier_id, image, is_gift, is_active)
                             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                            [
                                $productData['sku'],
                                $productData['name'],
                                $productData['slug'],
                                $productData['description'],
                                $productData['short_description'],
                                $productData['price'],
                                $productData['sale_price'],
                                $productData['stock_quantity'],
                                $productData['category_id'],
                                $productData['supplier_id'],
                                $productData['image'],
                                $productData['is_gift'],
                                $productData['is_active']
                            ]
                        );
                    }

                    $successCount++;
                } catch (Exception $e) {
                    $errorCount++;
                    $errors[] = "Row {$recordsCount}: " . $e->getMessage();
                }
            }

            fclose($handle);
        }

        // Log import
        $this->db->execute(
            "INSERT INTO import_export_logs (type, file_name, records_count, success_count, error_count, errors, admin_id)
             VALUES ('import', ?, ?, ?, ?, ?, ?)",
            [
                basename($filePath),
                $recordsCount,
                $successCount,
                $errorCount,
                !empty($errors) ? json_encode($errors) : null,
                $adminId
            ]
        );

        return [
            'success' => true,
            'records_count' => $recordsCount,
            'success_count' => $successCount,
            'error_count' => $errorCount,
            'errors' => $errors
        ];
    }

    /**
     * Generate slug from name
     */
    private function generateSlug($name) {
        $slug = strtolower(trim($name));
        $slug = preg_replace('/[^a-z0-9-]/', '-', $slug);
        $slug = preg_replace('/-+/', '-', $slug);
        $slug = trim($slug, '-');
        
        // Ensure uniqueness
        $baseSlug = $slug;
        $counter = 1;
        while ($this->db->fetchOne("SELECT id FROM products WHERE slug = ?", [$slug])) {
            $slug = $baseSlug . '-' . $counter;
            $counter++;
        }
        
        return $slug;
    }

    /**
     * Get import/export logs
     */
    public function getLogs($type = null, $limit = 50) {
        $sql = "SELECT * FROM import_export_logs WHERE 1=1";
        $params = [];

        if ($type) {
            $sql .= " AND type = ?";
            $params[] = $type;
        }

        $sql .= " ORDER BY created_at DESC LIMIT ?";
        $params[] = $limit;

        return $this->db->fetchAll($sql, $params);
    }
}
?>

