<?php

namespace App\Http\Controllers\Seller;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Traits\ImageUploadTrait;
use Illuminate\Support\Facades\Storage;

use App\Models\Setting;

class ProductController extends Controller
{
    use ImageUploadTrait;

    public function index()
    {
        $seller = Auth::user()->seller;
        $products = $seller->products()->latest()->paginate(10);
        
        // Calculate product limit for display
        if ($seller->hasActiveSubscription() && $seller->plan) {
            $productLimit = $seller->plan->product_limit ?? 10;
            $planName = $seller->plan->name ?? 'Premium';
        } else {
            $productLimit = 3; // Free seller limit
            $planName = 'Free';
        }
        $productCount = $seller->products()->count();
        $canAddMore = $productCount < $productLimit;
        
        return view('seller.products.index', compact('products', 'productLimit', 'productCount', 'planName', 'canAddMore'));
    }

    public function create()
    {
        $seller = Auth::user()->seller;
        $categories = Category::all();
        $minMoq = Setting::getValue('registration_moq_min', 1);
        $maxMoq = Setting::getValue('registration_moq_max', 10000);
        
        // Determine image limit based on subscription
        $imageLimit = ($seller->hasActiveSubscription() && $seller->plan) 
            ? ($seller->plan->product_image_limit ?? 5) 
            : 4; // Free sellers: 4 images per product

        return view('seller.products.create', compact('categories', 'minMoq', 'maxMoq', 'imageLimit'));
    }

    public function store(Request $request)
    {
        $seller = Auth::user()->seller;
        
        // Plan Limit Check - Free sellers get 3 products max
        $currentProductCount = $seller->products()->count();
        
        // Determine product limit based on subscription status
        if ($seller->hasActiveSubscription() && $seller->plan) {
            $planLimit = $seller->plan->product_limit ?? 10; // Default 10 for paid plans
        } else {
            $planLimit = 3; // FREE sellers: max 3 products
        }
        
        $imageLimit = ($seller->hasActiveSubscription() && $seller->plan) 
            ? ($seller->plan->product_image_limit ?? 5) 
            : 4; // Free sellers: 4 images per product

        if ($currentProductCount >= $planLimit) {
            $message = $seller->hasActiveSubscription() 
                ? 'You have reached your plan\'s product limit. Please upgrade to add more products.'
                : 'Free sellers can add only 3 products. Please subscribe to add more products.';
            return redirect()->back()->with('error', $message);
        }

        $minMoq = Setting::getValue('registration_moq_min', 1);
        $maxMoq = Setting::getValue('registration_moq_max', 10000);

        $request->validate([
            'name' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'description' => 'required|string',
            'price' => 'required|numeric|min:0',
            'currency' => 'required|in:INR,USD',
            'stock' => 'required|integer|min:0',
            'stock' => 'required|integer|min:0',
            'moq' => "required|integer|between:$minMoq,$maxMoq",
            'images' => 'required|array|min:1|max:' . $imageLimit,
            'images.*' => 'image|mimes:jpeg,png,jpg,gif,webp|max:2048',
            'specifications' => 'nullable|array',
            'specifications.*.key' => 'nullable|string|max:255',
            'specifications.*.value' => 'nullable|string|max:255',
        ]);

        $imagesJson = [];

        \Illuminate\Support\Facades\Log::info('Store Product Request Data:', $request->all());
        \Illuminate\Support\Facades\Log::info('Has Images:', ['has_file' => $request->hasFile('images')]);

        if ($request->hasFile('images')) {
            foreach ($request->file('images') as $image) {
                \Illuminate\Support\Facades\Log::info('Processing Image:', ['original_name' => $image->getClientOriginalName()]);
                // Upload Original
                $originalPath = $this->uploadImage($image, 'products');
                
                // Upload Thumbnail (300x300)
                $thumbnailPath = $this->uploadImage($image, 'products/thumbnails', 300, 300);

                $imagesJson[] = [
                    'original' => $originalPath,
                    'thumbnail' => $thumbnailPath,
                ];
            }
        }

        // Process Specifications
        $specifications = [];
        if ($request->has('specifications')) {
            foreach ($request->specifications as $spec) {
                if (!empty($spec['key']) && !empty($spec['value'])) {
                    $specifications[$spec['key']] = $spec['value'];
                }
            }
        }

        $product = Product::create([
            'seller_id' => $seller->id,
            'category_id' => $request->category_id,
            'name' => $request->name,
            'description' => $request->description,
            'price' => $request->price,
            'currency' => $request->currency,
            'stock' => $request->stock,
            'moq' => $request->moq,
            'images_json' => $imagesJson,
            'specifications' => $specifications,
            'plan_limit' => $planLimit,
            'is_approved' => false, // Pending admin approval
        ]);

        // Notify admin about new product for approval (optional - if admin email template exists)
        try {
            $adminEmail = Setting::getValue('admin_email', 'admin@theminiport.com');
            \App\Services\EmailService::send('new-product-approval', $adminEmail, [
                'product_name' => $product->name,
                'seller_name' => $seller->company_name,
                'product_url' => route('admin.products.edit', $product->id),
            ]);
        } catch (\Exception $e) {
            // Silent fail - don't block product creation
        }

        return redirect()->route('seller.products.index')
            ->with('success', 'Product submitted successfully! It will be visible to buyers once approved by admin.');
    }

    public function show(Product $product)
    {
        $this->authorizeProduct($product);
        return view('seller.products.show', compact('product'));
    }

    public function edit(Product $product)
    {
        $this->authorizeProduct($product);
        $seller = Auth::user()->seller;
        $categories = Category::all();
        $minMoq = Setting::getValue('registration_moq_min', 1);
        $maxMoq = Setting::getValue('registration_moq_max', 10000);

        // Determine image limit based on subscription
        $imageLimit = ($seller->hasActiveSubscription() && $seller->plan) 
            ? ($seller->plan->product_image_limit ?? 5) 
            : 4; // Free sellers: 4 images per product

        return view('seller.products.edit', compact('product', 'categories', 'minMoq', 'maxMoq', 'imageLimit'));
    }

    public function update(Request $request, Product $product)
    {
        $this->authorizeProduct($product);
        $seller = Auth::user()->seller;
        
        // Determine image limit based on subscription
        $imageLimit = ($seller->hasActiveSubscription() && $seller->plan) 
            ? ($seller->plan->product_image_limit ?? 5) 
            : 4; // Free sellers: 4 images per product

        $minMoq = Setting::getValue('registration_moq_min', 1);
        $maxMoq = Setting::getValue('registration_moq_max', 10000);

        \Illuminate\Support\Facades\Log::info('Update Product Request:', $request->all());
        \Illuminate\Support\Facades\Log::info('Min MOQ: ' . $minMoq . ', Max MOQ: ' . $maxMoq);

        $request->validate([
            'name' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'description' => 'required|string',
            'price' => 'required|numeric|min:0',
            'currency' => 'required|in:INR,USD',
            'stock' => 'required|integer|min:0',
            'stock' => 'required|integer|min:0',
            'moq' => "required|integer|between:$minMoq,$maxMoq",
            'images' => 'nullable|array|max:' . $imageLimit,
            'images.*' => 'image|mimes:jpeg,png,jpg,gif,webp|max:2048',
            'specifications' => 'nullable|array',
            'specifications.*.key' => 'nullable|string|max:255',
            'specifications.*.value' => 'nullable|string|max:255',
        ]);

        $imagesJson = $product->images_json;

        // Robustly handle existing data (fix for double-encoded or string data)
        if (is_string($imagesJson)) {
            $decoded = json_decode($imagesJson, true);
            $imagesJson = (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) ? $decoded : [];
        }
        // Ensure it's an array
        if (!is_array($imagesJson)) {
            $imagesJson = [];
        }

        \Illuminate\Support\Facades\Log::info('Update Product Request Data:', $request->all());
        \Illuminate\Support\Facades\Log::info('Has Images:', ['has_file' => $request->hasFile('images')]);

        // Calculate total images after update
        $existingCount = count($imagesJson);
        $deletingCount = count($request->delete_images ?? []);
        $newCount = $request->hasFile('images') ? count($request->file('images')) : 0;
        $totalAfterUpdate = $existingCount - $deletingCount + $newCount;

        if ($totalAfterUpdate > $imageLimit) {
            return redirect()->back()->with('error', "You can only have {$imageLimit} images per product. Current: {$existingCount}, trying to add: {$newCount}. Please delete some images first or upgrade your plan.");
        }

        if ($totalAfterUpdate < 1) {
            return redirect()->back()->with('error', "At least one image is required for the product.");
        }

        if ($request->hasFile('images')) {
            foreach ($request->file('images') as $image) {
                \Illuminate\Support\Facades\Log::info('Processing Image:', ['original_name' => $image->getClientOriginalName()]);
                $originalPath = $this->uploadImage($image, 'products');
                $thumbnailPath = $this->uploadImage($image, 'products/thumbnails', 300, 300);

                $imagesJson[] = [
                    'original' => $originalPath,
                    'thumbnail' => $thumbnailPath,
                ];
            }
        }
        
        // Handle image deletion if passed (e.g. checkbox array of indices to delete)
        if ($request->has('delete_images')) {
            $indicesToDelete = $request->delete_images;
            $newImagesJson = [];
            foreach ($imagesJson as $index => $img) {
                if (in_array($index, $indicesToDelete)) {
                    $this->deleteImage($img['original']);
                    $this->deleteImage($img['thumbnail']);
                } else {
                    $newImagesJson[] = $img;
                }
            }
            $imagesJson = $newImagesJson;
        }

        // Process Specifications
        $specifications = [];
        if ($request->has('specifications')) {
            foreach ($request->specifications as $spec) {
                if (!empty($spec['key']) && !empty($spec['value'])) {
                    $specifications[$spec['key']] = $spec['value'];
                }
            }
        }

        $product->update([
            'category_id' => $request->category_id,
            'name' => $request->name,
            'description' => $request->description,
            'price' => $request->price,
            'currency' => $request->currency,
            'stock' => $request->stock,
            'moq' => $request->moq,
            'images_json' => $imagesJson,
            'specifications' => $specifications,
        ]);

        \Illuminate\Support\Facades\Log::info('Product Updated. New MOQ: ' . $product->fresh()->moq);
        \Illuminate\Support\Facades\Log::info('Product Updated. Images Count: ' . count($imagesJson));

        return redirect()->route('seller.products.index')->with('success', 'Product updated successfully.');
    }

    public function destroy(Product $product)
    {
        $this->authorizeProduct($product);

        if ($product->images_json) {
            foreach ($product->images_json as $img) {
                $this->deleteImage($img['original']);
                $this->deleteImage($img['thumbnail']);
            }
        }

        $product->delete();

        return redirect()->route('seller.products.index')->with('success', 'Product deleted successfully.');
    }

    private function authorizeProduct(Product $product)
    {
        if ($product->seller_id !== Auth::user()->seller->id) {
            abort(403, 'Unauthorized action.');
        }
    }
}
