<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Arr;

use App\Http\Requests\BlogValidation;

use App\Utilities\Paginate;
use App\Utilities\SearchResult;

use App\Traits\PagesControllerTrait;
use App\Traits\PublicationsControllerTrait;

use App\Models\Blog;
use App\Models\Tag;

class BlogsController extends Controller
{
    use PagesControllerTrait;
    use PublicationsControllerTrait;

    protected function getModel()
    {
        return new Blog();
    }

    protected function getClassname()
    {
        return 'blog';
    }

    protected function getValidation()
    {
        return (new BlogValidation());
    }

    protected function findPage($path)
    {
        return (new Blog())->findByFullSlug($path);
    }

    
    public function index()
    {
        if (!auth()->user()?->can('viewAny', Blog::class)) {
            if (request()->expectsJson()) {
                return response()->json(['error' => 'You do not have permission to sort pages'], 403);
            } else {
                return redirect('/')->with('error', 'You do not have access to view Blogs');
            }
        }

        return view('blogs.index');
    }

public function paginate()
    {
        // 1. Force the fast sorting and hard limits
        request()->merge([
            'limit' => 20,              // Stop the database after 20 total records
            'sort_by' => 'created_at',  // Sorts by the actual date created (bypassing the slow version query)
            'descending' => true        // Puts the newest/latest blogs at the top
        ]);

        // 2. Fetch those 20 newest blogs instantly
        $allBlogs = (new Blog())->getByTags(request());

        // 3. Set up our 5-per-page logic
        $perPage = 4;
        $page = request()->input('paginate_page', 1);

        // 4. Slice the 20 records into the current page of 5
        $slicedBlogs = $allBlogs->slice(($page - 1) * $perPage, $perPage)->values();

        // 5. Package it into the exact JSON format your frontend expects
        return new \Illuminate\Pagination\LengthAwarePaginator(
            $slicedBlogs,       // The 5 blogs for the current page
            $allBlogs->count(), // Hard caps the total at 20 (fixing the 5748 issue)
            $perPage,           // 5 items per page
            $page,              // Current page number
            [
                'path' => request()->url(),
                'query' => request()->query()
            ]
        );
    }


    public function search()
    {
        request()->validate([
            'terms' => 'required|min:3',
        ]);

        $terms = SearchResult::collectTerms();
        $search_results = Blog::searchResults($terms);

        if ($search_results->count()) {
            $blogs = (new Blog())->getByTags(request(), $search_results->pluck('id')->toArray());
        } else {
            $blogs = collect();
        }

        return Paginate::create((new Blog())->loadCollectionAttributes($blogs));
    }
    
}
