<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class DataManagementController extends Controller
{
    /**
     * Import data from external source.
     */
    public function import(Request $request)
    {
        $request->validate([
            'data' => 'required|array',
            'type' => 'required|string|in:pages,products,customers,orders',
        ]);

        $user = $request->user();
        $imported = 0;
        $errors = [];

        try {
            switch ($request->type) {
                case 'pages':
                    foreach ($request->data as $pageData) {
                        try {
                            $page = $user->pages()->create([
                                'name' => $pageData['name'] ?? 'Imported Page',
                            ]);

                            if (isset($pageData['blocks'])) {
                                foreach ($pageData['blocks'] as $blockData) {
                                    $page->blocks()->create([
                                        'type' => $blockData['type'],
                                        'props' => $blockData['props'],
                                        'order' => $blockData['order'] ?? 0,
                                    ]);
                                }
                            }

                            $imported++;
                        } catch (\Exception $e) {
                            $errors[] = "Failed to import page: " . ($pageData['name'] ?? 'Unknown');
                        }
                    }
                    break;

                case 'products':
                    foreach ($request->data as $productData) {
                        try {
                            $user->products()->create([
                                'name' => $productData['name'],
                                'price' => $productData['price'],
                                'sku' => $productData['sku'] ?? null,
                                'category' => $productData['category'] ?? null,
                                'image_url' => $productData['image_url'] ?? null,
                                'stock' => $productData['stock'] ?? 0,
                            ]);
                            $imported++;
                        } catch (\Exception $e) {
                            $errors[] = "Failed to import product: " . ($productData['name'] ?? 'Unknown');
                        }
                    }
                    break;

                case 'customers':
                    foreach ($request->data as $customerData) {
                        try {
                            $user->customers()->create([
                                'name' => $customerData['name'],
                                'phone' => $customerData['phone'] ?? null,
                                'email' => $customerData['email'] ?? null,
                                'notes' => $customerData['notes'] ?? null,
                            ]);
                            $imported++;
                        } catch (\Exception $e) {
                            $errors[] = "Failed to import customer: " . ($customerData['name'] ?? 'Unknown');
                        }
                    }
                    break;

                case 'orders':
                    foreach ($request->data as $orderData) {
                        try {
                            $order = $user->orders()->create([
                                'customer_id' => $orderData['customer_id'],
                                'total' => $orderData['total'],
                                'status' => $orderData['status'] ?? 'Pending',
                                'payment_method' => $orderData['payment_method'],
                                'date' => $orderData['date'],
                            ]);

                            if (isset($orderData['products'])) {
                                foreach ($orderData['products'] as $productData) {
                                    $order->products()->attach($productData['product_id'], [
                                        'quantity' => $productData['quantity'],
                                        'price_at_time_of_purchase' => $productData['price_at_time_of_purchase'],
                                    ]);
                                }
                            }

                            $imported++;
                        } catch (\Exception $e) {
                            $errors[] = "Failed to import order: " . ($orderData['id'] ?? 'Unknown');
                        }
                    }
                    break;
            }

            return response()->json([
                'message' => "Successfully imported {$imported} items",
                'imported' => $imported,
                'errors' => $errors,
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'error' => 'Import failed',
                'message' => $e->getMessage(),
            ], 500);
        }
    }
}
