<?php

namespace App\Http\Controllers;

use App\Http\Resources\BlogResource;
use App\Http\Resources\BlogCategoryResource;
use App\Models\Blog;
use App\Models\BlogCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class BlogController extends Controller
{
    /**
     * Display a listing of blogs
     */
    public function index(Request $request)
    {
        $blogs = Blog::where('active', true);

        // Search functionality
        if ($request->has('search')) {
            $search = $request->input('search');
            $blogs->where('title', 'like', "%{$search}%")
                ->orWhere('description', 'like', "%{$search}%");
        }

        // Category filter
        if ($request->has('category')) {
            $categoryId = $request->input('category');
            $blogs->where('category_id', $categoryId);
        }

        // For API requests
        if ($request->wantsJson() || $request->is('api/*')) {
            $offset = $request->query('offset', 0);
            $limit = $request->query('limit', 10);

            $result = $blogs->latest()
                ->skip($offset)
                ->take($limit)
                ->get();

            return response()->json([
                'status' => 200,
                'message' => 'Blogs fetched successfully.',
                'data' => BlogResource::collection($result),
            ]);
        }

        // For web requests
        $result = $blogs->latest()->paginate(9);
        $categories = BlogCategory::where('status', 1)->get();
        
        return view('front_end.pages.blogs.index', compact('result', 'categories'));
    }

    /**
     * Display the specified blog
     */
    public function show(Request $request, $slug)
    {

        $blog = Blog::where('slug', $slug)->where('active', true)->firstOrFail();

        // For API requests
        if ($request->wantsJson() || $request->is('api/*')) {
            return response()->json([
                'status' => 200,
                'message' => 'Blog fetched successfully.',
                'data' => new BlogResource($blog),
            ]);
        }

        // Get related blogs
        $relatedBlogs = Blog::where('category_id', $blog->category_id)
            ->where('id', '!=', $blog->id)
            ->where('active', true)
            ->latest()
            ->limit(3)
            ->get();

        $categories = BlogCategory::where('status', 1)->get();

        return view('front_end.pages.blogs.show', compact('blog', 'relatedBlogs', 'categories'));
    }

    /**
     * Display blogs by category
     */
    public function category(Request $request, $slug)
    {
        $blogCategory = BlogCategory::where('slug', $slug)->where('status', 1)->firstOrFail();

        $blogs = Blog::where('category', $blogCategory->id)->where('active', true);

        // Search functionality
        if ($request->has('search')) {
            $search = $request->input('search');
            $blogs->where('title', 'like', "%{$search}%")
                ->orWhere('description', 'like', "%{$search}%");
        }


        // For API requests
        if ($request->wantsJson() || $request->is('api/*')) {
            $offset = $request->query('offset', 0);
            $limit = $request->query('limit', 10);

            $result = $blogs->latest()
                ->skip($offset)
                ->take($limit)
                ->get();

            return response()->json([
                'status' => 200,
                'message' => 'Blogs fetched successfully.',
                'data' => BlogResource::collection($result),
            ]);
        }

        // For web requests
        $result = $blogs->latest()->paginate(9);
        $categories = BlogCategory::where('status', 1)->get();

        return view('front_end.pages.blogs.index', compact('result', 'categories', 'slug'));
    }


    /**
     * Helper: Map category ID to name
     */
    private function getCategoryName($categoryId)
    {
        $categories = $this->getCategories();
        return $categories[$categoryId] ?? 'Uncategorized';
    }

    /**
     * Helper: Get all categories for dropdowns
     */
    private function getCategories()
    {
        return [
            1 => 'Technology',
            2 => 'Health',
            3 => 'Lifestyle',
            4 => 'Finance',
            5 => 'Education',
            6 => 'Travel',
            7 => 'Food',
            8 => 'Entertainment',
            9 => 'Sports',
            10 => 'Business',
            11 => 'Science',
            12 => 'Art',
            13 => 'Fashion',
            14 => 'Environment',
            15 => 'Politics',
        ];
    }

    public function listBlogs(Request $request)
    {
        // Set default values for offset and limit
        $offset = $request->query('offset', 0);
        $limit = $request->query('limit', 10);

        // Fetch blogs with pagination


        $blogs = Blog::where('active', true)
            ->select('id', 'title', 'slug', 'description', 'thumbnail', 'category_id', 'created_at', 'updated_at') // Select only necessary fields
            ->latest()
            ->skip($offset)
            ->take($limit)
            ->get();


        // Get total count for pagination
        $totalBlogs = Blog::where('active', true)->count();

        return response()->json([
            'status' => 200,
            'message' => 'Blogs fetched successfully.',
            'data' => BlogResource::collection($blogs), // Use BlogResource for consistent formatting
            'total' => $totalBlogs, // Include total count for pagination
            'offset' => $offset,
            'limit' => $limit,
        ]);
    }

    /**
     * Search blogs by title or description.
     */
    public function search(Request $request)
    {
        $request->validate([
            'query' => 'required|string|min:1',
        ]);

        $searchQuery = $request->input('query');

        $blogs = Blog::where('active', true)
            ->where(function ($query) use ($searchQuery) {
                $query->where('title', 'like', "%{$searchQuery}%")
                    ->orWhere('description', 'like', "%{$searchQuery}%");
            })
            ->latest()
            ->get();

        return response()->json([
            'status' => 200,
            'message' => 'Blogs fetched successfully.',
            'data' => BlogResource::collection($blogs),
        ]);
    }

    /**
     * Get blog details by ID.
     */
    public function getBlogById($id)
    {
        $blog = Blog::findOrFail($id);

        return response()->json([
            'status' => 200,
            'message' => 'Blog fetched successfully.',
            'data' => new BlogResource($blog),
        ]);
    }
}
