<?php

namespace App\Http\Controllers\Brand;

use App\Http\Controllers\Controller;
use App\Jobs\EnqueueAiTaskJob;
use App\Jobs\SyncBrandSocialAccounts;
use App\Models\AiTask;
use App\Models\Brand;
use App\Models\SocialAccount;
use App\Models\SocialAggregate;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function index()
    {
        // Guard clause for brand not found
        $brand = auth()->user()->brand;
        if (!$brand) {
            // Instead of redirecting to dashboard (which causes a loop), show an error page
            return response()->view('errors.brand-not-found', [], 404);
        }
        
        // Get KPI data
        $kpis = $this->getKpiData($brand->id);
        
        // Get connection status
        $connections = SocialAccount::where('brand_id', $brand->id)
            ->orderBy('provider')
            ->get();
            
        // Get recent activity
        $recentActivity = \App\Models\SocialPost::whereHas('socialAccount', function ($query) use ($brand) {
                $query->where('brand_id', $brand->id);
            })
            ->orderBy('published_at', 'desc')
            ->limit(10)
            ->get();

        // Get AI tasks for this brand
        $aiTasks = AiTask::where('brand_id', $brand->id)
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();

        return view('brand.dashboard', compact('kpis', 'connections', 'recentActivity', 'aiTasks'));
    }
    
    /**
     * Get KPI data for the dashboard.
     *
     * @param int $brandId
     * @return array
     */
    protected function getKpiData($brandId)
    {
        // Get overall aggregates
        $followers = SocialAggregate::where('brand_id', $brandId)
            ->where('key', 'total_followers')
            ->first();
            
        $posts = SocialAggregate::where('brand_id', $brandId)
            ->where('key', 'total_posts')
            ->first();
            
        $views = SocialAggregate::where('brand_id', $brandId)
            ->where('key', 'total_views')
            ->first();
            
        $engagement = SocialAggregate::where('brand_id', $brandId)
            ->where('key', 'engagement_rate')
            ->first();

        return [
            'followers' => $followers ? $followers->getNumericValue() : 0,
            'followers_change' => $followers ? $followers->getChangePercentage() : 0,
            'followers_positive' => $followers ? $followers->isChangePositive() : null,
            
            'posts' => $posts ? $posts->getNumericValue() : 0,
            'posts_change' => $posts ? $posts->getChangePercentage() : 0,
            'posts_positive' => $posts ? $posts->isChangePositive() : null,
            
            'views' => $views ? $views->getNumericValue() : 0,
            'views_change' => $views ? $views->getChangePercentage() : 0,
            'views_positive' => $views ? $views->isChangePositive() : null,
            
            'engagement' => $engagement ? $engagement->getNumericValue() : 0,
            'engagement_change' => $engagement ? $engagement->getChangePercentage() : 0,
            'engagement_positive' => $engagement ? $engagement->isChangePositive() : null,
        ];
    }
    
    /**
     * Get stats data for charts.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function stats()
    {
        // Guard clause for brand not found
        $brand = auth()->user()->brand;
        if (!$brand) {
            return response()->json(['error' => 'Brand not found'], 404);
        }
        
        // Get daily views for the last 14 days
        $viewsData = SocialAggregate::where('brand_id', $brand->id)
            ->where('key', 'daily_views')
            ->where('computed_at', '>=', now()->subDays(14))
            ->orderBy('computed_at')
            ->get();
            
        // Format data for chart
        $labels = [];
        $data = [];
        
        foreach ($viewsData as $item) {
            $labels[] = $item->computed_at->format('M j');
            $data[] = $item->getNumericValue();
        }

        return response()->json([
            'labels' => $labels,
            'data' => $data,
        ]);
    }
    
    /**
     * Trigger a sync for the current brand.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function syncNow(Request $request)
    {
        // Guard clause for brand not found
        $brand = auth()->user()->brand;
        if (!$brand) {
            // Instead of redirecting to dashboard (which causes a loop), show an error page
            return response()->view('errors.brand-not-found', [], 404);
        }
        
        // Dispatch the sync job
        SyncBrandSocialAccounts::dispatch($brand);
        
        return redirect()->route('brand.dashboard')
            ->with('success', 'Sync started successfully! It may take a few minutes to complete.');
    }
    
    /**
     * Show posts for a specific provider.
     *
     * @param string $provider
     * @return \Illuminate\Http\Response
     */
    public function providerShow($provider)
    {
        // Guard clause for brand not found
        $brand = auth()->user()->brand;
        if (!$brand) {
            // Instead of redirecting to dashboard (which causes a loop), show an error page
            return response()->view('errors.brand-not-found', [], 404);
        }
        
        // Validate provider
        if (!array_key_exists($provider, \App\Services\SocialProviders\ProviderFactory::getSupportedProviders())) {
            abort(404);
        }

        // Get accounts for this provider
        $accounts = SocialAccount::where('brand_id', $brand->id)
            ->where('provider', $provider)
            ->get();

        // If no accounts found, redirect with error
        if ($accounts->isEmpty()) {
            return redirect()->route('brand.dashboard')->with('error', 'Social account not found.');
        }

        // Get posts for this provider
        $posts = \App\Models\SocialPost::whereHas('socialAccount', function ($query) use ($provider, $brand) {
                $query->where('brand_id', $brand->id)
                    ->where('provider', $provider);
            })
            ->orderBy('published_at', 'desc')
            ->paginate(20);

        $providerName = \App\Services\SocialProviders\ProviderFactory::getProviderName($provider);

        return view('brand.provider.show', compact('provider', 'providerName', 'accounts', 'posts'));
    }
    
    /**
     * Generate an AI proposal.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function generateAiProposal(Request $request)
    {
        // Guard clause for brand not found
        $brand = auth()->user()->brand;
        if (!$brand) {
            return response()->view('errors.brand-not-found', [], 404);
        }

        // Dispatch the AI task job
        EnqueueAiTaskJob::dispatch('generate_proposal', $brand->id, auth()->id(), [
            'brand_name' => $brand->name,
            'brand_industry' => $brand->industry ?? 'general',
            // Add more payload data as needed
        ]);

        return redirect()->route('brand.dashboard')
            ->with('success', 'AI proposal generation started! Check back soon for results.');
    }

    /**
     * Get AI tasks for the current brand.
     *
     * @return \Illuminate\Http\Response
     */
    public function aiTasks()
    {
        // Guard clause for brand not found
        $brand = auth()->user()->brand;
        if (!$brand) {
            return response()->json(['error' => 'Brand not found'], 404);
        }

        // Get AI tasks for this brand
        $aiTasks = AiTask::where('brand_id', $brand->id)
            ->orderBy('created_at', 'desc')
            ->get();

        return response()->json($aiTasks);
    }
}
