<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Location;
use App\Models\Rating;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class RatingController extends Controller
{
    public function __construct()
    {
        // Middleware is handled by routes
    }

    public function index(Request $request)
    {
        $user = Auth::user();

        // Get filter parameters
        $status = $request->get('status', 'all');
        $rating_filter = $request->get('rating_filter');
        $search = $request->get('search');
        $sort = $request->get('sort', 'newest');

        // Build query
        $query = Rating::where('email', $user->email)
            ->with([
                'location' => function($q) {
                    $q->select('title_id', 'title', 'category', 'category_fa');
                },
                'categoryRelation' => function($q) {
                    $q->select('id', 'category_key', 'category_fa', 'category_en', 'category_ar');
                }
            ]);

        // Apply filters
        if ($status !== 'all') {
            $query->where('status', $status);
        }

        if ($rating_filter) {
            $query->where('rating', $rating_filter);
        }

        if ($search) {
            $query->where(function($q) use ($search) {
                $q->where('hotel_name', 'like', "%{$search}%")
                  ->orWhere('positive_comment', 'like', "%{$search}%")
                  ->orWhere('negative_comment', 'like', "%{$search}%")
                  ->orWhere('category', 'like', "%{$search}%");
            });
        }

        // Apply sorting
        switch ($sort) {
            case 'oldest':
                $query->orderBy('timestamp', 'asc');
                break;
            case 'rating_high':
                $query->orderBy('rating', 'desc');
                break;
            case 'rating_low':
                $query->orderBy('rating', 'asc');
                break;
            case 'status':
                $query->orderBy('status', 'asc');
                break;
            default:
                $query->orderBy('timestamp', 'desc');
        }

        $ratings = $query->paginate(12)->withQueryString();

        // Get statistics
        $stats = $this->getRatingStats($user);

        // Check if it's an AJAX request for infinite scroll
        if ($request->ajax()) {
            return response()->json([
                'html' => view('user.ratings.partials.rating-grid', compact('ratings'))->render(),
                'hasMorePages' => $ratings->hasMorePages(),
                'nextPageUrl' => $ratings->nextPageUrl()
            ]);
        }

        return view('user.ratings.index', compact('ratings', 'stats', 'status', 'rating_filter', 'search', 'sort'));
    }

    /**
     * Get rating statistics for user
     */
    private function getRatingStats($user)
    {
        $total = Rating::where('email', $user->email)->count();
        $approved = Rating::where('email', $user->email)->where('status', 'approved')->count();
        $pending = Rating::where('email', $user->email)->where('status', 'pending')->count();
        $rejected = Rating::where('email', $user->email)->where('status', 'rejected')->count();

        $avgRating = Rating::where('email', $user->email)->avg('rating') ?? 0;

        // Get rating distribution
        $ratingDistribution = [];
        for ($i = 1; $i <= 5; $i++) {
            $ratingDistribution[$i] = Rating::where('email', $user->email)
                ->where('rating', $i)
                ->count();
        }

        // Get monthly activity
        $monthlyActivity = [];
        for ($i = 11; $i >= 0; $i--) {
            $date = now()->subMonths($i);
            $monthKey = $date->format('Y-m');

            $count = Rating::where('email', $user->email)
                ->whereYear('timestamp', $date->year)
                ->whereMonth('timestamp', $date->month)
                ->count();

            $monthlyActivity[] = [
                'month' => $monthKey,
                'count' => $count
            ];
        }

        return [
            'total' => $total,
            'approved' => $approved,
            'pending' => $pending,
            'rejected' => $rejected,
            'avg_rating' => round($avgRating, 1),
            'rating_distribution' => $ratingDistribution,
            'monthly_activity' => $monthlyActivity
        ];
    }

    public function create(Request $request)
    {
        $user = Auth::user();
        $locationId = $request->location_id;
        $location = null;

        if ($locationId) {
            $location = Location::with(['categoryRelation', 'province', 'city'])->find($locationId);

            // Check if user already rated this location
            $existingRating = Rating::where('email', $user->email)
                ->where('title_id', $location->title_id)
                ->first();

            if ($existingRating) {
                return redirect()->route('user.ratings.index')
                    ->with('warning', 'شما قبلاً برای این مکان نظر ثبت کرده‌اید.');
            }
        }

        // Get active locations with related data
        $locations = Location::with(['categoryRelation', 'province', 'city'])
            ->where('is_active', 1)
            ->orderBy('title')
            ->get();

        // Get user's rating statistics for motivation
        $userStats = $this->getUserRatingStats($user);

        // Get popular locations for suggestions
        $popularLocations = $this->getPopularLocations();

        // Get recent locations for quick access
        $recentLocations = $this->getRecentLocations();

        return view('user.ratings.create', compact(
            'locations',
            'location',
            'userStats',
            'popularLocations',
            'recentLocations'
        ));
    }

    /**
     * Get user rating statistics
     */
    private function getUserRatingStats($user)
    {
        $total = Rating::where('email', $user->email)->count();
        $thisMonth = Rating::where('email', $user->email)
            ->whereMonth('timestamp', now()->month)
            ->whereYear('timestamp', now()->year)
            ->count();

        return [
            'total' => $total,
            'this_month' => $thisMonth,
            'avg_rating' => Rating::where('email', $user->email)->avg('rating') ?? 0
        ];
    }

    /**
     * Get popular locations
     */
    private function getPopularLocations()
    {
        return Location::with(['categoryRelation'])
            ->where('is_active', 1)
            ->withCount('ratings')
            ->orderBy('ratings_count', 'desc')
            ->limit(5)
            ->get();
    }

    /**
     * Get recent locations
     */
    private function getRecentLocations()
    {
        return Location::with(['categoryRelation'])
            ->where('is_active', 1)
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get();
    }

    public function store(Request $request)
    {
        $user = Auth::user();

        $request->validate([
            'title_id' => 'required|exists:locations,title_id',
            'rating' => 'required|integer|min:1|max:5',
            'service_rating' => 'nullable|integer|min:1|max:5',
            'cleanliness_rating' => 'nullable|integer|min:1|max:5',
            'location_rating' => 'nullable|integer|min:1|max:5',
            'price_rating' => 'nullable|integer|min:1|max:5',
            'positive_comment' => 'nullable|string',
            'negative_comment' => 'nullable|string',
            'trip_type' => 'nullable|string|max:50',
            'travel_method' => 'nullable|string|max:50',
            'stay_date' => 'nullable|date',
        ]);

        // Store comments as plain text
        $positiveComment = $request->positive_comment;
        $negativeComment = $request->negative_comment;

        // Find the location to get its name and category
        $location = Location::where('title_id', $request->title_id)->first();

        $rating = new Rating;
        $rating->title_id = $request->title_id;
        $rating->category = $location->category;
        $rating->hotel_name = $location->title;
        $rating->name = $user->full_name;
        $rating->email = $user->email;
        $rating->rating = $request->rating;
        $rating->service_rating = $request->service_rating;
        $rating->cleanliness_rating = $request->cleanliness_rating;
        $rating->location_rating = $request->location_rating;
        $rating->price_rating = $request->price_rating;
        $rating->positive_comment = $positiveComment;
        $rating->negative_comment = $negativeComment;
        $rating->trip_type = $request->trip_type;
        $rating->travel_method = $request->travel_method;
        $rating->stay_date = $request->stay_date;
        $rating->status = 'pending';

        $rating->save();

        return redirect()->route('user.ratings.create')
            ->with('success', 'نظر شما با موفقیت ثبت شد و پس از بررسی منتشر خواهد شد.');
    }

    public function show($id)
    {
        $user = Auth::user();
        $rating = Rating::where('id', $id)
            ->where('email', $user->email)
            ->with(['categoryRelation' => function($q) {
                $q->select('id', 'category_key', 'category_fa', 'category_en', 'category_ar');
            }])
            ->firstOrFail();

        return view('user.ratings.show', compact('rating'));
    }

    public function edit($id)
    {
        $user = Auth::user();
        $rating = Rating::where('id', $id)
            ->where('email', $user->email)
            ->firstOrFail();

        // Only allow edits if the rating is still pending
        if ($rating->status !== 'pending') {
            return redirect()->route('user.ratings.index')
                ->with('error', 'نظرات تایید یا رد شده قابل ویرایش نیستند.');
        }

        $location = Location::where('title_id', $rating->title_id)->first();

        return view('user.ratings.edit', compact('rating', 'location'));
    }

    public function update(Request $request, $id)
    {
        $user = Auth::user();
        $rating = Rating::where('id', $id)
            ->where('email', $user->email)
            ->firstOrFail();

        // Only allow edits if the rating is still pending
        if ($rating->status !== 'pending') {
            return redirect()->route('user.ratings.index')
                ->with('error', 'نظرات تایید یا رد شده قابل ویرایش نیستند.');
        }

        $request->validate([
            'rating' => 'required|integer|min:1|max:5',
            'service_rating' => 'nullable|integer|min:1|max:5',
            'cleanliness_rating' => 'nullable|integer|min:1|max:5',
            'location_rating' => 'nullable|integer|min:1|max:5',
            'price_rating' => 'nullable|integer|min:1|max:5',
            'positive_comment' => 'nullable|string',
            'negative_comment' => 'nullable|string',
            'trip_type' => 'nullable|string|max:50',
            'travel_method' => 'nullable|string|max:50',
            'stay_date' => 'nullable|date',
        ]);

        // Store comments as plain text
        $positiveComment = $request->positive_comment;
        $negativeComment = $request->negative_comment;

        $rating->rating = $request->rating;
        $rating->service_rating = $request->service_rating;
        $rating->cleanliness_rating = $request->cleanliness_rating;
        $rating->location_rating = $request->location_rating;
        $rating->price_rating = $request->price_rating;
        $rating->positive_comment = $positiveComment;
        $rating->negative_comment = $negativeComment;
        $rating->trip_type = $request->trip_type;
        $rating->travel_method = $request->travel_method;
        $rating->stay_date = $request->stay_date;

        $rating->save();

        return redirect()->route('user.ratings.index')
            ->with('success', 'نظر شما با موفقیت به‌روزرسانی شد.');
    }

    public function destroy($id)
    {
        $user = Auth::user();
        $rating = Rating::where('id', $id)
            ->where('email', $user->email)
            ->where('status', 'pending') // Only allow deletion if still pending
            ->firstOrFail();

        $rating->delete();

        return redirect()->route('user.ratings.index')
            ->with('success', 'نظر با موفقیت حذف شد.');
    }


}
