<?php

namespace App\Http\Controllers;

use App\Models\Review;
use App\Models\ReviewVote;
use Illuminate\Http\Request;

class ReviewVoteController extends Controller
{
    /**
     * Vote on a review (helpful/not helpful)
     */
    public function vote(Request $request, Review $review)
    {
        $validated = $request->validate([
            'is_helpful' => 'required|boolean',
        ]);

        $userId = auth()->id();

        // Check if already voted
        $existingVote = ReviewVote::where('review_id', $review->id)
            ->where('user_id', $userId)
            ->first();

        if ($existingVote) {
            // If vote is same, remove it (toggle)
            if ($existingVote->is_helpful == $validated['is_helpful']) {
                // Decrement count
                if ($existingVote->is_helpful) {
                    $review->decrement('helpful_count');
                } else {
                    $review->decrement('not_helpful_count');
                }

                $existingVote->delete();

                return back()->with('success', 'Vote dibatalkan.');
            }

            // If vote is different, update it
            // Decrement old count
            if ($existingVote->is_helpful) {
                $review->decrement('helpful_count');
            } else {
                $review->decrement('not_helpful_count');
            }

            // Increment new count
            if ($validated['is_helpful']) {
                $review->increment('helpful_count');
            } else {
                $review->increment('not_helpful_count');
            }

            $existingVote->update(['is_helpful' => $validated['is_helpful']]);

            return back()->with('success', 'Vote berhasil diubah.');
        }

        // Create new vote
        ReviewVote::create([
            'review_id' => $review->id,
            'user_id' => $userId,
            'is_helpful' => $validated['is_helpful'],
        ]);

        // Increment count
        if ($validated['is_helpful']) {
            $review->increment('helpful_count');
        } else {
            $review->increment('not_helpful_count');
        }

        return back()->with('success', 'Terima kasih atas feedback Anda!');
    }
}