<?php

namespace App\Http\Controllers\Brand;

use App\Http\Controllers\Controller;
use App\Models\Campaign;
use App\Models\CampaignMilestone;
use App\Models\CampaignBudgetAllocation;
use App\Models\User;
use App\Jobs\EnqueueAiTaskJob;
use Illuminate\Http\Request;

class CampaignPlannerController extends Controller
{
    /**
     * Show the campaign planner view
     *
     * @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);
        }
        
        // Load related data
        $campaign->load(['milestones', 'budgetAllocations', 'creators']);
        
        return view('brand.campaigns.planner', compact('campaign'));
    }
    
    /**
     * Store a new milestone for the campaign
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Campaign  $campaign
     * @return \Illuminate\Http\Response
     */
    public function storeMilestone(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',
            'due_date' => 'nullable|date',
            'budget_allocation' => 'nullable|numeric|min:0',
            'assigned_creator_id' => 'nullable|exists:users,id',
            'status' => 'required|in:pending,in_progress,completed',
        ]);
        
        $milestone = new CampaignMilestone([
            'campaign_id' => $campaign->id,
            'name' => $validated['name'],
            'description' => $validated['description'] ?? null,
            'due_date' => $validated['due_date'] ?? null,
            'budget_allocation' => $validated['budget_allocation'] ?? null,
            'assigned_creator_id' => $validated['assigned_creator_id'] ?? null,
            'status' => $validated['status'],
        ]);
        
        $milestone->save();
        
        return response()->json(['success' => true, 'milestone' => $milestone]);
    }
    
    /**
     * Update an existing milestone
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\CampaignMilestone  $milestone
     * @return \Illuminate\Http\Response
     */
    public function updateMilestone(Request $request, CampaignMilestone $milestone)
    {
        // Ensure the milestone belongs to the authenticated brand
        if ($milestone->campaign->brand_id !== auth()->user()->brand_id) {
            abort(403);
        }
        
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'due_date' => 'nullable|date',
            'budget_allocation' => 'nullable|numeric|min:0',
            'assigned_creator_id' => 'nullable|exists:users,id',
            'status' => 'required|in:pending,in_progress,completed',
        ]);
        
        $milestone->update($validated);
        
        return response()->json(['success' => true, 'milestone' => $milestone]);
    }
    
    /**
     * Delete a milestone
     *
     * @param  \App\Models\CampaignMilestone  $milestone
     * @return \Illuminate\Http\Response
     */
    public function deleteMilestone(CampaignMilestone $milestone)
    {
        // Ensure the milestone belongs to the authenticated brand
        if ($milestone->campaign->brand_id !== auth()->user()->brand_id) {
            abort(403);
        }
        
        $milestone->delete();
        
        return response()->json(['success' => true]);
    }
    
    /**
     * Store a new budget allocation for the campaign
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Campaign  $campaign
     * @return \Illuminate\Http\Response
     */
    public function storeBudgetAllocation(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([
            'category' => 'required|string|max:255',
            'amount' => 'required|numeric|min:0',
            'percentage' => 'nullable|numeric|min:0|max:100',
            'notes' => 'nullable|string',
        ]);
        
        $allocation = new CampaignBudgetAllocation([
            'campaign_id' => $campaign->id,
            'category' => $validated['category'],
            'amount' => $validated['amount'],
            'percentage' => $validated['percentage'] ?? null,
            'notes' => $validated['notes'] ?? null,
        ]);
        
        $allocation->save();
        
        return response()->json(['success' => true, 'allocation' => $allocation]);
    }
    
    /**
     * Update an existing budget allocation
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\CampaignBudgetAllocation  $allocation
     * @return \Illuminate\Http\Response
     */
    public function updateBudgetAllocation(Request $request, CampaignBudgetAllocation $allocation)
    {
        // Ensure the allocation belongs to the authenticated brand
        if ($allocation->campaign->brand_id !== auth()->user()->brand_id) {
            abort(403);
        }
        
        $validated = $request->validate([
            'category' => 'required|string|max:255',
            'amount' => 'required|numeric|min:0',
            'percentage' => 'nullable|numeric|min:0|max:100',
            'notes' => 'nullable|string',
        ]);
        
        $allocation->update($validated);
        
        return response()->json(['success' => true, 'allocation' => $allocation]);
    }
    
    /**
     * Delete a budget allocation
     *
     * @param  \App\Models\CampaignBudgetAllocation  $allocation
     * @return \Illuminate\Http\Response
     */
    public function deleteBudgetAllocation(CampaignBudgetAllocation $allocation)
    {
        // Ensure the allocation belongs to the authenticated brand
        if ($allocation->campaign->brand_id !== auth()->user()->brand_id) {
            abort(403);
        }
        
        $allocation->delete();
        
        return response()->json(['success' => true]);
    }
    
    /**
     * Request AI planning suggestions for the campaign
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Campaign  $campaign
     * @return \Illuminate\Http\Response
     */
    public function requestAiPlanning(Request $request, Campaign $campaign)
    {
        // Ensure the campaign belongs to the authenticated brand
        if ($campaign->brand_id !== auth()->user()->brand_id) {
            abort(403);
        }
        
        // Prepare the payload for the AI task
        $payload = [
            'campaign_id' => $campaign->id,
            'name' => $campaign->name,
            'description' => $campaign->description,
            'objective' => $campaign->objective,
            'deliverables' => $campaign->deliverables,
            'audience' => $campaign->audience,
            'start_date' => $campaign->start_date,
            'end_date' => $campaign->end_date,
            'budget' => $campaign->budget,
            'currency' => $campaign->currency,
        ];
        
        // Dispatch the AI task job
        EnqueueAiTaskJob::dispatch('campaign_planning', auth()->user()->brand_id, null, $payload);
        
        // For demonstration purposes, let's also simulate the AI response
        // In a real implementation, this would be handled by an external AI processing system
        $aiTask = \App\Models\AiTask::where('type', 'campaign_planning')
            ->where('brand_id', auth()->user()->brand_id)
            ->orderBy('created_at', 'desc')
            ->first();
            
        if ($aiTask) {
            // Simulate AI processing completion
            $aiTask->update([
                'status' => 'completed',
                'result_text' => 'AI planning suggestions generated successfully',
                'result_meta' => [
                    'campaign_id' => $campaign->id,
                    'milestones' => [
                        [
                            'name' => 'Campaign Kickoff',
                            'description' => 'Initial planning and team alignment',
                            'due_date' => now()->addDays(7)->format('Y-m-d'),
                            'status' => 'pending',
                        ],
                        [
                            'name' => 'Content Creation',
                            'description' => 'Create content for all deliverables',
                            'due_date' => now()->addDays(21)->format('Y-m-d'),
                            'status' => 'pending',
                        ],
                        [
                            'name' => 'Content Review',
                            'description' => 'Review and approve all content',
                            'due_date' => now()->addDays(28)->format('Y-m-d'),
                            'status' => 'pending',
                        ],
                        [
                            'name' => 'Campaign Launch',
                            'description' => 'Launch the campaign on all platforms',
                            'due_date' => now()->addDays(35)->format('Y-m-d'),
                            'status' => 'pending',
                        ],
                        [
                            'name' => 'Performance Analysis',
                            'description' => 'Analyze campaign performance and prepare report',
                            'due_date' => now()->addDays(42)->format('Y-m-d'),
                            'status' => 'pending',
                        ],
                    ],
                    'budget_allocations' => [
                        [
                            'category' => 'Content Creation',
                            'amount' => $campaign->budget * 0.4,
                            'percentage' => 40,
                            'notes' => 'For content creation and editing',
                        ],
                        [
                            'category' => 'Influencer Fees',
                            'amount' => $campaign->budget * 0.3,
                            'percentage' => 30,
                            'notes' => 'For influencer collaboration fees',
                        ],
                        [
                            'category' => 'Advertising',
                            'amount' => $campaign->budget * 0.2,
                            'percentage' => 20,
                            'notes' => 'For paid advertising',
                        ],
                        [
                            'category' => 'Contingency',
                            'amount' => $campaign->budget * 0.1,
                            'percentage' => 10,
                            'notes' => 'For unexpected expenses',
                        ],
                    ],
                ],
            ]);
            
            // Dispatch the job to process the AI planning results
            \App\Jobs\ProcessCampaignPlanningAiJob::dispatch($aiTask);
        }
        
        return response()->json(['success' => true, 'message' => 'AI planning request submitted successfully']);
    }
    
    /**
     * Export campaign as proposal/contract
     *
     * @param  \App\Models\Campaign  $campaign
     * @return \Illuminate\Http\Response
     */
    public function exportCampaign(Campaign $campaign)
    {
        // Ensure the campaign belongs to the authenticated brand
        if ($campaign->brand_id !== auth()->user()->brand_id) {
            abort(403);
        }
        
        // For now, we'll just return a simple response
        // In a real implementation, this would generate a PDF or document
        return response()->json(['success' => true, 'message' => 'Campaign exported successfully']);
    }
}
