<?php

namespace App\Http\Controllers\Business;

use App\Models\Business;
use App\Models\Offer;
use App\Models\Venue;
use App\Models\Redemption;
use App\Models\Review;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Carbon\Carbon;

class DashboardController extends Controller
{
    /**
     * Display business dashboard (main entry point)
     */
    public function index(Request $request)
    {
        $user = auth()->user();
        $business = null;

        // Check if user is business owner
        if ($user->hasRole('business_owner') || $user->account_type === 'business') {
            $business = Business::where('owner_id', $user->id)->first();
        }

        // Check if user is staff member
        if (!$business) {
            $staff = \App\Models\BusinessStaff::where('user_id', $user->id)
                ->where('status', 'active')
                ->first();

            if ($staff) {
                $business = $staff->business;
            }
        }

        if (!$business) {
            return redirect()->route('business.register')
                ->with('error', 'No business found. Please create one or check your staff assignment.');
        }

        return $this->show($request, $business);
    }

    /**
     * Display specific business dashboard with analytics
     */
    public function show(Request $request, Business $business)
    {
        // Check if user is owner or staff member of this business
        $user = auth()->user();
        $isOwner = $business->owner_id === $user->id;
        $isStaff = \App\Models\BusinessStaff::where('business_id', $business->id)
            ->where('user_id', $user->id)
            ->where('status', 'active')
            ->exists();

        abort_if(!($isOwner || $isStaff), 403);

        $business->load('teams', 'staff', 'venues', 'offers');

        // Time period for analytics (default: last 30 days)
        $period = $request->get('period', '30');
        $startDate = Carbon::now()->subDays($period);

        // Key Statistics
        $statistics = $this->getKeyStatistics($business);

        // Analytics Data
        $analytics = [
            'venues' => [
                'total' => $business->venues->count(),
                'active' => $business->venues->where('status', 'active')->count(),
            ],
            'offers' => [
                'total' => Offer::where('business_id', $business->id)->count(),
                'active' => Offer::where('business_id', $business->id)->where('status', 'active')->count(),
                'redemptions' => Redemption::whereHas('offer', function ($q) use ($business) {
                    $q->where('business_id', $business->id);
                })->where('created_at', '>=', $startDate)->count(),
            ],
            'staff' => [
                'total' => $business->staff->count(),
                'active' => $business->staff->where('status', 'active')->count(),
            ],
            'ratings' => [
                'average' => Review::whereHas('venue', function ($q) use ($business) {
                    $q->where('business_id', $business->id);
                })->avg('rating') ?? 0,
                'total_reviews' => Review::whereHas('venue', function ($q) use ($business) {
                    $q->where('business_id', $business->id);
                })->count(),
            ],
        ];

        // Revenue Data (if exists)
        $revenue = $this->getRevenueData($business, $startDate);

        // Redemption Trends
        $redemptionTrends = $this->getRedemptionTrends($business, $period);

        // Recent Redemptions
        $recentRedemptions = Redemption::whereHas('offer', function ($q) use ($business) {
            $q->where('business_id', $business->id);
        })->with('offer', 'user')->latest()->limit(10)->get();

        // Top Performing Offers
        $topOffers = $this->getTopOffers($business, $period);

        // Performance Summary
        $performance = $this->getPerformanceSummary($business, $startDate);

        return view('business.dashboard', [
            'business' => $business,
            'statistics' => $statistics,
            'analytics' => $analytics,
            'revenue' => $revenue,
            'redemptionTrends' => $redemptionTrends,
            'recentRedemptions' => $recentRedemptions,
            'topOffers' => $topOffers,
            'performance' => $performance,
            'period' => $period,
        ]);
    }

    /**
     * Get key statistics for the business
     */
    private function getKeyStatistics($business)
    {
        // Get reviews through venues
        $reviews = Review::whereHas('venue', function ($q) use ($business) {
            $q->where('business_id', $business->id);
        })->get();

        return [
            'venues' => $business->venues->count(),
            'active_venues' => $business->venues->where('status', 'active')->count(),
            'total_staff' => $business->staff->count(),
            'active_staff' => $business->staff->where('status', 'active')->count(),
            'total_offers' => Offer::where('business_id', $business->id)->count(),
            'active_offers' => Offer::where('business_id', $business->id)->where('status', 'active')->count(),
            'avg_rating' => $reviews->avg('rating') ?? 0,
            'total_reviews' => $reviews->count(),
            'plan' => $business->activeSubscription()->with('plan')->first()?->plan?->name ?? 'No Plan',
        ];
    }

    /**
     * Get revenue data
     */
    private function getRevenueData($business, $startDate)
    {
        // Get redemptions in period
        $redemptions = Redemption::whereHas('offer', function ($q) use ($business) {
            $q->where('business_id', $business->id);
        })->where('created_at', '>=', $startDate)->with('offer')->get();

        $totalRevenue = $redemptions->sum(function ($r) {
            return $r->offer->discount_value ?? 0;
        });

        return [
            'total' => $totalRevenue,
            'count' => $redemptions->count(),
            'average' => $redemptions->count() > 0 ? $totalRevenue / $redemptions->count() : 0,
        ];
    }

    /**
     * Get redemption trends for chart
     */
    private function getRedemptionTrends($business, $period)
    {
        $startDate = Carbon::now()->subDays($period);
        $trends = [];

        for ($i = $period - 1; $i >= 0; $i--) {
            $date = Carbon::now()->subDays($i);
            $count = Redemption::whereHas('offer', function ($q) use ($business) {
                $q->where('business_id', $business->id);
            })->whereDate('created_at', $date->toDateString())->count();

            $trends[] = [
                'date' => $date->format('M d'),
                'count' => $count,
            ];
        }

        return $trends;
    }

    /**
     * Get top performing offers
     */
    private function getTopOffers($business, $period)
    {
        $startDate = Carbon::now()->subDays($period);

        return Offer::where('business_id', $business->id)
            ->withCount(['redemptions' => function ($q) use ($startDate) {
                $q->where('created_at', '>=', $startDate);
            }])
            ->orderBy('redemptions_count', 'desc')
            ->limit(5)
            ->get();
    }

    /**
     * Get performance summary
     */
    private function getPerformanceSummary($business, $startDate)
    {
        $totalRedemptions = Redemption::whereHas('offer', function ($q) use ($business) {
            $q->where('business_id', $business->id);
        })->where('created_at', '>=', $startDate)->count();

        $totalReviews = Review::whereHas('venue', function ($q) use ($business) {
            $q->where('business_id', $business->id);
        })->where('created_at', '>=', $startDate)->count();

        $avgRating = Review::whereHas('venue', function ($q) use ($business) {
            $q->where('business_id', $business->id);
        })->avg('rating') ?? 0;

        return [
            'redemptions' => $totalRedemptions,
            'reviews' => $totalReviews,
            'avg_rating' => $avgRating,
        ];
    }
}

