<?php

namespace App\Http\Controllers;

use App\Models\News;
use Exception;
use Illuminate\Http\Request;

class NewsController extends Controller
{
    public function index(Request $request)
    {
        $category = $request->get('category', 'all');

        $query = News::published()->orderBy('created_at', 'desc');

        if ($category !== 'all') {
            $query->byCategory($category);
        }

        $news = $query->paginate(6);

        $categories = News::published()
            ->select('category')
            ->distinct()
            ->pluck('category');

        // Handle AJAX requests
        if ($request->ajax() || $request->has('ajax')) {
            try {
                $html = view('landing.components.news-grid', compact('news'))->render();
                return response()->json([
                    'html' => $html,
                    'hasMore' => $news->hasMorePages(),
                    'currentPage' => $news->currentPage(),
                    'lastPage' => $news->lastPage(),
                    'debug' => [
                        'category' => $category,
                        'count' => $news->count(),
                        'total' => $news->total()
                    ]
                ]);
            } catch (\Exception $e) {
                return response()->json([
                    'error' => $e->getMessage(),
                    'debug' => [
                        'category' => $category,
                        'count' => $news->count(),
                        'total' => $news->total()
                    ]
                ], 500);
            }
        }

        return view('landing.components.news-list', compact('news', 'categories', 'category'));
    }

    public function show($slug)
    {
        $news = News::published()->where('slug', $slug)->firstOrFail();

        // Increment view count
        $news->incrementViews();

        // Get related news from same category
        $relatedNews = News::published()
            ->where('category', $news->category)
            ->where('id', '!=', $news->id)
            ->orderBy('created_at', 'desc')
            ->limit(3)
            ->get();

        return view('landing.components.detail-information', compact('news', 'relatedNews'));
    }

    public function getCategories()
    {
        $categories = News::published()
            ->select('category')
            ->distinct()
            ->pluck('category');

        return response()->json($categories);
    }
}
