<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use App\Models\Announcement;
use App\Models\AnnouncementComment;
use App\Models\AnnouncementLike;
use App\Models\DiscoverPost;
use Illuminate\Support\Facades\Storage;

class AnnouncementController extends Controller
{
    private function getDemoAuthorIds(): array
    {
        return DiscoverPost::whereNull('user_id')->distinct()->pluck('demo_author_id')->filter(function ($v) {
            return is_numeric($v) && (int) $v >= 100000 && (int) $v <= 599999;
        })->map(fn ($v) => (int) $v)->sort()->values()->unique()->all();
    }

    public function index(Request $request): View
    {
        $posts = Announcement::withCount(['likes', 'comments'])->latest()->paginate(20)->withQueryString();
        $demoAuthorIds = $this->getDemoAuthorIds();
        return view('admin.announcements.index', [
            'posts' => $posts,
            'demoAuthorIds' => $demoAuthorIds,
            'pageTitle' => __('admin.nav.announcements'),
            'title' => 'Announcements',
        ]);
    }

    public function create(): View
    {
        return view('admin.announcements.create', [
            'pageTitle' => 'Add Announcement',
            'title' => 'Add Announcement',
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'content' => 'required|string|max:5000',
            'image' => 'nullable|image|max:5120',
        ]);
        $imagePath = null;
        if ($request->hasFile('image')) {
            $imagePath = $request->file('image')->store('announcements', 'public');
        }
        Announcement::create([
            'demo_author_id' => '0',
            'content' => $validated['content'],
            'image_path' => $imagePath,
        ]);
        return redirect()->route('admin.announcements')->with('success', 'Announcement created (AI Bot)');
    }

    public function edit($id): View
    {
        $post = Announcement::findOrFail($id);
        return view('admin.announcements.edit', [
            'post' => $post,
            'pageTitle' => 'Edit Announcement',
            'title' => 'Edit Announcement',
        ]);
    }

    public function update(Request $request, $id): RedirectResponse
    {
        $post = Announcement::findOrFail($id);
        $validated = $request->validate([
            'content' => 'required|string|max:5000',
            'image' => 'nullable|image|max:5120',
        ]);
        $imagePath = $post->image_path;
        if ($request->hasFile('image')) {
            if ($post->image_path && Storage::disk('public')->exists($post->image_path)) {
                Storage::disk('public')->delete($post->image_path);
            }
            $imagePath = $request->file('image')->store('announcements', 'public');
        }
        $post->update(['content' => $validated['content'], 'image_path' => $imagePath]);
        return redirect()->route('admin.announcements')->with('success', 'Announcement updated');
    }

    public function destroy($id): RedirectResponse
    {
        $post = Announcement::findOrFail($id);
        if ($post->image_path && Storage::disk('public')->exists($post->image_path)) {
            Storage::disk('public')->delete($post->image_path);
        }
        $post->delete();
        return redirect()->route('admin.announcements')->with('success', 'Announcement deleted');
    }

    public function storeComment(Request $request, $id): RedirectResponse
    {
        $validated = $request->validate([
            'body' => 'required|string|max:2000',
            'demo_author_id' => 'required|integer|min:100000|max:599999',
        ], [
            'demo_author_id.min' => 'Choose ID from Discover demo posts (100000–599999).',
            'demo_author_id.max' => 'ID must be below 600000.',
        ]);
        $announcement = Announcement::findOrFail($id);
        $authorDisplay = (string) $validated['demo_author_id'];
        AnnouncementComment::create([
            'announcement_id' => $announcement->id,
            'user_id' => null,
            'author_display' => $authorDisplay,
            'body' => $validated['body'],
        ]);
        return redirect()->back()->with('success', 'Comment added (User ' . $authorDisplay . ')');
    }

    public function storeLikes(Request $request, $id): RedirectResponse
    {
        $validated = $request->validate([
            'count' => 'required|integer|min:1|max:500',
        ], ['count.min' => 'Add at least 1 like.', 'count.max' => 'Maximum 500 at once.']);
        $announcement = Announcement::findOrFail($id);
        $count = (int) $validated['count'];
        for ($i = 0; $i < $count; $i++) {
            AnnouncementLike::create([
                'announcement_id' => $announcement->id,
                'user_id' => null,
            ]);
        }
        return redirect()->back()->with('success', $count . ' like(s) added.');
    }
}
