<?php

namespace App\Http\Controllers\Creator;

use App\Http\Controllers\Controller;
use App\Jobs\SyncUserSocialAccounts;
use App\Models\SocialAccount;
use App\Models\SocialAggregate;
use App\Models\SocialPost;
use App\Services\SocialProviders\ProviderFactory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class DashboardController extends Controller
{
    /**
     * Display the creator dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        // Get current user
        $user = Auth::user();
        
        // Get KPI data
        $kpis = $this->getKpiData();
        
        // Get connection status
        $connections = SocialAccount::where('user_id', Auth::id())
            ->orderBy('provider')
            ->get();
            
        // Get recent activity
        $recentActivity = SocialPost::whereHas('socialAccount', function ($query) {
                $query->where('user_id', Auth::id());
            })
            ->orderBy('published_at', 'desc')
            ->limit(10)
            ->get();

        return view('creator.dashboard', compact('user', 'kpis', 'connections', 'recentActivity'));
    }

    /**
     * Get KPI data for the dashboard.
     *
     * @return array
     */
    protected function getKpiData()
    {
        $userId = Auth::id();
        
        // Get overall aggregates
        $followers = SocialAggregate::where('user_id', $userId)
            ->where('key', 'total_followers')
            ->first();
            
        $posts = SocialAggregate::where('user_id', $userId)
            ->where('key', 'total_posts')
            ->first();
            
        $views = SocialAggregate::where('user_id', $userId)
            ->where('key', 'total_views')
            ->first();
            
        $engagement = SocialAggregate::where('user_id', $userId)
            ->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()
    {
        $userId = Auth::id();
        
        // Get daily views for the last 14 days
        $viewsData = SocialAggregate::where('user_id', $userId)
            ->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 user.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function syncNow(Request $request)
    {
        // Dispatch the sync job
        SyncUserSocialAccounts::dispatch(Auth::user());
        
        return redirect()->route('creator.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)
    {
        // Validate provider
        if (!array_key_exists($provider, ProviderFactory::getSupportedProviders())) {
            abort(404);
        }

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

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

        $providerName = ProviderFactory::getProviderName($provider);

        return view('creator.provider.show', compact('provider', 'providerName', 'accounts', 'posts'));
    }
}