<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Models\Appointment;
use App\Models\ReviewFeedback;
use App\Support\Tenancy;
use Illuminate\Http\Request;

/**
 * Review gateway: the WhatsApp link lands here. 4–5★ → forward to the
 * clinic's Google review URL; 1–3★ → capture private feedback internally.
 */
class ReviewController extends Controller
{
    public function show(Request $request, Tenancy $tenancy, string $appointment)
    {
        abort_unless($request->hasValidSignature(), 403);

        $appt = Appointment::with('patient')->where('uuid', $appointment)->firstOrFail();

        return view('whatsapp.review', [
            'tenant' => $tenancy->get(),
            'appointment' => $appt,
        ]);
    }

    public function submit(Request $request, Tenancy $tenancy, string $appointment)
    {
        abort_unless($request->hasValidSignature(), 403);

        $data = $request->validate([
            'rating' => ['required', 'integer', 'min:1', 'max:5'],
            'comment' => ['nullable', 'string', 'max:2000'],
        ]);

        $appt = Appointment::with('patient')->where('uuid', $appointment)->firstOrFail();
        $tenant = $tenancy->get();

        ReviewFeedback::create([
            'tenant_id' => $tenant->id,
            'patient_id' => $appt->patient_id,
            'appointment_id' => $appt->id,
            'rating' => $data['rating'],
            'comment' => $data['comment'] ?? null,
            'submitted_at' => now(),
        ]);

        // Happy patients → Google; unhappy → thank-you (kept internal).
        if ($data['rating'] >= 4 && $tenant->google_review_url) {
            return redirect()->away($tenant->google_review_url);
        }

        return view('whatsapp.review-thanks', ['tenant' => $tenant]);
    }
}
