<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\Request;

class ProductImportController extends Controller
{
    public function index()
    {
        $categories = Category::orderBy('name_en')->get();

        // Check for success message in query parameter
        if (request()->has('success')) {
            return redirect()->route('products.import')->with('success', request()->query('success'));
        }

        return view('products.import', compact('categories'));
    }

    public function store(Request $request)
    {
        try {
            $request->validate([
                'category_id' => 'required|exists:categories,id',
                'source' => 'required|in:aliexpress,amazon,noon',
                'products' => 'required|array',
                'products.*' => 'array',
            ]);

            $categoryId = $request->category_id;
            $source = $request->source;
            $products = $request->products;

            // Debug: Log the raw request data
            \Log::info('Raw products data received', [
                'count' => count($products),
                'first_product_raw' => $products[0] ?? null,
                'first_product_keys' => $products[0] ? array_keys($products[0]) : [],
            ]);

            $imported = 0;
            foreach ($products as $productData) {
                try {
                    // Log the first product for debugging
                    if ($imported === 0) {
                        \Log::info('First product received from Excel', [
                            'raw_data' => $productData,
                            'keys' => array_keys($productData),
                        ]);
                    }

                    // Get values with exact Excel column names (including spaces!)
                    Product::create([
                        'category_id' => $categoryId,
                        'source' => $source,
                        'product_id' => $this->getStringValue($productData['ProductId'] ?? null),
                        'image_url' => $this->getStringValue($productData['Image Url'] ?? null),
                        'video_url' => $this->getStringValue($productData['Video Url'] ?? null),
                        'name_ar' => $this->getStringValue($productData['Product Desc'] ?? null),
                        'name_en' => $this->getStringValue($productData['Product Desc'] ?? null),
                        'description_ar' => $this->getStringValue($productData['Product Desc'] ?? null),
                        'description_en' => $this->getStringValue($productData['Product Desc'] ?? null),
                        'price' => $this->getNumericValue($productData['Origin Price'] ?? null),
                        'discount_price' => $this->getNumericValue($productData['Discount Price'] ?? null),
                        'discount' => $this->getNumericValue($productData['Discount'] ?? null),
                        'currency' => $this->getStringValue($productData['Currency'] ?? 'EGP'),
                        'clicks' => 0,
                        'direct_commission_rate' => $this->getNumericValue($productData['Direct linking commission rate (%)'] ?? null),
                        'estimated_direct_commission' => $this->getNumericValue($productData['Estimated direct linking commission'] ?? null),
                        'indirect_commission_rate' => $this->getNumericValue($productData['Indirect linking commission rate (%) '] ?? null),
                        'estimated_indirect_commission' => $this->getNumericValue($productData['Estimated indirect linking commission'] ?? null),
                        'sales_180day' => $this->getIntValue($productData['Sales180Day'] ?? null),
                        'positive_feedback' => $this->getNumericValue($productData['Positive Feedback'] ?? null),
                        'promotion_url' => $this->getStringValue($productData['Promotion Url'] ?? null),
                        'code_name' => $this->getStringValue($productData['Code Name'] ?? null),
                        'code_start_time' => $this->parseDate($productData['Code Start Time'] ?? null),
                        'code_end_time' => $this->parseDate($productData['Code End Time'] ?? null),
                        'code_value' => $this->getNumericValue($productData['Code Value'] ?? null),
                        'code_quantity' => $this->getIntValue($productData['Code Quantity'] ?? null),
                        'code_minimum_spend' => $this->getNumericValue($productData['Code Minimum Spend'] ?? null),
                    ]);
                    $imported++;
                } catch (\Exception $e) {
                    // Log error for debugging
                    \Log::error('Product import error', [
                        'error' => $e->getMessage(),
                        'data' => $productData,
                    ]);

                    continue;
                }
            }

            return response()->json([
                'success' => true,
                'imported' => $imported,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    private function parseDate($date)
    {
        if (empty($date) || $date === 'NULL' || $date === 'null') {
            return null;
        }

        try {
            // Handle Excel serial dates
            if (is_numeric($date)) {
                return \Carbon\Carbon::createFromFormat('Y-m-d', '1900-01-01')
                    ->addDays($date - 2)
                    ->format('Y-m-d H:i:s');
            }

            return \Carbon\Carbon::parse($date)->format('Y-m-d H:i:s');
        } catch (\Exception $e) {
            return null;
        }
    }

    private function getStringValue($value)
    {
        if ($value === null || $value === 'NULL' || $value === 'null') {
            return null;
        }

        return (string) $value;
    }

    private function getNumericValue($value)
    {
        if ($value === null || $value === 'NULL' || $value === 'null' || $value === '') {
            return 0;
        }

        // Remove currency symbols (EGP, USD, etc.), percentage signs, and any non-numeric characters except decimal point and minus
        $cleaned = preg_replace('/[^0-9.\-]/', '', (string) $value);

        return (float) $cleaned;
    }

    private function getIntValue($value)
    {
        if ($value === null || $value === 'NULL' || $value === 'null' || $value === '') {
            return 0;
        }

        return (int) $value;
    }
}
