<?php

namespace App\Http\Controllers\Admin;

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

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

        // Filter by category
        if ($request->filled('category')) {
            $query->where('blog_category_id', $request->category);
        }

        // Filter by status
        if ($request->filled('status')) {
            if ($request->status === 'published') {
                $query->published();
            } elseif ($request->status === 'draft') {
                $query->where('is_published', false);
            }
        }

        // Search by title
        if ($request->filled('search')) {
            $query->where('title', 'like', '%' . $request->search . '%');
        }

        $blogs = $query->orderBy('created_at', 'desc')->paginate(20);
        $categories = BlogCategory::active()->ordered()->get();

        return view('admin.blogs.index', compact('blogs', 'categories'));
    }

    public function create()
    {
        $categories = BlogCategory::active()->ordered()->get();
        
        // Get all plans (not filtering by status to show all options)
        $plans = UserPlan::all();
        
        // Get all packages
        $packages = AdPackage::all();
        
        // Get available ad units grouped by type
        $adUnits = \DB::table('ad_units')->get()->groupBy('type');
        
        // Get default ad units (first of each type)
        $defaultBanner = \DB::table('ad_units')->where('type', 'banner')->first();
        $defaultNative = \DB::table('ad_units')->where('type', 'native')->first();
        $defaultInterstitial = \DB::table('ad_units')->where('type', 'interstitial')->first();

        return view('admin.blogs.create', compact(
            'categories', 
            'plans', 
            'packages', 
            'adUnits',
            'defaultBanner',
            'defaultNative',
            'defaultInterstitial'
        ));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:blogs,slug',
            'excerpt' => 'nullable|string',
            'content' => 'required|string',
            'featured_image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'blog_category_id' => 'nullable|exists:blog_categories,id',
            'user_plan_id' => 'nullable|exists:user_plans,id',
            'package_id' => 'nullable|exists:ad_packages,id',
            'is_published' => 'boolean',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string',
            'meta_keywords' => 'nullable|string',
            'ad_unit_top_banner_id' => 'nullable|integer',
            'ad_unit_in_content_native_id' => 'nullable|integer',
            'ad_unit_bottom_interstitial_id' => 'nullable|integer',
        ]);

        // Auto-generate slug if not provided
        if (empty($validated['slug'])) {
            $validated['slug'] = Str::slug($validated['title']);
        }

        // Handle featured image upload
        if ($request->hasFile('featured_image')) {
            $path = $request->file('featured_image')->store('blogs', 'public');
            $validated['featured_image'] = $path;
        }

        // Set author
        $validated['author_id'] = Auth::id();

        // Set published status
        $validated['is_published'] = $request->has('is_published');
        if ($validated['is_published'] && empty($validated['published_at'])) {
            $validated['published_at'] = now();
        }
        
        // Set default ad units if not specified
        if (empty($validated['ad_unit_top_banner_id'])) {
            $defaultBanner = \DB::table('ad_units')->where('type', 'banner')->first();
            if ($defaultBanner) {
                $validated['ad_unit_top_banner_id'] = $defaultBanner->id;
            }
        }
        
        if (empty($validated['ad_unit_in_content_native_id'])) {
            $defaultNative = \DB::table('ad_units')->where('type', 'native')->first();
            if ($defaultNative) {
                $validated['ad_unit_in_content_native_id'] = $defaultNative->id;
            }
        }
        
        if (empty($validated['ad_unit_bottom_interstitial_id'])) {
            $defaultInterstitial = \DB::table('ad_units')->where('type', 'interstitial')->first();
            if ($defaultInterstitial) {
                $validated['ad_unit_bottom_interstitial_id'] = $defaultInterstitial->id;
            }
        }

        Blog::create($validated);

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

    public function edit(Blog $blog)
    {
        $categories = BlogCategory::active()->ordered()->get();
        
        // Get all plans
        $plans = UserPlan::all();
        
        // Get all packages
        $packages = AdPackage::all();
        
        // Get available ad units grouped by type
        $adUnits = \DB::table('ad_units')->get()->groupBy('type');
        
        // Get default ad units (first of each type)
        $defaultBanner = \DB::table('ad_units')->where('type', 'banner')->first();
        $defaultNative = \DB::table('ad_units')->where('type', 'native')->first();
        $defaultInterstitial = \DB::table('ad_units')->where('type', 'interstitial')->first();

        return view('admin.blogs.edit', compact(
            'blog',
            'categories', 
            'plans', 
            'packages', 
            'adUnits',
            'defaultBanner',
            'defaultNative',
            'defaultInterstitial'
        ));
    }

    public function update(Request $request, Blog $blog)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'required|string|max:255|unique:blogs,slug,' . $blog->id,
            'excerpt' => 'nullable|string',
            'content' => 'required|string',
            'featured_image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'blog_category_id' => 'nullable|exists:blog_categories,id',
            'user_plan_id' => 'nullable|exists:user_plans,id',
            'package_id' => 'nullable|exists:ad_packages,id',
            'is_published' => 'boolean',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string',
            'meta_keywords' => 'nullable|string',
            'ad_unit_top_banner_id' => 'nullable|integer',
            'ad_unit_in_content_native_id' => 'nullable|integer',
            'ad_unit_bottom_interstitial_id' => 'nullable|integer',
        ]);

        // Handle featured image upload
        if ($request->hasFile('featured_image')) {
            // Delete old image
            if ($blog->featured_image) {
                Storage::disk('public')->delete($blog->featured_image);
            }
            $path = $request->file('featured_image')->store('blogs', 'public');
            $validated['featured_image'] = $path;
        }

        // Set published status
        $validated['is_published'] = $request->has('is_published');
        if ($validated['is_published'] && !$blog->published_at) {
            $validated['published_at'] = now();
        }

        $blog->update($validated);

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

    public function destroy(Blog $blog)
    {
        // Delete featured image
        if ($blog->featured_image) {
            Storage::disk('public')->delete($blog->featured_image);
        }

        $blog->delete();

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

    /**
     * Handle AJAX image upload for rich text editor
     */
    public function uploadImage(Request $request)
    {
        $request->validate([
            'file' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048'
        ]);

        if ($request->hasFile('file')) {
            $path = $request->file('file')->store('blogs/content', 'public');
            $url = Storage::url($path);

            return response()->json([
                'location' => asset('storage/' . $path)
            ]);
        }

        return response()->json(['error' => 'Upload failed'], 400);
    }
}
