<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Exception;

class ProductController extends Controller
{
    /**
     * Display the main upload view.
     */
    public function index()
    {
        return view('welcome');
    }

    /**
     * Handle the file upload and process it with Gemini to extract product data.
     */
    public function upload(Request $request)
    {
        // ... existing upload method ...
        // 1. Validate the incoming request
        $validator = Validator::make($request->all(), [
            'document' => 'required|file|mimes:jpg,jpeg,png,pdf|max:10240', // Max 10MB
        ]);

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()->first()], 422);
        }

        $file = $request->file('document');
        $mimeType = $file->getMimeType();
        $fileContents = base64_encode($file->get());

        // 2. Prepare a simplified prompt for Gemini API (no image retrieval)
        $systemPrompt = "You are an expert data extraction assistant for an e-commerce platform.
        Your task is to analyze the provided document and extract product information.
        The products you find should be returned as a JSON array.
        Each object in the array must contain 'product_name', 'product_description', 'category', 'brand', 'normal_price', and 'warranty'.
        Include 'sale_price' if it is mentioned, otherwise set it to null.
        Ensure the output is ONLY the raw JSON array, without any markdown formatting or extra text.";

        try {
            // 3. Call Gemini API
            $apiKey = config('services.gemini.api_key');
            if (empty($apiKey)) {
                 return response()->json(['error' => 'Gemini API key is not configured. Please check your .env file.'], 500);
            }
            $apiUrl = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-05-20:generateContent?key={$apiKey}";

            $payload = [
                'contents' => [
                    [
                        'parts' => [
                            ['text' => 'Extract product details from this document.'],
                            [
                                'inlineData' => [
                                    'mimeType' => $mimeType,
                                    'data' => $fileContents
                                ]
                            ]
                        ]
                    ]
                ],
                'systemInstruction' => [ 'parts' => [ ['text' => $systemPrompt] ] ],
            ];

            $response = Http::timeout(120)->post($apiUrl, $payload);

            if ($response->failed()) {
                Log::error('Gemini API request failed', ['status' => $response->status(), 'response' => $response->body()]);
                return response()->json(['error' => 'Failed to analyze the document with AI. Status: ' . $response->status()], 500);
            }
            
            $resultText = $response->json('candidates.0.content.parts.0.text', '');
            $jsonText = preg_replace('/^```json\s*|\s*```$/', '', $resultText);
            $products = json_decode($jsonText, true);

            if (json_last_error() !== JSON_ERROR_NONE) {
                 Log::error('Failed to decode JSON from Gemini', ['response' => $resultText]);
                return response()->json(['error' => 'Could not parse the extracted product data.'], 500);
            }

            // Add a default placeholder image URL to each product since we are not fetching one.
            foreach ($products as &$product) {
                 $product['image_url'] = "https://placehold.co/500x500/ffffff/cccccc?text=Upload+Image";
            }

            return response()->json($products);

        } catch (Exception $e) {
            Log::error('Error in upload process', ['message' => $e->getMessage()]);
            return response()->json(['error' => 'An unexpected error occurred.'], 500);
        }
    }

    /**
     * Approves a product, handles image upload, and sends it to WooCommerce.
     */
    public function approve(Request $request)
    {
        Log::info('Product approval request received', $request->all());
        $imageId = null;
        
        // Get WooCommerce credentials from config
        $wooCommerceUrl = config('services.woocommerce.url');
        $consumerKey = config('services.woocommerce.key');
        $consumerSecret = config('services.woocommerce.secret');
        $wpApiUrl = config('services.woocommerce.wp_api_url');

        // Validate that credentials are set
        if (empty($wooCommerceUrl) || empty($consumerKey) || empty($consumerSecret) || empty($wpApiUrl)) {
            Log::error('WooCommerce/WordPress API credentials are not fully configured in .env file.');
            return response()->json(['error' => 'Server integration is not fully configured. Please check API credentials.'], 500);
        }

        // Handle the uploaded and resized image data by uploading it to WordPress Media Library
        if ($request->has('image_data') && Str::startsWith($request->input('image_data'), 'data:image')) {
            try {
                // *** DEBUGGING: Log the exact URL being used for the media upload ***
                Log::info('Attempting to upload image to WordPress Media API at URL: ' . $wpApiUrl);

                $imageData = $request->input('image_data');
                $productName = $request->input('product_name', 'product');
                $slug = Str::slug($productName);
                $fileName = $slug . '-' . time() . '.jpg';
                
                @list($type, $fileData) = explode(';', $imageData);
                @list(, $fileData) = explode(',', $fileData);
                
                // Upload image directly to WordPress Media API
                $mediaResponse = Http::withBasicAuth($consumerKey, $consumerSecret)
                    ->withHeaders([
                        'Content-Type' => 'image/jpeg',
                        'Content-Disposition' => 'attachment; filename="' . $fileName . '"'
                    ])
                    ->withBody(base64_decode($fileData), 'image/jpeg')
                    ->post($wpApiUrl);

                if ($mediaResponse->successful()) {
                    $imageId = $mediaResponse->json('id');
                    Log::info('Image uploaded to WP Media Library successfully.', ['id' => $imageId]);
                } else {
                    $errorBody = $mediaResponse->json();
                    $errorMessage = $errorBody['message'] ?? 'Please check permissions or file type.';
                    Log::error('Failed to upload image to WP Media Library', [
                        'status' => $mediaResponse->status(),
                        'response' => $mediaResponse->body()
                    ]);
                    return response()->json(['error' => 'Failed to upload image to store: ' . $errorMessage], 500);
                }

            } catch (Exception $e) {
                 Log::error('Error during image upload to WordPress', ['message' => $e->getMessage()]);
                 $detailedError = 'An unexpected error occurred during image upload. ' . $e->getMessage();
                 return response()->json(['error' => $detailedError], 500);
            }
        }

        $productData = [
            'name' => $request->input('product_name'),
            'type' => 'simple',
            'regular_price' => (string) $request->input('normal_price'),
            'description' => $request->input('product_description'),
            'categories' => [
                ['name' => $request->input('category')]
            ],
            'images' => [] // Start with empty images array
        ];

        if ($imageId) {
            $productData['images'][] = ['id' => $imageId];
        } else {
            // Fallback for placeholder image if no new image was uploaded
            $productData['images'][] = ['src' => $request->input('image_url')];
        }
        
        if($request->input('sale_price')) {
            $productData['sale_price'] = (string) $request->input('sale_price');
        }

        try {
            // *** DEBUGGING: Log the exact URL being used for the product creation ***
            Log::info('Attempting to create product via WooCommerce API at URL: ' . $wooCommerceUrl);

            // Make the actual API call to WooCommerce to create the product
            $response = Http::withBasicAuth($consumerKey, $consumerSecret)
                            ->timeout(60)
                            ->post($wooCommerceUrl, $productData);

            if ($response->successful()) {
                Log::info('Successfully uploaded product to WooCommerce', ['product' => $productData, 'response' => $response->json()]);
                return response()->json(['message' => 'Product approved and sent to WooCommerce successfully!']);
            } else {
                $wooError = $response->json();
                $errorMessage = 'Failed to create product. Status: ' . $response->status();
                if (isset($wooError['message'])) {
                    $errorMessage .= ' - ' . $wooError['message'];
                }
                
                Log::error('Failed to upload product to WooCommerce', [
                    'status' => $response->status(),
                    'response' => $response->body(),
                    'sent_data' => $productData
                ]);
                return response()->json(['error' => $errorMessage], 500);
            }

        } catch (Exception $e) {
            Log::error('Error during WooCommerce product creation', ['message' => $e->getMessage()]);
            $detailedError = 'An unexpected error occurred. ' . $e->getMessage();
            return response()->json(['error' => $detailedError], 500);
        }
    }
}
```

### What to Do Next

1.  **Clear your cache:** Run `php artisan config:clear` in your terminal one more time to be absolutely sure you're not using old settings.
2.  **Try the approval again:** Click the "Approve" button to trigger the error.
3.  **Check your logs:** Open the file `storage/logs/laravel.log`. At the bottom, you will now see new lines that look like this:
    ```
    [2025-09-28 11:35:00] local.INFO: Attempting to upload image to WordPress Media API at URL: https://your-store.com/wp-json/wp/v2/media
    [2025-09-28 11:35:00] local.INFO: Attempting to create product via WooCommerce API at URL: https://your-store.com/wp-json/wc/v3/products
    

