<?php

namespace App\Http\Controllers\Advocacy;

use App\Http\Controllers\Controller;
use App\Models\RHealthStory;
use App\Models\RCampaign;
use App\Http\Requests\Advocacy\StoreHealthStoryRequest;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\JsonResponse;

/**
 * Controller: RHealthStoryController
 * 
 * Handles health success/impact story submissions and moderation.
 * Public submission allowed (guests), moderation for managers.
 * 
 * @author SSHIA Development Team
 * @version 1.0.0
 */
class RHealthStoryController extends Controller
{
    /**
     * Display public stories masonry grid.
     */
    public function publicIndex(Request $request): View
    {
        $query = RHealthStory::published()
                           ->with(['campaign', 'user'])
                           ->orderByDesc('is_featured')
                           ->orderByDesc('published_at');

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

        // Filter by location
        if ($request->filled('location')) {
            $query->where('location', 'LIKE', "%{$request->location}%");
        }

        $stories = $query->paginate(12);

        // Campaigns for filter
        $campaigns = RCampaign::active()
                             ->orderBy('title')
                             ->get(['id', 'title']);

        return view('advocacy.stories.index', [
            'stories' => $stories,
            'campaigns' => $campaigns,
            'filters' => $request->only(['campaign', 'location']),
        ]);
    }

    /**
     * Display single story (public).
     */
    public function publicShow(RHealthStory $story): View
    {
        if (!$story->isPublished()) {
            abort(404);
        }

        // Increment views
        $story->incrementViews();

        $story->load(['campaign', 'user']);

        // Related stories
        $related = RHealthStory::published()
                              ->where('id', '!=', $story->id)
                              ->when($story->campaign_id, function ($q) use ($story) {
                                  $q->where('campaign_id', $story->campaign_id);
                              })
                              ->limit(3)
                              ->get();

        return view('advocacy.stories.show', [
            'story' => $story,
            'related' => $related,
        ]);
    }

    /**
     * Show story submission form (public).
     */
    public function create(): View
    {
        $campaigns = RCampaign::active()
                             ->orderBy('title')
                             ->get(['id', 'title']);

        return view('advocacy.stories.submit', [
            'campaigns' => $campaigns,
        ]);
    }

    /**
     * Store new story submission (public).
     */
    public function store(StoreHealthStoryRequest $request): mixed
    {
        try {
            $data = $request->validated();

            // Generate slug
            $data['slug'] = RHealthStory::generateSlug($data['title']);

            // Handle featured image
            if ($request->hasFile('featured_image')) {
                $data['featured_image'] = $request->file('featured_image')
                    ->store('stories/images', 'public');
            }

            // Handle gallery
            if ($request->hasFile('gallery')) {
                $gallery = [];
                foreach ($request->file('gallery') as $image) {
                    $gallery[] = $image->store('stories/gallery', 'public');
                }
                $data['gallery'] = $gallery;
            }

            // Generate excerpt if not provided
            if (empty($data['excerpt'])) {
                $data['excerpt'] = str()->limit(strip_tags($data['content']), 200);
            }

            $story = RHealthStory::create($data);

            $message = auth()->check() ?
                'Your story has been submitted and is pending review.' :
                'Thank you for sharing your story! It will be reviewed before publication.';

            return redirect()
                ->route('advocacy.public.stories.index')
                ->with('success', $message);

        } catch (\Exception $e) {
            return back()
                ->withInput()
                ->with('error', 'Failed to submit story: ' . $e->getMessage());
        }
    }

    /**
     * Display story moderation queue.
     */
    public function index(Request $request): View
    {
        abort_unless(auth()->user()->can('moderate stories'), 403);

        $query = RHealthStory::with(['campaign', 'user'])
                           ->orderByDesc('created_at');

        // Filter by status
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        } else {
            // Default to pending review
            $query->pendingReview();
        }

        $stories = $query->paginate(15);

        // Stats
        $stats = [
            'pending' => RHealthStory::pendingReview()->count(),
            'approved' => RHealthStory::whereIn('status', ['approved', 'published'])->count(),
            'rejected' => RHealthStory::where('status', 'rejected')->count(),
            'total' => RHealthStory::count(),
        ];

        return view('advocacy.stories.moderation', [
            'stories' => $stories,
            'stats' => $stats,
            'filters' => $request->only(['status']),
        ]);
    }

    /**
     * Display story for moderation.
     */
    public function show(RHealthStory $story): View
    {
        abort_unless(auth()->user()->can('moderate stories'), 403);

        $story->load(['campaign', 'user']);

        return view('advocacy.stories.moderate', [
            'story' => $story,
        ]);
    }

    /**
     * Approve story.
     */
    public function approve(Request $request, RHealthStory $story): mixed
    {
        abort_unless(auth()->user()->can('moderate stories'), 403);

        try {
            $story->approve(auth()->id());
            $story->publish();

            return redirect()
                ->route('advocacy.stories.moderation')
                ->with('success', 'Story approved and published!');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    /**
     * Reject story.
     */
    public function reject(Request $request, RHealthStory $story): mixed
    {
        abort_unless(auth()->user()->can('moderate stories'), 403);

        $request->validate([
            'rejection_reason' => 'required|string|max:1000',
        ]);

        try {
            $story->reject(auth()->id(), $request->rejection_reason);

            return redirect()
                ->route('advocacy.stories.moderation')
                ->with('success', 'Story rejected.');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    /**
     * Feature/unfeature story.
     */
    public function toggleFeatured(RHealthStory $story): JsonResponse
    {
        abort_unless(auth()->user()->can('feature stories'), 403);

        $story->update([
            'is_featured' => !$story->is_featured,
        ]);

        return response()->json([
            'success' => true,
            'is_featured' => $story->is_featured,
        ]);
    }

    /**
     * Share story (increment counter).
     */
    public function share(RHealthStory $story): JsonResponse
    {
        $story->incrementShares();

        return response()->json([
            'success' => true,
            'shares' => $story->shares_count,
        ]);
    }

    /**
     * Delete story.
     */
    public function destroy(RHealthStory $story): mixed
    {
        abort_unless(auth()->user()->can('delete stories'), 403);

        $story->delete();

        return redirect()
            ->route('advocacy.stories.moderation')
            ->with('success', 'Story deleted successfully!');
    }
}
