<?php

namespace App\Http\Controllers;

use App\Models\News;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class NewsController extends Controller
{
    /**
     * Display a listing of the news.
     */
    public function index(Request $request)
    {
        // Add ability to filter news
        $query = News::with('author')->latest();
        
        // Filter by search term if provided
        if ($request->filled('search')) {
            $searchTerm = $request->input('search');
            $query->where(function($q) use ($searchTerm) {
                $q->where('title', 'like', "%{$searchTerm}%")
                  ->orWhere('short_description', 'like', "%{$searchTerm}%")
                  ->orWhere('content', 'like', "%{$searchTerm}%");
            });
        }
        
        // Filter by author if provided
        if ($request->filled('author')) {
            $query->whereHas('author', function($q) use ($request) {
                $q->where('name', 'like', "%{$request->input('author')}%");
            });
        }
        
        $news = $query->paginate(9)->withQueryString();
        
        // Get popular authors for filtering
        $popularAuthors = News::with('author')
            ->select('author_id')
            ->groupBy('author_id')
            ->selectRaw('count(*) as article_count')
            ->orderByDesc('article_count')
            ->limit(5)
            ->get()
            ->map(function($item) {
                return $item->author;
            });
            
        return view('news.index', compact('news', 'popularAuthors'));
    }

    /**
     * Display the specified news article.
    */
    public function show(string $slug)
    {
        $article = News::with('author')->where('slug', $slug)->firstOrFail();
        
        // Enhanced related articles algorithm 
        $relatedNews = News::with('author')
            ->where('id', '!=', $article->id)
            ->where(function($query) use ($article) {
                // Match by author
                $query->where('author_id', $article->author_id)
                      // Or match by title keywords (now using multiple words)
                      ->orWhere(function($q) use ($article) {
                          $keywords = array_filter(
                              explode(' ', $article->title),
                              function($word) { return strlen($word) > 3; }
                          );
                          
                          foreach (array_slice($keywords, 0, 3) as $keyword) {
                              $q->orWhere('title', 'like', '%' . $keyword . '%');
                          }
                      })
                      // Or match by content similarity
                      ->orWhere(function($q) use ($article) {
                          // Extract potential tags or categories from content
                          $contentExcerpt = Str::limit(strip_tags($article->content), 500);
                          $contentWords = array_filter(
                              explode(' ', $contentExcerpt), 
                              function($word) { return strlen($word) > 4; }
                          );
                          
                          foreach (array_slice($contentWords, 0, 5) as $word) {
                              $q->orWhere('content', 'like', '%' . $word . '%');
                          }
                      });
            })
            ->latest()
            ->limit(3)
            ->get();
            
        // Record view (could be expanded to a proper view counter)
        // This would require adding a views column to the news table
        if ($article->exists && property_exists($article, 'views')) {
            $article->increment('views');
        }
            
        return view('news.show', compact('article', 'relatedNews'));
    }
}