<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Traits\DeleteModelTrait;
use App\Traits\FlashMessageTrait;
use App\Models\Review;
use Illuminate\Http\Request;
use Inertia\Inertia;

class AdminReviewController extends Controller
{
    use DeleteModelTrait, FlashMessageTrait;

    public function index(Request $request)
    {
        try {
            $perPage = 5;
            $reviews = Review::with(['property', 'reviewer'])
                ->orderBy('created_at', 'desc')
                ->paginate($perPage);
            
            $reviews->getCollection()->transform(function ($review, $index) use ($reviews) {
                $review->sn = ($reviews->currentPage() - 1) * $reviews->perPage() + $index + 1;
                $review->property_title = $review->property->title ?? 'N/A';
                $review->reviewer_name = $review->reviewer->name ?? 'N/A';
                return $review;
            });

            return Inertia::render('Admin/Reviews/Review', [
                'reviews' => $reviews->items(),
                'pagination' => [
                    'current_page' => $reviews->currentPage(),
                    'last_page' => $reviews->lastPage(),
                    'per_page' => $reviews->perPage(),
                    'total' => $reviews->total(),
                    'from' => $reviews->firstItem(),
                    'to' => $reviews->lastItem(),
                    'links' => $reviews->linkCollection()->toArray(),
                ]
            ]);
        } catch (\Exception $e) {
            return $this->error('Failed to load reviews: ' . $e->getMessage());
        }
    }

    public function show($id)
    {
        try {
            $review = Review::with(['property', 'reviewer'])->find($id);
            
            if (!$review) {
                return response()->json(['error' => 'Review not found'], 404);
            }

            return response()->json($review);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    public function destroy($id)
    {
        try {
            $review = Review::find($id);

            if (!$review) {
                return $this->error('Review not found');
            }

            return $this->deleteModel($id, new Review());
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
}
