<?php

namespace App\Http\Controllers\Employee;

use App\Http\Controllers\Controller;
use App\Models\BlogArticle;
use App\Models\BlogCategory;
use App\Services\NotificationService;
use App\Support\HtmlSanitizer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class BlogArticleController extends Controller
{
    public function index(Request $request)
    {
        $articles = BlogArticle::query()
            ->with('category')
            ->where('author_id', auth()->id())
            ->when($request->status, fn ($q) => $q->where('status', $request->status))
            ->when($request->search, fn ($q) => $q->where('title', 'like', '%' . $request->search . '%'))
            ->latest()
            ->paginate(15)
            ->withQueryString();

        return view('employee.blog-articles.index', compact('articles'));
    }

    public function create()
    {
        $categories = BlogCategory::active()->ordered()->get();

        return view('employee.blog-articles.create', compact('categories'));
    }

    public function store(Request $request)
    {
        $data = $this->validatedData($request);
        $data['content'] = app(HtmlSanitizer::class)->sanitize($data['content']);
        $data['author_id'] = auth()->id();
        $this->applyEmployeeStatus($data, $request);

        if ($request->hasFile('featured_image')) {
            $data['featured_image'] = $request->file('featured_image')->store('blogs', 'public');
        }

        $article = BlogArticle::create($data);

        $this->notifyAdminsIfPending($article, false);

        return redirect()->route('employee.blog-articles.index')->with('success', 'Article saved successfully.');
    }

    public function edit(BlogArticle $blogArticle)
    {
        abort_unless($blogArticle->author_id === auth()->id(), 403);

        $categories = BlogCategory::active()->ordered()->get();

        return view('employee.blog-articles.edit', compact('blogArticle', 'categories'));
    }

    public function update(Request $request, BlogArticle $blogArticle)
    {
        abort_unless($blogArticle->author_id === auth()->id(), 403);

        $data = $this->validatedData($request, $blogArticle);
        $data['content'] = app(HtmlSanitizer::class)->sanitize($data['content']);
        $this->applyEmployeeStatus($data, $request, $blogArticle);

        if ($request->hasFile('featured_image')) {
            if ($blogArticle->featured_image) {
                Storage::disk('public')->delete($blogArticle->featured_image);
            }
            $data['featured_image'] = $request->file('featured_image')->store('blogs', 'public');
        }

        $blogArticle->update($data);
        $blogArticle->refresh();

        $this->notifyAdminsIfPending($blogArticle, true);

        return redirect()->route('employee.blog-articles.index')->with('success', 'Article updated successfully.');
    }

    public function destroy(BlogArticle $blogArticle)
    {
        abort_unless($blogArticle->author_id === auth()->id(), 403);

        if ($blogArticle->featured_image) {
            Storage::disk('public')->delete($blogArticle->featured_image);
        }

        $blogArticle->delete();

        return redirect()->route('employee.blog-articles.index')->with('success', 'Article deleted successfully.');
    }

    private function validatedData(Request $request, ?BlogArticle $article = null): array
    {
        return $request->validate([
            'blog_category_id' => 'required|exists:blog_categories,id',
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:blog_articles,slug,' . ($article?->id ?: 'NULL') . ',id',
            'excerpt' => 'nullable|string|max:500',
            'content' => 'required|string',
            'featured_image' => 'nullable|image|mimes:jpg,jpeg,png,webp|max:5120',
            'seo_title' => 'nullable|string|max:255',
            'seo_description' => 'nullable|string|max:320',
        ]);
    }

    private function applyEmployeeStatus(array &$data, Request $request, ?BlogArticle $existing = null): void
    {
        $action = $request->input('submit_action', 'pending');
        $status = $action === 'draft' ? 'draft' : 'pending';

        if ($existing && $existing->status === 'approved' && $status !== 'draft') {
            $status = 'pending';
        }

        $data['status'] = $status;
        $data['published_at'] = null;
        $data['approved_by'] = null;
        $data['review_note'] = null;
        $data['is_active'] = true;
        $data['is_featured'] = false;
        $data['sort_order'] = $existing?->sort_order ?? 0;
    }

    private function notifyAdminsIfPending(BlogArticle $article, bool $isUpdate): void
    {
        if ($article->status !== 'pending') {
            return;
        }

        $actor = auth()->user();
        $actionText = $isUpdate ? 'updated and submitted' : 'submitted';

        app(NotificationService::class)->notifyAdmins(
            type: 'blog_article_pending_review',
            title: 'Blog Waiting For Review',
            message: "{$actor->name} {$actionText} the article \"{$article->title}\" for approval.",
            actionUrl: route('admin.blog-articles.edit', $article),
            sendEmail: true,
            emailSubject: 'A blog article is waiting for review'
        );
    }
}
