<?php

namespace App\Http\Controllers;

use App\Models\Review;
use App\Models\Booking;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log; // ✅ ADD THIS LINE

class ReviewController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $query = Review::with(['reviewer', 'reviewedUser', 'booking'])->public();

            // Filter by review type
            if ($request->has('type')) {
                $query->where('review_type', $request->get('type'));
            }

            // Filter by rating
            if ($request->has('min_rating')) {
                $query->where('rating', '>=', $request->get('min_rating'));
            }

            // Filter by user
            if ($request->has('user_id')) {
                $query->where('reviewed_user_id', $request->get('user_id'));
            }

            // Order by
            $orderBy = $request->get('order_by', 'created_at');
            $orderDirection = $request->get('order_direction', 'desc');
            $query->orderBy($orderBy, $orderDirection);

            // Pagination
            $perPage = $request->get('per_page', 2);
            $reviews = $query->paginate($perPage);

            return response()->json([
                'success' => true,
                'data' => $reviews->items(),
                'pagination' => [
                    'current_page' => $reviews->currentPage(),
                    'per_page' => $reviews->perPage(),
                    'total' => $reviews->total(),
                    'last_page' => $reviews->lastPage(),
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch reviews',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    public function store(Request $request): JsonResponse
{
    try {
        $user = $request->user();
        $validated = $request->validate([
            'booking_id' => 'required|exists:bookings,booking_id',
            'reviewed_user_id' => 'required|exists:users,user_id',
            'review_type' => 'required|in:parent_to_babysitter,babysitter_to_parent',
            'rating' => 'required|integer|min:1|max:5',
            'review_text' => 'nullable|string',
            'would_recommend' => 'nullable|boolean',
            'strengths' => 'nullable|string',
            'areas_for_improvement' => 'nullable|string'
        ]);

        // Get booking details
        $booking = Booking::find($validated['booking_id']);

        // ✅ ADD DEBUGGING LOGS
        Log::info('🔍 REVIEW CREATION DEBUG - User and Booking Details:', [
            'user_id' => $user->user_id,
            'user_type' => $user->user_type,
            'booking_id' => $validated['booking_id'],
            'booking_parent_id' => $booking ? $booking->parent_id : 'not_found',
            'booking_babysitter_id' => $booking ? $booking->babysitter_id : 'not_found',
            'review_type' => $validated['review_type'],
            'reviewed_user_id' => $validated['reviewed_user_id']
        ]);

        // ✅ Check if booking is completed
        if (!$booking || $booking->booking_status !== 'completed') {
            return response()->json([
                'success' => false,
                'message' => 'Reviews can only be submitted for completed bookings. Current status: ' . ($booking ? $booking->booking_status : 'not found')
            ], 422);
        }

        // ✅ Check if user is part of this booking (either parent or babysitter)
        $isParent = $booking->parent_id == $user->user_id;
        $isBabysitter = $booking->babysitter_id == $user->user_id;

        Log::info('🔍 USER ROLE CHECK:', [
            'isParent' => $isParent,
            'isBabysitter' => $isBabysitter,
            'parent_id_match' => $booking->parent_id == $user->user_id,
            'babysitter_id_match' => $booking->babysitter_id == $user->user_id
        ]);

        if (!$isParent && !$isBabysitter) {
            return response()->json([
                'success' => false,
                'message' => 'You can only review bookings you are part of',
                'debug_info' => [ // ✅ ADD DEBUG INFO
                    'your_user_id' => $user->user_id,
                    'booking_parent_id' => $booking->parent_id,
                    'booking_babysitter_id' => $booking->babysitter_id,
                    'expected_parent_id' => $booking->parent_id,
                    'expected_babysitter_id' => $booking->babysitter_id
                ]
            ], 403);
        }

        // ✅ Validate review type based on user role
        if ($isParent && $validated['review_type'] !== 'parent_to_babysitter') {
            return response()->json([
                'success' => false,
                'message' => 'As a parent, you can only submit parent to babysitter reviews'
            ], 422);
        }

        if ($isBabysitter && $validated['review_type'] !== 'babysitter_to_parent') {
            return response()->json([
                'success' => false,
                'message' => 'As a babysitter, you can only submit babysitter to parent reviews'
            ], 422);
        }

        // ✅ Validate that reviewed user is correct based on review type
        if ($validated['review_type'] === 'parent_to_babysitter') {
            if ((int)$validated['reviewed_user_id'] !== (int)$booking->babysitter_id) {
                return response()->json([
                    'success' => false,
                    'message' => 'You can only review the babysitter for this booking. ' .
                        'Expected babysitter ID: ' . $booking->babysitter_id .
                        ', Provided user ID: ' . $validated['reviewed_user_id']
                ], 422);
            }
        } else { // babysitter_to_parent
            if ((int)$validated['reviewed_user_id'] !== (int)$booking->parent_id) {
                return response()->json([
                    'success' => false,
                    'message' => 'You can only review the parent for this booking. ' .
                        'Expected parent ID: ' . $booking->parent_id .
                        ', Provided user ID: ' . $validated['reviewed_user_id']
                ], 422);
            }
        }

        // Check if review already exists for this booking and type
        $existingReview = Review::where('booking_id', $validated['booking_id'])
            ->where('review_type', $validated['review_type'])
            ->first();

        if ($existingReview) {
            return response()->json([
                'success' => false,
                'message' => 'You have already submitted a ' . $validated['review_type'] . ' review for this booking'
            ], 422);
        }

        $validated['reviewer_id'] = $user->user_id;
        $validated['is_verified_booking'] = true;
        $validated['is_public'] = true;

        $review = Review::create($validated);

        // Log successful review creation
        Log::info('✅ REVIEW CREATED - Successfully:', [
            'review_id' => $review->review_id,
            'booking_id' => $validated['booking_id'],
            'reviewer_id' => $user->user_id,
            'reviewed_user_id' => $validated['reviewed_user_id'],
            'review_type' => $validated['review_type'],
            'rating' => $validated['rating']
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Review created successfully',
            'data' => $review->load(['reviewer', 'reviewedUser', 'booking'])
        ], 201);
    } catch (\Illuminate\Validation\ValidationException $e) {
        return response()->json([
            'success' => false,
            'message' => 'Validation failed',
            'errors' => $e->errors()
        ], 422);
    } catch (\Exception $e) {
        Log::error('❌ REVIEW CREATION - Failed:', [
            'error' => $e->getMessage(),
            'trace' => $e->getTraceAsString()
        ]);

        return response()->json([
            'success' => false,
            'message' => 'Failed to create review',
            'error' => config('app.debug') ? $e->getMessage() : null
        ], 500);
    }
}

    /**
     * Display the specified resource.
     */
    public function show(string $id): JsonResponse
    {
        try {
            $review = Review::with(['reviewer', 'reviewedUser', 'booking'])->public()->find($id);

            if (!$review) {
                return response()->json([
                    'success' => false,
                    'message' => 'Review not found'
                ], 404);
            }

            return response()->json([
                'success' => true,
                'data' => $review
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch review',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Update the specified resource in storage.
     */
    /**
 * Update the specified resource in storage.
 */
public function update(Request $request, string $id): JsonResponse
{
    try {
        $user = $request->user();
        $review = Review::find($id);

        if (!$review) {
            return response()->json([
                'success' => false,
                'message' => 'Review not found'
            ], 404);
        }

        // Check if user owns the review
        if ($review->reviewer_id !== $user->user_id) {
            return response()->json([
                'success' => false,
                'message' => 'You can only update your own reviews'
            ], 403);
        }

        // Validate update data
        $validated = $request->validate([
            'rating' => 'sometimes|integer|min:1|max:5',
            'review_text' => 'nullable|string',
            'would_recommend' => 'nullable|boolean',
            'strengths' => 'nullable|string',
            'areas_for_improvement' => 'nullable|string',
            'is_public' => 'sometimes|boolean'
        ]);

        // Check if review can be updated (within 24 hours of creation)
        $reviewAgeInHours = $review->created_at->diffInHours(now());
        if ($reviewAgeInHours > 24) {
            return response()->json([
                'success' => false,
                'message' => 'Reviews can only be updated within 24 hours of creation'
            ], 422);
        }

        $review->update($validated);

        // Log review update
        Log::info('✏️ REVIEW UPDATED - Successfully:', [
            'review_id' => $review->review_id,
            'updated_fields' => array_keys($validated)
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Review updated successfully',
            'data' => $review->load(['reviewer', 'reviewedUser', 'booking'])
        ]);

    } catch (\Illuminate\Validation\ValidationException $e) {
        return response()->json([
            'success' => false,
            'message' => 'Validation failed',
            'errors' => $e->errors()
        ], 422);
    } catch (\Exception $e) {
        Log::error('❌ REVIEW UPDATE - Failed:', [
            'review_id' => $id,
            'error' => $e->getMessage(),
            'trace' => $e->getTraceAsString()
        ]);

        return response()->json([
            'success' => false,
            'message' => 'Failed to update review',
            'error' => config('app.debug') ? $e->getMessage() : null
        ], 500);
    }
}

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Request $request, string $id): JsonResponse
    {
        try {
            $user = $request->user();
            $review = Review::find($id);

            if (!$review) {
                return response()->json([
                    'success' => false,
                    'message' => 'Review not found'
                ], 404);
            }

            // Check if user owns the review or is admin
            if ($review->reviewer_id !== $user->user_id && !$user->isAdmin()) {
                return response()->json([
                    'success' => false,
                    'message' => 'You can only delete your own reviews'
                ], 403);
            }

            $review->delete();

            return response()->json([
                'success' => true,
                'message' => 'Review deleted successfully'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete review',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Get my reviews (reviews by me)
     */
   /**
 * Get my reviews (reviews by me)
 */
public function getMyReviews(Request $request): JsonResponse
{
    try {
        $user = $request->user();

        Log::info('🔍 GET MY REVIEWS - Starting:', [
            'user_id' => $user->user_id,
            'email' => $user->email
        ]);

        $query = Review::with(['reviewedUser', 'booking'])
                    ->where('reviewer_id', $user->user_id);

        // Remove the ->public() scope temporarily for testing
        // $query = Review::with(['reviewedUser', 'booking'])->public()->where('reviewer_id', $user->user_id);

        // Filter by review type
        if ($request->has('type')) {
            $query->where('review_type', $request->get('type'));
        }

        // Order by
        $orderBy = $request->get('order_by', 'created_at');
        $orderDirection = $request->get('order_direction', 'desc');
        $query->orderBy($orderBy, $orderDirection);

        // Pagination
        $perPage = $request->get('per_page', 15);
        $reviews = $query->paginate($perPage);

        Log::info('📊 GET MY REVIEWS - Results:', [
            'total_reviews' => $reviews->total(),
            'current_page' => $reviews->currentPage(),
            'user_id' => $user->user_id
        ]);

        if ($reviews->isEmpty()) {
            Log::warning('⚠️ GET MY REVIEWS - No reviews found for user:', [
                'user_id' => $user->user_id
            ]);
        }

        return response()->json([
            'success' => true,
            'data' => $reviews->items(),
            'pagination' => [
                'current_page' => $reviews->currentPage(),
                'per_page' => $reviews->perPage(),
                'total' => $reviews->total(),
                'last_page' => $reviews->lastPage(),
            ]
        ]);

    } catch (\Exception $e) {
        Log::error('❌ GET MY REVIEWS - Failed:', [
            'user_id' => $user->user_id ?? 'unknown',
            'error' => $e->getMessage(),
            'trace' => $e->getTraceAsString()
        ]);

        return response()->json([
            'success' => false,
            'message' => 'Failed to fetch my reviews',
            'error' => config('app.debug') ? $e->getMessage() : null
        ], 500);
    }
}

    /**
     * Get reviews about me
     */
    public function getReviewsAboutMe(Request $request): JsonResponse
    {
        try {
            $user = $request->user();
            $query = Review::with(['reviewer', 'booking'])
                        ->public()
                        ->where('reviewed_user_id', $user->user_id);

            // Filter by review type
            if ($request->has('type')) {
                $query->where('review_type', $request->get('type'));
            }

            // Order by
            $orderBy = $request->get('order_by', 'created_at');
            $orderDirection = $request->get('order_direction', 'desc');
            $query->orderBy($orderBy, $orderDirection);

            // Pagination
            $perPage = $request->get('per_page', 15);
            $reviews = $query->paginate($perPage);

            return response()->json([
                'success' => true,
                'data' => $reviews->items(),
                'pagination' => [
                    'current_page' => $reviews->currentPage(),
                    'per_page' => $reviews->perPage(),
                    'total' => $reviews->total(),
                    'last_page' => $reviews->lastPage(),
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch reviews',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Mark review as helpful
     */
    public function markAsHelpful(string $id): JsonResponse
    {
        try {
            $review = Review::public()->find($id);

            if (!$review) {
                return response()->json([
                    'success' => false,
                    'message' => 'Review not found'
                ], 404);
            }

            $review->markAsHelpful();

            return response()->json([
                'success' => true,
                'message' => 'Review marked as helpful',
                'data' => $review
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to mark review as helpful',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Report review
     */
    public function reportReview(string $id): JsonResponse
    {
        try {
            $review = Review::public()->find($id);

            if (!$review) {
                return response()->json([
                    'success' => false,
                    'message' => 'Review not found'
                ], 404);
            }

            $review->report();

            return response()->json([
                'success' => true,
                'message' => 'Review reported successfully',
                'data' => $review
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to report review',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * ✅ NEW: Get reviews for a specific booking
     */
    public function getReviewsByBooking(string $bookingId): JsonResponse
    {
        try {
            $booking = Booking::find($bookingId);

            if (!$booking) {
                return response()->json([
                    'success' => false,
                    'message' => 'Booking not found'
                ], 404);
            }

            // Check if user is part of this booking
            $user = request()->user();
            $isParticipant = $booking->parent_id === $user->user_id ||
                            $booking->babysitter_id === $user->user_id;

            if (!$isParticipant) {
                return response()->json([
                    'success' => false,
                    'message' => 'You can only view reviews for bookings you are part of'
                ], 403);
            }

            $reviews = Review::with(['reviewer', 'reviewedUser'])
                            ->where('booking_id', $bookingId)
                            ->public()
                            ->get();

            return response()->json([
                'success' => true,
                'data' => $reviews,
                'booking_details' => [
                    'booking_id' => $booking->booking_id,
                    'status' => $booking->booking_status,
                    'parent_name' => $booking->parent ? $booking->parent->first_name . ' ' . $booking->parent->last_name : null,
                    'babysitter_name' => $booking->babysitter ? $booking->babysitter->first_name . ' ' . $booking->babysitter->last_name : null
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch reviews for booking',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * ✅ NEW: Check if user can review a booking
     */
    public function checkCanReview(string $bookingId): JsonResponse
    {
        try {
            $user = request()->user();
            $booking = Booking::find($bookingId);

            if (!$booking) {
                return response()->json([
                    'success' => false,
                    'message' => 'Booking not found'
                ], 404);
            }

            $isParent = $booking->parent_id === $user->user_id;
            $isBabysitter = $booking->babysitter_id === $user->user_id;
            $isParticipant = $isParent || $isBabysitter;

            if (!$isParticipant) {
                return response()->json([
                    'success' => false,
                    'can_review' => false,
                    'message' => 'You are not part of this booking'
                ]);
            }

            // Check if booking is completed
            if ($booking->booking_status !== 'completed') {
                return response()->json([
                    'success' => true,
                    'can_review' => false,
                    'message' => 'Booking must be completed to submit review'
                ]);
            }

            // Check if user has already submitted review for this booking
            $reviewType = $isParent ? 'parent_to_babysitter' : 'babysitter_to_parent';
            $existingReview = Review::where('booking_id', $bookingId)
                                  ->where('reviewer_id', $user->user_id)
                                  ->where('review_type', $reviewType)
                                  ->first();

            $canReview = !$existingReview;

            return response()->json([
                'success' => true,
                'can_review' => $canReview,
                'review_type' => $reviewType,
                'existing_review' => $existingReview ? [
                    'review_id' => $existingReview->review_id,
                    'rating' => $existingReview->rating
                ] : null,
                'message' => $canReview ? 'You can submit a review' : 'You have already reviewed this booking'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to check review eligibility',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * ✅ NEW: Get pending reviews (bookings that need review)
     */
    public function getPendingReviews(Request $request): JsonResponse
    {
        try {
            $user = $request->user();

            // Get completed bookings where user hasn't submitted review yet
            $completedBookings = Booking::where(function($query) use ($user) {
                    $query->where('parent_id', $user->user_id)
                          ->orWhere('babysitter_id', $user->user_id);
                })
                ->where('booking_status', 'completed')
                ->with(['parent', 'babysitter', 'occupationCategory'])
                ->get();

            $pendingReviews = [];

            foreach ($completedBookings as $booking) {
                $isParent = $booking->parent_id === $user->user_id;
                $reviewType = $isParent ? 'parent_to_babysitter' : 'babysitter_to_parent';
                $reviewedUserId = $isParent ? $booking->babysitter_id : $booking->parent_id;

                // Check if review already exists
                $existingReview = Review::where('booking_id', $booking->booking_id)
                                      ->where('reviewer_id', $user->user_id)
                                      ->where('review_type', $reviewType)
                                      ->first();

                if (!$existingReview) {
                    $pendingReviews[] = [
                        'booking_id' => $booking->booking_id,
                        'review_type' => $reviewType,
                        'reviewed_user_id' => $reviewedUserId,
                        'reviewed_user_name' => $isParent ?
                            ($booking->babysitter ? $booking->babysitter->first_name . ' ' . $booking->babysitter->last_name : null) :
                            ($booking->parent ? $booking->parent->first_name . ' ' . $booking->parent->last_name : null),
                        'booking_details' => [
                            'start_date' => $booking->start_date,
                            'end_date' => $booking->end_date,
                            'total_weeks' => $booking->total_weeks,
                            'occupation_category' => $booking->occupationCategory ? $booking->occupationCategory->category_name : null
                        ],
                        'can_review' => true
                    ];
                }
            }

            return response()->json([
                'success' => true,
                'data' => $pendingReviews,
                'count' => count($pendingReviews)
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch pending reviews',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * ✅ NEW: Get user rating statistics
     */
    public function getUserRatingStats(string $userId): JsonResponse
    {
        try {
            $reviews = Review::public()
                            ->where('reviewed_user_id', $userId)
                            ->get();

            if ($reviews->isEmpty()) {
                return response()->json([
                    'success' => true,
                    'data' => [
                        'average_rating' => 0,
                        'total_reviews' => 0,
                        'rating_breakdown' => [
                            '5_star' => 0,
                            '4_star' => 0,
                            '3_star' => 0,
                            '2_star' => 0,
                            '1_star' => 0
                        ],
                        'recommendation_rate' => 0
                    ]
                ]);
            }

            $totalReviews = $reviews->count();
            $averageRating = $reviews->avg('rating');
            $recommendationCount = $reviews->where('would_recommend', true)->count();

            $ratingBreakdown = [
                '5_star' => $reviews->where('rating', 5)->count(),
                '4_star' => $reviews->where('rating', 4)->count(),
                '3_star' => $reviews->where('rating', 3)->count(),
                '2_star' => $reviews->where('rating', 2)->count(),
                '1_star' => $reviews->where('rating', 1)->count()
            ];

            return response()->json([
                'success' => true,
                'data' => [
                    'average_rating' => round($averageRating, 1),
                    'total_reviews' => $totalReviews,
                    'rating_breakdown' => $ratingBreakdown,
                    'recommendation_rate' => round(($recommendationCount / $totalReviews) * 100, 1)
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch rating statistics',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }
}
