<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\Analytic;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function show($slug, Request $request)
    {
        $product = Product::where('slug', $slug)->with(['seller', 'category'])->firstOrFail();

        // Track Recently Viewed
        $recentlyViewed = session()->get('recently_viewed', []);
        if (!in_array($product->id, $recentlyViewed)) {
            array_unshift($recentlyViewed, $product->id);
            $recentlyViewed = array_slice($recentlyViewed, 0, 8); // Keep last 8
            session()->put('recently_viewed', $recentlyViewed);
        }

        // Log Product View
        $country = null;
        try {
            // Simple IP Geolocation (Timeout to prevent slow loading)
            $ip = $request->ip();
            if ($ip !== '127.0.0.1' && $ip !== '::1') {
                $geo = json_decode(file_get_contents("http://ip-api.com/json/{$ip}?fields=country"), true);
                $country = $geo['country'] ?? null;
            }
        } catch (\Exception $e) {
            // Fail silently to not disrupt user experience
        }

        Analytic::create([
            'seller_id' => $product->seller_id,
            'type' => 'product_view',
            'source_id' => $product->id,
            'country' => $country,
            'ip_address' => $request->ip(),
        ]);

        // Fetch Related Products (Same Category, excluding current product)
        $relatedProducts = Product::where('category_id', $product->category_id)
            ->where('id', '!=', $product->id)
            ->with('seller')
            ->take(4)
            ->get();

        if ($request->wantsJson()) {
            return response()->json([
                'html' => view('public.products.quick-view', compact('product'))->render(),
                'product' => $product
            ]);
        }

        return view('public.products.show', compact('product', 'relatedProducts'));
    }
    public function quickView($slug)
    {
        $product = Product::where('slug', $slug)->with(['seller', 'category'])->firstOrFail();
        
        // Log view (optional, but good for analytics)
        Analytic::create([
            'seller_id' => $product->seller_id,
            'type' => 'product_view', // Or 'quick_view' if we want to distinguish
            'source_id' => $product->id,
            'ip_address' => request()->ip(),
        ]);

        return view('public.products.quick-view', compact('product'));
    }
}
