<?php

namespace App\Http\Controllers\Advocacy;

use App\Http\Controllers\Controller;
use App\Models\RCampaign;
use App\Models\RHealthStory;
use App\Models\RPoll;
use App\Services\PollService;
use App\Http\Requests\Advocacy\StoreCampaignRequest;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\JsonResponse;

/**
 * Controller: RCampaignController
 * 
 * Handles health advocacy campaign management.
 * Health Marketer and Manager access for management.
 * Public access for viewing.
 * 
 * @author SSHIA Development Team
 * @version 1.0.0
 */
class RCampaignController extends Controller
{
    /**
     * Display public advocacy landing page.
     * Public access - Site Layout
     */
    public function publicIndex(): View
    {
        // Active campaigns
        $campaigns = RCampaign::active()
                             ->with(['user', 'stories'])
                             ->orderByDesc('is_featured')
                             ->orderByDesc('start_date')
                             ->paginate(12);

        // Featured campaign for hero
        $featuredCampaign = RCampaign::active()
                                    ->featured()
                                    ->with(['stories', 'polls'])
                                    ->first();

        // Success stories masonry
        $stories = RHealthStory::published()
                              ->with(['campaign', 'user'])
                              ->orderByDesc('is_featured')
                              ->orderByDesc('published_at')
                              ->limit(6)
                              ->get();

        // Active polls
        $activePolls = app(PollService::class)->getActivePolls('sidebar');

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

    /**
     * Display single campaign (public).
     */
    public function publicShow(RCampaign $campaign): View
    {
        if ($campaign->status !== RCampaign::STATUS_ACTIVE) {
            abort(404);
        }

        $campaign->load(['stories' => function ($q) {
            $q->published()->latest()->limit(10);
        }, 'polls' => function ($q) {
            $q->active();
        }]);

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

        // Analytics for public view
        $analytics = [
            'views'           => $campaign->views_count,
            'stories'         => $campaign->stories()->published()->count(),
            'pending_stories' => $campaign->stories()->pendingReview()->count(),
            'polls'           => $campaign->polls()->active()->count(),
        ];

        return view('advocacy.campaigns.public-show', [
            'campaign'  => $campaign,
            'analytics' => $analytics,
        ]);
    }

    /**
     * Display campaign management dashboard.
     */
    public function index(Request $request): View
    {
        abort_unless(auth()->user()->can('view campaigns'), 403);

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

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

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

        // Statistics
        $stats = [
            'total' => RCampaign::count(),
            'active' => RCampaign::active()->count(),
            'draft' => RCampaign::where('status', 'draft')->count(),
            'completed' => RCampaign::where('status', 'completed')->count(),
        ];

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

    /**
     * Show form for creating campaign.
     */
    public function create(): View
    {
        abort_unless(auth()->user()->can('create campaigns'), 403);

        return view('advocacy.campaigns.create');
    }

    /**
     * Store new campaign.
     */
    public function store(StoreCampaignRequest $request): mixed
    {
        abort_unless(auth()->user()->can('create campaigns'), 403);

        try {
            $data = $request->validated();
            $data['user_id'] = auth()->id();
            $data['slug'] = RCampaign::generateSlug($data['title']);

            // Handle banner image upload
            if ($request->hasFile('banner_image')) {
                $data['banner_image'] = $request->file('banner_image')
                    ->store('campaigns/banners', 'public');
            }

            // Handle thumbnail upload
            if ($request->hasFile('thumbnail')) {
                $data['thumbnail'] = $request->file('thumbnail')
                    ->store('campaigns/thumbnails', 'public');
            }

            $campaign = RCampaign::create($data);

            return redirect()
                ->route('advocacy.campaigns.index')
                ->with('success', 'Campaign created successfully!');

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

    /**
     * Display campaign details (dashboard).
     */
    public function show(RCampaign $campaign): View
    {
        abort_unless(auth()->user()->can('view campaigns'), 403);

        $campaign->load(['stories', 'polls.options']);

        // Get analytics
        $analytics = [
            'views' => $campaign->views_count,
            'stories' => $campaign->stories()->published()->count(),
            'pending_stories' => $campaign->stories()->pendingReview()->count(),
            'polls' => $campaign->polls()->active()->count(),
        ];

        return view('advocacy.campaigns.show', [
            'campaign' => $campaign,
            'analytics' => $analytics,
        ]);
    }

    /**
     * Show form for editing campaign.
     */
    public function edit(RCampaign $campaign): View
    {
        abort_unless(auth()->user()->can('edit campaigns'), 403);

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

    /**
     * Update campaign.
     */
    public function update(StoreCampaignRequest $request, RCampaign $campaign): mixed
    {
        abort_unless(auth()->user()->can('edit campaigns'), 403);

        try {
            $data = $request->validated();

            // Handle banner image upload
            if ($request->hasFile('banner_image')) {
                $data['banner_image'] = $request->file('banner_image')
                    ->store('campaigns/banners', 'public');
            }

            // Handle thumbnail upload
            if ($request->hasFile('thumbnail')) {
                $data['thumbnail'] = $request->file('thumbnail')
                    ->store('campaigns/thumbnails', 'public');
            }

            $campaign->update($data);

            return redirect()
                ->route('advocacy.campaigns.show', $campaign)
                ->with('success', 'Campaign updated successfully!');

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

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

        $campaign->delete();

        return redirect()
            ->route('advocacy.campaigns.index')
            ->with('success', 'Campaign deleted successfully!');
    }

    /**
     * Toggle campaign status.
     */
    public function toggleStatus(RCampaign $campaign): JsonResponse
    {
        abort_unless(auth()->user()->can('edit campaigns'), 403);

        $newStatus = match($campaign->status) {
            'draft' => 'active',
            'active' => 'paused',
            'paused' => 'active',
            default => 'active',
        };

        $campaign->update(['status' => $newStatus]);

        return response()->json([
            'success' => true,
            'status' => $newStatus,
            'message' => "Campaign status changed to {$newStatus}.",
        ]);
    }

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

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

        return response()->json([
            'success' => true,
            'is_featured' => $campaign->is_featured,
            'message' => $campaign->is_featured ? 
                'Campaign featured!' : 
                'Campaign unfeatured.',
        ]);
    }
}
