<?php

namespace App\Http\Controllers\Backend;

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

class BlogController extends Controller
{
    public function index(Request $request)
    {
        $query = Blog::with('category');

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

        $blogs = $query->latest()->paginate(10);
        return view('admin.pages.blogs.index', compact('blogs'));
    }

    public function create()
    {
        $categories = BlogCategory::where('status', 1)->get();
        return view('admin.pages.blogs.create', compact('categories'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'content' => 'required|string',
            'thumbnail' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'category_id' => 'nullable|exists:blog_categories,id',
            'active' => 'boolean',
            'is_featured' => 'boolean',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string',
            'meta_keywords' => 'nullable|string',
            'type' => 'nullable|string|max:125',
            'status' => 'nullable|string|max:125',
        ]);

        // Handle thumbnail upload using storeMedia
        $thumbnailPath = null;
        if ($request->hasFile('thumbnail')) {
            $thumbnailPath = storeMedia($request->file('thumbnail'), 'blogs');
        }

        // Get category name if category is selected
        $categoryName = null;
        if ($request->category_id) {
            $category = BlogCategory::find($request->category_id);
            $categoryName = $category ? $category->name : null;
        }

        Blog::create([
            'title' => $request->title,
            'slug' => Str::slug($request->title),
            'description' => $request->description,
            'content' => $request->content,
            'type' => $request->type ?? 'blog',
            'category' => $request->category_id,
            'category_name' => $categoryName,
            'category_id' => $request->category_id,
            'is_featured' => $request->is_featured ?? false,
            'thumbnail' => $thumbnailPath,
            'meta_title' => $request->meta_title,
            'meta_description' => $request->meta_description,
            'meta_keywords' => $request->meta_keywords,
            'status' => $request->status ?? 'Published',
            'active' => $request->active ?? true,
            'user_id' => auth()->id(),
            'created_by_name' => auth()->user()->name ?? 'Admin',
            'published_at' => now(),
            'hits' => 0,
        ]);

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

    public function edit(Blog $blog)
    {
        $categories = BlogCategory::where('status', 1)->get();
        return view('admin.pages.blogs.edit', compact('blog', 'categories'));
    }

    public function update(Request $request, Blog $blog)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'content' => 'required|string',
            'thumbnail' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'category_id' => 'nullable|exists:blog_categories,id',
            'active' => 'boolean',
            'is_featured' => 'boolean',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string',
            'meta_keywords' => 'nullable|string',
            'type' => 'nullable|string|max:125',
            'status' => 'nullable|string|max:125',
        ]);

        // Handle thumbnail upload
        $thumbnailPath = $blog->thumbnail;
        if ($request->hasFile('thumbnail')) {
            // Delete old thumbnail
            if ($blog->thumbnail) {
                Storage::disk('public')->delete($blog->thumbnail);
            }
            $thumbnailPath = storeMedia($request->file('thumbnail'), 'blogs');
        }

        // Get category name if category is selected
        $categoryName = $blog->category_name;
        if ($request->category_id) {
            $category = BlogCategory::find($request->category_id);
            $categoryName = $category ? $category->name : null;
        }

        $blog->update([
            'title' => $request->title,
            'slug' => Str::slug($request->title),
            'description' => $request->description,
            'content' => $request->content,
            'type' => $request->type ?? $blog->type ?? 'blog',
            'category' => $request->category_id,
            'category_name' => $categoryName,
            'category_id' => $request->category_id,
            'is_featured' => $request->is_featured ?? false,
            'thumbnail' => $thumbnailPath,
            'meta_title' => $request->meta_title,
            'meta_description' => $request->meta_description,
            'meta_keywords' => $request->meta_keywords,
            'status' => $request->status ?? $blog->status ?? 'Published',
            'active' => $request->active ?? true,
            'updated_by' => auth()->id(),
        ]);

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

    public function show(Blog $blog)
    {
        $blog->load('category', 'user');
        return view('admin.pages.blogs.show', compact('blog'));
    }

    public function destroy(Blog $blog)
    {
        try {
            // Delete thumbnail if exists
            if ($blog->thumbnail) {
                Storage::disk('public')->delete($blog->thumbnail);
            }
            
            $blog->delete();
            
            return redirect()->route('admin.blogs.index')
                ->with('success', 'Blog deleted successfully.');
        } catch (\Exception $e) {
            return redirect()->route('admin.blogs.index')
                ->with('error', 'Error deleting blog: ' . $e->getMessage());
        }
    }
} 