<?php

namespace App\Service;

use App\Http\Resources\BlogCategoryResource;
use App\Http\Resources\BlogResource;
use App\Models\Blog;
use App\Models\BlogCategory;
use App\Traits\JsonResponseTrait;
use App\Traits\PaginationResponseTrait;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Log;

class BlogService
{
    use JsonResponseTrait, PaginationResponseTrait;

    /**
     * Get all blogs with search, sort, filter and pagination
     */
    public function getBlogs(array $filters = [])
    {
        $query = Blog::with(['category', 'author']);

        $query->where('status', true);

        // Search functionality
        if (!empty($filters['search'])) {
            $searchTerm = $filters['search'];
            $query->where(function ($q) use ($searchTerm) {
                $q->where('title', 'LIKE', "%{$searchTerm}%")
                    ->orWhere('content', 'LIKE', "%{$searchTerm}%")
                    ->orWhere('excerpt', 'LIKE', "%{$searchTerm}%")
                    ->orWhere('slug', 'LIKE', "%{$searchTerm}%")
                    ->orWhereHas('category', function ($categoryQuery) use ($searchTerm) {
                        $categoryQuery->where('name', 'LIKE', "%{$searchTerm}%");
                    })
                    ->orWhereHas('author', function ($authorQuery) use ($searchTerm) {
                        $authorQuery->where('firstname', 'LIKE', "%{$searchTerm}%")
                            ->orWhere('lastname', 'LIKE', "%{$searchTerm}%");
                    });
            });
        }

        // Filter by category
        if (!empty($filters['category_id'])) {
            $query->where('category_id', $filters['category_id']);
        }

        // Filter by author
        if (!empty($filters['author_id'])) {
            $query->where('author_id', $filters['author_id']);
        }


        // Filter by featured status
        if (isset($filters['is_featured'])) {
            $query->where('is_featured', (bool) $filters['is_featured']);
        }

        // Date range filtering
        if (!empty($filters['published_from'])) {
            $query->whereDate('published_at', '>=', $filters['published_from']);
        }

        if (!empty($filters['published_to'])) {
            $query->whereDate('published_at', '<=', $filters['published_to']);
        }

        // Date range filtering for created_at
        if (!empty($filters['created_from'])) {
            $query->whereDate('created_at', '>=', $filters['created_from']);
        }

        if (!empty($filters['created_to'])) {
            $query->whereDate('created_at', '<=', $filters['created_to']);
        }

        // Sorting functionality
        $sortBy = $filters['sort_by'] ?? 'created_at';
        $sortOrder = $filters['sort_order'] ?? 'desc';

        // Validate sort column to prevent SQL injection
        $allowedSortColumns = ['title', 'status', 'is_featured', 'published_at', 'created_at', 'updated_at', 'view_count'];
        if (!in_array($sortBy, $allowedSortColumns)) {
            $sortBy = 'created_at';
        }

        // Validate sort order
        $sortOrder = in_array(strtolower($sortOrder), ['asc', 'desc']) ? $sortOrder : 'desc';

        $query->orderBy($sortBy, $sortOrder);

        // Use the pagination trait for consistent response format
        return $this->paginatedResponse(
            BlogResource::class,
            $query,
            [],
            'Blogs retrieved successfully'
        );
    }

    /**
     * Get blog by ID
     */
    public function getBlogById(string $blogId)
    {
        //status must be true
        $blog = Blog::where('id', $blogId)->where('status', true)->with(['category', 'author'])->first();

        if (!$blog) {
            return $this->errorResponse(statusCode: 404, message: "Blog not found");
        }

        return $this->successDataResponse(
            data: $blog,
            message: "Blog retrieved successfully"
        );
    }


    /**
     * Update blog read count
     */
    public function updateReadCount(string $blogId)
    {
        $blog = Blog::where('id', $blogId)->first();

        if (!$blog) {
            return $this->errorResponse(statusCode: 404, message: "Blog not found");
        }

        $blog->update([
            'read_count' => $blog->read_count + 1,
        ]);

        return $this->successDataResponse(
            data: $blog,
            message: "Blog read count updated successfully"
        );
    }

    /**
     * Get all blog categories with search, sort, filter and pagination
     */
    public function getBlogCategories(array $filters = [])
    {
        $query = BlogCategory::withCount('blogs');
        $query->where('status', true);

        // Search functionality
        if (!empty($filters['search'])) {
            $searchTerm = $filters['search'];
            $query->where(function ($q) use ($searchTerm) {
                $q->where('name', 'LIKE', "%{$searchTerm}%")
                    ->orWhere('description', 'LIKE', "%{$searchTerm}%");
            });
        }

        // Filter by status
        if (isset($filters['status'])) {
            $query->where('status', (bool) $filters['status']);
        }

        // Filter by blog count range
        if (!empty($filters['min_blogs_count'])) {
            $query->having('blogs_count', '>=', $filters['min_blogs_count']);
        }

        if (!empty($filters['max_blogs_count'])) {
            $query->having('blogs_count', '<=', $filters['max_blogs_count']);
        }

        // Date range filtering
        if (!empty($filters['created_from'])) {
            $query->whereDate('created_at', '>=', $filters['created_from']);
        }

        if (!empty($filters['created_to'])) {
            $query->whereDate('created_at', '<=', $filters['created_to']);
        }

        // Sorting functionality
        $sortBy = $filters['sort_by'] ?? 'name';
        $sortOrder = $filters['sort_order'] ?? 'asc';

        // Validate sort column to prevent SQL injection
        $allowedSortColumns = ['name', 'status', 'blogs_count', 'created_at', 'updated_at'];
        if (!in_array($sortBy, $allowedSortColumns)) {
            $sortBy = 'name';
        }

        // Validate sort order
        $sortOrder = in_array(strtolower($sortOrder), ['asc', 'desc']) ? $sortOrder : 'asc';

        $query->orderBy($sortBy, $sortOrder);

        // Use the pagination trait for consistent response format
        return $this->paginatedResponse(
            BlogCategoryResource::class,
            $query,
            [],
            'Blog categories retrieved successfully'
        );
    }

    /**
     * Get category by ID
     */
    public function getBlogCategoryById(string $categoryId)
    {
        $category = BlogCategory::where('id', $categoryId)->where('status', true)->with('blogs')->first();

        if (!$category) {
            return $this->errorResponse(statusCode: 404, message: "Blog category not found");
        }

        return $this->successDataResponse(
            data: $category,
            message: "Blog category retrieved successfully"
        );
    }



}
