<?php

namespace App\Http\Controllers;

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

class ReviewReplyController extends Controller
{
    /**
     * Store reply to review (Admin only)
     */
    public function store(Request $request, Review $review)
    {
        // Check if user is admin
        // You can use middleware or policy here
        // Example: $this->authorize('admin');
        
        if (!auth()->user()->is_admin) {
            abort(403, 'Unauthorized');
        }

        $validated = $request->validate([
            'reply' => 'required|string|max:1000',
        ]);

        // Check if reply already exists
        if ($review->reply) {
            return back()->with('error', 'Review ini sudah memiliki balasan. Silakan edit balasan yang ada.');
        }

        ReviewReply::create([
            'review_id' => $review->id,
            'user_id' => auth()->id(),
            'reply' => $validated['reply'],
        ]);

        // Optional: Notify review author
        // $review->user->notify(new ReviewRepliedNotification($review));

        return back()->with('success', 'Balasan berhasil dikirim!');
    }

    /**
     * Update reply
     */
    public function update(Request $request, ReviewReply $reply)
    {
        if (!auth()->user()->is_admin) {
            abort(403);
        }

        $validated = $request->validate([
            'reply' => 'required|string|max:1000',
        ]);

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

        return back()->with('success', 'Balasan berhasil diupdate!');
    }

    /**
     * Delete reply
     */
    public function destroy(ReviewReply $reply)
    {
        if (!auth()->user()->is_admin) {
            abort(403);
        }

        $reply->delete();

        return back()->with('success', 'Balasan berhasil dihapus.');
    }
}