<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Article;
use App\Models\CardArticle;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ArticleController extends Controller
{
    public function index()
{
    $cardArticles = CardArticle::whereHas('articles', function($q) {
            $q->where('status', 'Disetujui');
        })
        ->with(['articles' => function($q) {
            $q->where('status', 'Disetujui')->with('subArticles');
        }])
        ->withCount(['articles' => function($q) {
            $q->where('status', 'Disetujui');
        }])
        ->latest()
        ->take(8)
        ->get();

    $readingSpeed = 200; 

    foreach ($cardArticles as $card) {
        $totalReadingTime = 0;
        foreach ($card->articles as $article) {
            $text = $article->title . ' ' . $article->description;
            if ($article->subArticles && $article->subArticles->isNotEmpty()) {
                $subText = $article->subArticles
                    ->map(function ($sub) {
                        return $sub->title . ' ' . $sub->content;
                    })
                    ->implode(' ');
                $text .= ' ' . $subText;
            }
            $wordCount = str_word_count(strip_tags($text));
            $articleReadingTime = ceil($wordCount / $readingSpeed);
            $totalReadingTime += $articleReadingTime;
        }
        $card->readingTime = $totalReadingTime;
    }   
    
    $totalArticles = Article::where('status', 'Disetujui')->count();
    $totalUsers = User::count();

    return view('home', compact('cardArticles', 'totalArticles', 'totalUsers'));
}

public function showAllCards(Request $request)
{
    $search = $request->get('search');
    $cardArticlesQuery = CardArticle::whereHas('articles', function ($q) {
        $q->where('status', 'Disetujui');
    })
    ->withCount(['articles' => function ($q) {
        $q->where('status', 'Disetujui');
    }])
    ->latest();

    if ($search) {
        $cardArticlesQuery->where('title', 'like', '%' . $search . '%');
    }

    $cardArticles = $cardArticlesQuery->paginate(8);

    $readingSpeed = 200; 

    foreach ($cardArticles as $card) {
        $totalReadingTime = 0;
        foreach ($card->articles as $article) {
            $text = $article->title . ' ' . $article->description;

            if ($article->subArticles && $article->subArticles->isNotEmpty()) {
                $subText = $article->subArticles
                    ->map(function ($sub) {
                        return $sub->title . ' ' . $sub->content;
                    })
                    ->implode(' ');

                $text .= ' ' . $subText;
            }

            $wordCount = str_word_count(strip_tags($text));
            $articleReadingTime = ceil($wordCount / $readingSpeed);
            $totalReadingTime += $articleReadingTime;
        }

        $card->readingTime = $totalReadingTime;
    }

    return view('livewire.pages.home.all-cards', compact('cardArticles'));
}

public function showArticles(Request $request, $id)
{
    try {
        $card = CardArticle::whereHas('articles', function($query) {
                $query->where('status', 'Disetujui');
            })->findOrFail($id);

        $articlesQuery = $card->articles()
            ->with('subArticles')
            ->where('status', 'Disetujui');

        if ($request->has('search')) {
            $search = $request->get('search');
            $articlesQuery->where('title', 'like', '%' . $search . '%');
        }

        $articles = $articlesQuery->latest()->paginate(8);
        $readingSpeed = 200; 

        foreach ($articles as $article) {
            $text = $article->title . ' ' . $article->description;
            
            if ($article->subArticles && $article->subArticles->isNotEmpty()) {
                $subText = $article->subArticles->map(function ($sub) {
                    return $sub->title . ' ' . $sub->content;
                })->implode(' ');

                $text .= ' ' . $subText;
            }
            
            $wordCount = str_word_count(strip_tags($text));
            $article->readingTime = ceil($wordCount / $readingSpeed);
        }

        $totalReadingTime = $articles->sum('readingTime');
        $card->readingTime = $totalReadingTime;

        return view('livewire.pages.home.articles', compact('card', 'articles'));
    } catch (\Exception $e) {
        return redirect('/')->with('error', 'Card artikel tidak ditemukan atau tidak memiliki artikel yang disetujui.');
    }
}

    public function showArticleDetail($id)
{
    $article = Article::with(['subArticles' => function ($query) {
        $query->orderBy('order_number', 'asc'); 
    }])->findOrFail($id);

    return view('livewire.pages.home.article-detail', compact('article'));
}

}
