<?php

namespace App\Http\Controllers;

use App\Models\Review;
use App\Models\Destination;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class ReviewController extends Controller
{
    // Get reviews for a specific package
    public function getByPackage($packageId)
    {
        $package = Destination::find($packageId);
        
        if (!$package) {
            return response()->json([
                'success' => false,
                'message' => 'Package not found'
            ], 404);
        }

        $reviews = Review::with('user:id,name')
            ->where('package_id', $packageId)
            ->orderBy('created_at', 'desc')
            ->get();

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

    // Create a new review
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'package_id' => 'required|exists:tour_packages,id',
            'rating' => 'required|integer|min:1|max:5',
            'comment' => 'required|string|max:1000',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 422);
        }

        // Check if user already reviewed this package
        $existingReview = Review::where('user_id', Auth::id())
            ->where('package_id', $request->package_id)
            ->first();

        if ($existingReview) {
            return response()->json([
                'success' => false,
                'message' => 'You have already reviewed this package'
            ], 409);
        }

        $review = Review::create([
            'user_id' => Auth::id(),
            'package_id' => $request->package_id,
            'rating' => $request->rating,
            'comment' => $request->comment,
        ]);

        // Update package rating
        $this->updatePackageRating($request->package_id);

        return response()->json([
            'success' => true,
            'review' => $review->load('user:id,name'),
            'message' => 'Review submitted successfully'
        ]);
    }

    // Delete a review
    public function destroy($id)
    {
        $review = Review::find($id);

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

        // Check if the authenticated user owns the review
        if ($review->user_id !== Auth::id()) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized to delete this review'
            ], 403);
        }

        $packageId = $review->package_id;
        $review->delete();

        // Update package rating after deletion
        $this->updatePackageRating($packageId);

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

    // Helper method to update package rating
    private function updatePackageRating($packageId)
    {
        $averageRating = Review::where('package_id', $packageId)
            ->avg('rating');

        Destination::where('id', $packageId)
            ->update(['rating' => $averageRating]);
    }


        public function store_review(Request $request)
    {
        // Validate input
        $validator = Validator::make($request->all(), [
            'user_id' => 'required|integer',
            'package_id' => 'required|integer',
            'rating' => 'required|numeric|min:1|max:5',
            'comment' => 'nullable|string|max:1000',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation error',
                'errors' => $validator->errors()
            ], 422);
        }

        // Insert into database
        $review = Review::create([
            'user_id' => $request->user_id,
            'package_id' => $request->package_id,
            'rating' => $request->rating,
            'comment' => $request->comment,
        ]);

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

        public function getPackageReviews($packageId)
    {
        try {
            // Validate package exists
            $package = Destination::find($packageId);
            if (!$package) {
                return response()->json([
                    'success' => false,
                    'message' => 'Package not found'
                ], 404);
            }

            // Get reviews with user data
            $reviews = Review::with(['user' => function($query) {
                    $query->select('id', 'name');
                }])
                ->where('package_id', $packageId)
                ->orderBy('created_at', 'desc')
                ->get(['id', 'user_id', 'rating', 'comment', 'created_at']);

            // Calculate average rating
            $averageRating = $reviews->avg('rating');
            $totalReviews = $reviews->count();

            return response()->json([
                'success' => true,
                'data' => [
                    'reviews' => $reviews,
                    'average_rating' => round($averageRating, 1),
                    'total_reviews' => $totalReviews
                ]
            ]);

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