<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\BlogPost;
use App\Models\BlogCategory;
use App\Models\BlogTag;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class BlogController extends Controller
{

    public function index(Request $request)
    {
        $query = BlogPost::where('author_id', auth()->id())->with(['author', 'category'])->latest();
        
        if ($request->has('search')) {
            $query->where(function($q) use ($request) {
                $q->where('title', 'like', '%' . $request->search . '%')
                  ->orWhere('excerpt', 'like', '%' . $request->search . '%');
            });
        }
        
        // Filter by category
        if ($request->has('category')) {
            $query->where('category_id', $request->category);
        }
        
        // Filter by status
        if ($request->has('status')) {
            if ($request->status === 'published') {
                $query->where('is_published', true);
            } elseif ($request->status === 'draft') {
                $query->where('is_published', false);
            } elseif ($request->status === 'featured') {
                $query->where('is_featured', true);
            }
        }
        
        $posts = $query->paginate(20);
        $categories = BlogCategory::where('is_active', true)->get();
        
        return view('admin.blog.index', compact('posts', 'categories'));
    }

    /**
     * Show the form for creating a new blog post.
     */
    public function create()
    {
        $categories = BlogCategory::where('is_active', true)->get();
        $tags = BlogTag::where('is_active', true)->get();
        
        return view('admin.blog.create', compact('categories', 'tags'));
    }

    /**
     * Store a newly created blog post in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'excerpt' => 'required|string|max:500',
            'content' => 'required|string',
            'featured_image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'category_id' => 'nullable|exists:blog_categories,id',
            'tags' => 'nullable|array',
            'tags.*' => 'exists:blog_tags,id',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string|max:160',
            'meta_keywords' => 'nullable|string',
            'is_featured' => 'boolean',
            'is_published' => 'boolean',
            'published_at' => 'nullable|date',
            'read_time' => 'nullable|integer|min:1',
        ]);

        $post = new BlogPost();
        $post->title = $request->title;
        $post->slug = $this->generateUniqueSlug($request->title);
        $post->excerpt = $request->excerpt;
        $post->content = $request->content;
        $post->category_id = $request->category_id;
        $post->meta_title = $request->meta_title ?? $request->title;
        $post->meta_description = $request->meta_description ?? $request->excerpt;
        $post->meta_keywords = $request->meta_keywords ? explode(',', $request->meta_keywords) : [];
        $post->is_featured = $request->has('is_featured');
        $post->is_published = $request->has('is_published');
        $post->published_at = $request->published_at;
        $post->read_time = $request->read_time ?? $post->getReadTimeAttribute();
        $post->author_id = auth()->id();

        // Handle featured image upload
        if ($request->hasFile('featured_image')) {
            $image = $request->file('featured_image');
            $imageName = time() . '_' . Str::slug($request->title) . '.' . $image->getClientOriginalExtension();
            $image->move(public_path('uploads/blog'), $imageName);
            $post->featured_image = "uploads/blog/" . $imageName;
        }

        $post->save();

        // Sync tags
        if ($request->has('tags')) {
            $post->tags()->sync($request->tags);
        }

        return redirect()->route('admin.blog.index')
            ->with('success', 'Blog post created successfully.');
    }

    /**
     * Show the form for editing the specified blog post.
     */
    public function edit(BlogPost $blog)
    {
        $categories = BlogCategory::where('is_active', true)->get();
        $tags = BlogTag::where('is_active', true)->get();
        $selectedTags = $blog->tags->pluck('id')->toArray();
        
        return view('admin.blog.edit', compact('blog', 'categories', 'tags', 'selectedTags'));
    }

    /**
     * Update the specified blog post in storage.
     */
    public function update(Request $request, BlogPost $blog)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'excerpt' => 'required|string|max:500',
            'content' => 'required|string',
            'featured_image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'category_id' => 'nullable|exists:blog_categories,id',
            'tags' => 'nullable|array',
            'tags.*' => 'exists:blog_tags,id',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string|max:160',
            'meta_keywords' => 'nullable|string',
            'is_featured' => 'boolean',
            'is_published' => 'boolean',
            'published_at' => 'nullable|date',
            'read_time' => 'nullable|integer|min:1',
        ]);

        $blog->title = $request->title;
        $blog->excerpt = $request->excerpt;
        $blog->content = $request->content;
        $blog->category_id = $request->category_id;
        $blog->meta_title = $request->meta_title ?? $request->title;
        $blog->meta_description = $request->meta_description ?? $request->excerpt;
        $blog->meta_keywords = $request->meta_keywords ? explode(',', $request->meta_keywords) : [];
        $blog->is_featured = $request->has('is_featured');
        $blog->is_published = $request->has('is_published');
        $blog->published_at = $request->published_at;
        $blog->read_time = $request->read_time ?? $blog->getReadTimeAttribute();

        // Handle featured image upload
        if ($request->hasFile('featured_image')) {
            // Delete old image
            if ($blog->featured_image && file_exists(public_path($blog->featured_image))) {
                unlink(public_path($blog->featured_image));
            }
            
            $image = $request->file('featured_image');
            $imageName = time() . '_' . Str::slug($request->title) . '.' . $image->getClientOriginalExtension();
            $image->move(public_path('uploads/blog'), $imageName);
            $blog->featured_image = "uploads/blog/" . $imageName;
        }

        $blog->save();

        // Sync tags
        if ($request->has('tags')) {
            $blog->tags()->sync($request->tags);
        } else {
            $blog->tags()->detach();
        }

        return redirect()->route('admin.blog.index')
            ->with('success', 'Blog post updated successfully.');
    }

    /**
     * Remove the specified blog post from storage.
     */
    public function destroy(BlogPost $blog)
    {
        // Delete featured image
        if ($blog->featured_image && file_exists(public_path($blog->featured_image))) {
            unlink(public_path($blog->featured_image));
        }

        $blog->delete();

        return redirect()->route('admin.blog.index')
            ->with('success', 'Blog post deleted successfully.');
    }

    /**
     * Toggle publish status
     */
    public function toggleStatus(BlogPost $blog)
    {
        $blog->is_published = !$blog->is_published;
        if ($blog->is_published && !$blog->published_at) {
            $blog->published_at = now();
        }
        $blog->save();

        $status = $blog->is_published ? 'published' : 'unpublished';
        return response()->json([
            'success' => true,
            'message' => "Blog post {$status} successfully.",
            'is_published' => $blog->is_published
        ]);
    }

    /**
     * Toggle featured status
     */
    public function toggleFeatured(BlogPost $blog)
    {
        $blog->is_featured = !$blog->is_featured;
        $blog->save();

        $status = $blog->is_featured ? 'featured' : 'unfeatured';
        return response()->json([
            'success' => true,
            'message' => "Blog post {$status} successfully.",
            'is_featured' => $blog->is_featured
        ]);
    }

    /**
     * Generate unique slug
     */
    private function generateUniqueSlug($title)
    {
        $slug = Str::slug($title);
        $originalSlug = $slug;
        $count = 1;

        while (BlogPost::where('slug', $slug)->exists()) {
            $slug = $originalSlug . '-' . $count++;
        }

        return $slug;
    }
}