<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Models\Seller;
use Illuminate\Http\Request;

class SellerProfileController extends Controller
{
    public function show($slug)
    {
        $seller = Seller::where('slug', $slug)
            ->where('is_active', true)
            ->with([
                'products' => fn($q) => $q->latest()->limit(12),
                'subscription.plan',
                'banners' => fn($q) => $q->orderBy('order'),
                'certificates',
                'pages' => fn($q) => $q->where('is_active', true),
                'testimonials' => fn($q) => $q->where('is_active', true)->orderBy('order'),
                'faqs' => fn($q) => $q->where('is_active', true)->orderBy('order'),
                'micrositeSettings',
            ])
            ->firstOrFail();

        // Get or create microsite settings
        $settings = $seller->getOrCreateMicrositeSettings();
        
        // Track page view
        $this->trackPageView($seller);

        $settings->incrementViews();

        $products = $seller->products()->latest()->limit(12)->get(); // Use get() instead of paginate for show page
        $isPaid = $seller->hasActiveSubscription();
        
        // Get plan-based features
        $plan = $seller->subscription?->plan;
        $showContact = $isPaid && ($plan?->show_contact_details ?? false);
        $hasVerifiedBadge = $isPaid && ($plan?->has_verified_badge ?? false);
        $isFeatured = $isPaid && ($plan?->is_featured ?? false);

        return view('public.seller.show', compact('seller', 'products', 'isPaid', 'settings', 'showContact', 'hasVerifiedBadge', 'isFeatured'));
    }

    public function products(Request $request, $slug)
    {
        $seller = Seller::where('slug', $slug)->where('is_active', true)->firstOrFail();
        $settings = $seller->getOrCreateMicrositeSettings();
        
        $query = $seller->products()->latest();

        // Search
        if ($request->has('q')) {
            $query->where('name', 'like', '%' . $request->q . '%');
        }

        // Category Filter
        if ($request->has('category') && $request->category != '') {
             $query->where('category_id', $request->category);
        }

        // Sort
        if ($request->has('sort')) {
            switch ($request->sort) {
                case 'price_low':
                    $query->orderBy('price', 'asc');
                    break;
                case 'price_high':
                    $query->orderBy('price', 'desc');
                    break;
                default:
                    $query->latest();
            }
        }

        $products = $query->paginate(24);
        $categories = \App\Models\Category::whereIn('id', $seller->products()->pluck('category_id')->unique())->get();

        return view('public.seller.products', compact('seller', 'products', 'settings', 'categories'));
    }

    private function trackPageView($seller) {
        $country = null;
        try {
            $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
        }
        
        \App\Models\Analytic::create([
            'seller_id' => $seller->id,
            'type' => 'profile_view',
            'source_id' => $seller->id,
            'country' => $country,
            'ip_address' => request()->ip(),
        ]);
    }
}
