<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Blog;
use App\Models\Category;
use App\Models\User;
use Illuminate\Http\Request;

class BlogController extends Controller
{
    public function index()
    {
        $blogs = Blog::with('author', 'category')->latest()->paginate(20);
        return view('admin.blogs.index', compact('blogs'));
    }

    public function create()
    {
        $blog = new Blog();
        $categories = $this->categoryOptions();
        $authors = User::orderBy('name')->get(['id', 'name', 'email', 'role']);
        return view('admin.blogs.form', compact('blog', 'categories', 'authors'));
    }

    public function destroy(Blog $blog)
    {
        if ($blog->featured_image) {
            @unlink(public_path('uploads/blogs/' . $blog->featured_image));
        }
        // Decrement reseller's blog count
        if ($blog->author && $blog->author->isReseller() && $blog->author->blogs_used > 0) {
            $blog->author->decrement('blogs_used');
        }
        $blog->delete();
        return back()->with('success', 'Blog deleted.');
    }

    public function edit(Blog $blog)
    {
        $categories = $this->categoryOptions();
        $authors = User::orderBy('name')->get(['id', 'name', 'email', 'role']);
        return view('admin.blogs.form', compact('blog', 'categories', 'authors'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'user_id'      => 'required|exists:users,id',
            'title'        => 'required|string|max:255',
            'category_id'  => 'nullable|exists:categories,id',
            'excerpt'      => 'nullable|string|max:500',
            'content'      => 'required|string|min:20',
            'language'     => 'nullable|string|max:10',
            'tags'         => 'nullable|string|max:1000',
            'status'       => 'required|in:draft,published',
        ]);

        Blog::create([
            'user_id'      => (int) $data['user_id'],
            'title'        => $data['title'],
            'category_id'  => $data['category_id'] ?? null,
            'excerpt'      => $data['excerpt'] ?? null,
            'content'      => $data['content'],
            'language'     => $data['language'] ?? 'en',
            'tags'         => $this->parseTags($data['tags'] ?? ''),
            'status'       => $data['status'],
            'published_at' => $data['status'] === 'published' ? now() : null,
        ]);

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

    public function update(Request $request, Blog $blog)
    {
        $data = $request->validate([
            'user_id'      => 'required|exists:users,id',
            'title'       => 'required|string|max:255',
            'category_id' => 'nullable|exists:categories,id',
            'excerpt'     => 'nullable|string|max:500',
            'content'     => 'required|string|min:20',
            'language'    => 'nullable|string|max:10',
            'tags'        => 'nullable|string|max:1000',
            'status'      => 'required|in:draft,published',
        ]);

        $blog->update([
            'user_id'      => (int) $data['user_id'],
            'title'       => $data['title'],
            'category_id' => $data['category_id'] ?? null,
            'excerpt'     => $data['excerpt'] ?? null,
            'content'     => $data['content'],
            'language'    => $data['language'] ?? 'en',
            'tags'        => $this->parseTags($data['tags'] ?? ''),
            'status'      => $data['status'],
            'published_at'=> $data['status'] === 'published' ? ($blog->published_at ?? now()) : null,
        ]);

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

    protected function parseTags(?string $input): array
    {
        if (!$input) return [];
        return array_values(array_filter(array_map('trim', explode(',', $input))));
    }

    protected function categoryOptions(): array
    {
        return $this->flatten(Category::tree());
    }

    protected function flatten($cats, int $depth = 0): array
    {
        $out = [];
        foreach ($cats as $c) {
            $out[] = ['id' => $c->id, 'name' => str_repeat('— ', $depth) . $c->name];
            if ($c->relationLoaded('childrenRecursive')) {
                $out = array_merge($out, $this->flatten($c->childrenRecursive, $depth + 1));
            }
        }
        return $out;
    }
}
