<?php

namespace App\Http\Controllers\Brand;

use App\Http\Controllers\Controller;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Http\Request;

class CampaignController extends Controller
{
    /**
     * Display a listing of campaigns
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $campaigns = Campaign::where('brand_id', auth()->user()->brand_id)
            ->withCount('creators')
            ->orderBy('created_at', 'desc')
            ->paginate(20);
            
        return view('brand.campaigns.index', compact('campaigns'));
    }
    
    /**
     * Show the form for creating a new campaign
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        // Get creators for the campaign invitation
        $creators = User::whereHas('roles', function ($q) {
            $q->where('name', 'creator');
        })->get();
        
        return view('brand.campaigns.create', compact('creators'));
    }
    
    /**
     * Display the specified campaign
     *
     * @param  \App\Models\Campaign  $campaign
     * @return \Illuminate\Http\Response
     */
    public function show(Campaign $campaign)
    {
        // Ensure the campaign belongs to the authenticated brand
        if ($campaign->brand_id !== auth()->user()->brand_id) {
            abort(403);
        }
        
        $campaign->load('creators');
        
        return view('brand.campaigns.show', compact('campaign'));
    }
    
    /**
     * Store a newly created campaign
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'objective' => 'nullable|string',
            'deliverables' => 'nullable|string',
            'audience' => 'nullable|string',
            'budget' => 'nullable|numeric|min:0',
            'currency' => 'nullable|string|max:3',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after:start_date',
            'creators' => 'nullable|array',
            'creators.*' => 'exists:users,id',
        ]);
        
        // Create the campaign
        $campaign = new Campaign([
            'brand_id' => auth()->user()->brand_id,
            'name' => $validated['name'],
            'description' => $validated['description'] ?? null,
            'objective' => $validated['objective'] ?? null,
            'deliverables' => $validated['deliverables'] ?? null,
            'audience' => $validated['audience'] ?? null,
            'budget' => $validated['budget'] ?? null,
            'currency' => $validated['currency'] ?? 'USD',
            'start_date' => $validated['start_date'] ?? null,
            'end_date' => $validated['end_date'] ?? null,
            'status' => 'draft',
            'created_by' => auth()->id(),
        ]);
        
        $campaign->save();
        
        // Attach creators to the campaign
        if (!empty($validated['creators'])) {
            $campaign->creators()->attach($validated['creators'], [
                'invited_by' => auth()->id(),
                'status' => 'invited',
                'invitation_sent_at' => now()
            ]);
        }
        
        return redirect()->route('brand.campaigns.show', $campaign)->with('success', 'Campaign created successfully!');
    }
    
    /**
     * Update the specified campaign
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Campaign  $campaign
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Campaign $campaign)
    {
        // Ensure the campaign belongs to the authenticated brand
        if ($campaign->brand_id !== auth()->user()->brand_id) {
            abort(403);
        }
        
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'objective' => 'nullable|string',
            'deliverables' => 'nullable|string',
            'audience' => 'nullable|string',
            'budget' => 'nullable|numeric|min:0',
            'currency' => 'nullable|string|max:3',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after:start_date',
            'status' => 'required|in:draft,active,paused,completed,cancelled',
        ]);
        
        $campaign->update($validated);
        
        return redirect()->back()->with('success', 'Campaign updated successfully!');
    }
    
    /**
     * Redirect to the campaign planner
     *
     * @param  \App\Models\Campaign  $campaign
     * @return \Illuminate\Http\Response
     */
    public function plan(Campaign $campaign)
    {
        // Ensure the campaign belongs to the authenticated brand
        if ($campaign->brand_id !== auth()->user()->brand_id) {
            abort(403);
        }
        
        return redirect()->route('brand.campaigns.planner.show', $campaign);
    }
}