<?php

namespace App\Http\Controllers;

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

class ProductController extends Controller
{
    /**
     * Authenticated user product listing (kept for compatibility) — shows active products.
     */
    public function index(Request $request)
    {
        return $this->publicIndex($request);
    }

    /**
     * Public product listing for users and guests.
     */
    public function publicIndex(Request $request = null)
    {
        $productsQuery = Product::with(['category', 'programmingLanguage'])->where('is_active', true);

        if (request('search')) {
            $search = request('search');
            $productsQuery->where(function ($query) use ($search) {
                $query->where('name', 'like', "%{$search}%")
                      ->orWhere('description', 'like', "%{$search}%");
            });
        }

        if (request('category')) {
            $productsQuery->where('category_id', request('category'));
        }

        if (request('language')) {
            // The Product model uses the `programming_language` column as the FK
            // (see App\Models\Product::programmingLanguage relation).
            $productsQuery->where('programming_language', request('language'));
        }

        if (request('price_filter') === 'free') {
            $productsQuery->where('price', 0);
        } elseif (request('price_filter') === 'paid') {
            $productsQuery->where('price', '>', 0);
        }

        $sort = request('sort', 'name');
        switch ($sort) {
            case 'price_low':
                $productsQuery->orderBy('price', 'asc');
                break;
            case 'price_high':
                $productsQuery->orderBy('price', 'desc');
                break;
            case 'newest':
                $productsQuery->orderBy('created_at', 'desc');
                break;
            default:
                $productsQuery->orderBy('name', 'asc');
        }

        $products = $productsQuery->paginate(15)->withQueryString();
        $categories = \App\Models\ProductCategory::where('is_active', true)->orderBy('sort_order')->get();
        $programmingLanguages = \App\Models\ProgrammingLanguage::where('is_active', true)->orderBy('sort_order')->get();

        return view('user.products.index', compact('products', 'categories', 'programmingLanguages'));
    }

    /**
     * Show product details for authenticated users (compatibility).
     */
    public function show(Product $product)
    {
        if (!$product->is_active) {
            abort(404);
        }

        // Check if user owns this product
        $userOwnsProduct = false;
        if (auth()->check()) {
            $userOwnsProduct = auth()->user()->licenses()
                ->where('product_id', $product->id)
                ->where('status', 'active')
                ->where(function ($q) {
                    $q->whereNull('license_expires_at')
                      ->orWhere('license_expires_at', '>', now());
                })
                ->exists();
        }

        // Process content for HTML/text detection
        $product->description_has_html = $product->description ? strip_tags($product->description) !== $product->description : false;
        $product->requirements_has_html = $product->requirements ? (is_string($product->requirements) && strip_tags($product->requirements) !== $product->requirements) : false;
        $product->installation_guide_has_html = $product->installation_guide ? (is_string($product->installation_guide) && strip_tags($product->installation_guide) !== $product->installation_guide) : false;

        // Get license count for this product
        $licenseCount = \App\Models\License::where('product_id', $product->id)
            ->where('status', 'active')
            ->where(function ($q) {
                $q->whereNull('license_expires_at')
                  ->orWhere('license_expires_at', '>', now());
            })
            ->count();

        $relatedProducts = Product::where('category_id', $product->category_id)
            ->where('id', '!=', $product->id)
            ->where('is_active', true)
            ->with(['category', 'programmingLanguage'])
            ->latest()
            ->limit(3)
            ->get();

        return view('user.products.show', compact('product', 'relatedProducts', 'userOwnsProduct', 'licenseCount'));
    }

    /**
     * Public product details (by slug) for guests.
     */
    public function publicShow($slug)
    {
        $product = Product::where('slug', $slug)->where('is_active', true)->with(['category', 'programmingLanguage'])->firstOrFail();

        // Check if user owns this product
        $userOwnsProduct = false;
        if (auth()->check()) {
            $userOwnsProduct = auth()->user()->licenses()
                ->where('product_id', $product->id)
                ->where('status', 'active')
                ->where(function ($q) {
                    $q->whereNull('license_expires_at')
                      ->orWhere('license_expires_at', '>', now());
                })
                ->exists();
        }

        // Process content for HTML/text detection
        $product->description_has_html = $product->description ? strip_tags($product->description) !== $product->description : false;
        $product->requirements_has_html = $product->requirements ? (is_string($product->requirements) && strip_tags($product->requirements) !== $product->requirements) : false;
        $product->installation_guide_has_html = $product->installation_guide ? (is_string($product->installation_guide) && strip_tags($product->installation_guide) !== $product->installation_guide) : false;

        // Get license count for this product
        $licenseCount = \App\Models\License::where('product_id', $product->id)
            ->where('status', 'active')
            ->where(function ($q) {
                $q->whereNull('license_expires_at')
                  ->orWhere('license_expires_at', '>', now());
            })
            ->count();

        $relatedProducts = Product::where('category_id', $product->category_id)
            ->where('id', '!=', $product->id)
            ->where('is_active', true)
            ->with(['category', 'programmingLanguage'])
            ->latest()
            ->limit(3)
            ->get();

        return view('user.products.show', compact('product', 'relatedProducts', 'userOwnsProduct', 'licenseCount'));
    }
}