<?php

namespace App\Http\Controllers\Coach;

use App\Http\Controllers\Controller;
use App\Models\LandingTestimonial;
use App\Models\User;
use App\Notifications\NewTestimonialSubmitted;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;

class TestimonialController extends Controller
{
    /**
     * Display coach's testimonials and submission form.
     */
    public function index(Request $request)
    {
        $coach = $request->user();

        $testimonials = LandingTestimonial::where('coach_id', $coach->id)
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($testimonial) {
                return [
                    'id' => $testimonial->id,
                    'content' => $testimonial->content,
                    'rating' => $testimonial->rating,
                    'status' => $testimonial->status,
                    'rejection_reason' => $testimonial->rejection_reason,
                    'submitted_at' => $testimonial->submitted_at?->format('d/m/Y H:i'),
                    'reviewed_at' => $testimonial->reviewed_at?->format('d/m/Y H:i'),
                ];
            });

        return Inertia::render('Coach/Testimonials/Index', [
            'testimonials' => $testimonials,
            'canSubmit' => $this->canSubmitTestimonial($coach),
            'coachAvatar' => $coach->avatar_url,
            'coachName' => $coach->name,
            'coachSpecialization' => $coach->specialization,
        ]);
    }

    /**
     * Store a new testimonial from coach.
     */
    public function store(Request $request)
    {
        $coach = $request->user();

        if (!$this->canSubmitTestimonial($coach)) {
            return back()->withErrors([
                'limit' => 'Ya tienes un testimonio pendiente de revisión o aprobado.',
            ]);
        }

        $validated = $request->validate([
            'content' => 'required|string|min:50|max:500',
            'rating' => 'required|integer|min:1|max:5',
            'avatar' => 'nullable|image|max:2048',
        ], [
            'content.required' => 'El testimonio es obligatorio.',
            'content.min' => 'El testimonio debe tener al menos 50 caracteres.',
            'content.max' => 'El testimonio no puede superar los 500 caracteres.',
            'rating.required' => 'La valoración es obligatoria.',
            'rating.min' => 'La valoración mínima es 1 estrella.',
            'rating.max' => 'La valoración máxima es 5 estrellas.',
            'avatar.image' => 'El archivo debe ser una imagen.',
            'avatar.max' => 'La imagen no puede superar los 2MB.',
        ]);

        $avatarPath = null;
        if ($request->hasFile('avatar')) {
            $avatarPath = $request->file('avatar')->store('testimonials', 'public');
            $avatarPath = Storage::disk('public')->url($avatarPath);
        } else {
            // Use coach's profile photo if available
            $avatarPath = $coach->avatar_url ?? null;
        }

        $testimonial = LandingTestimonial::create([
            'coach_id' => $coach->id,
            'name' => $coach->name,
            'role' => $coach->specialization ?? 'Coach Fitness',
            'content' => $validated['content'],
            'rating' => $validated['rating'],
            'avatar' => $avatarPath,
            'status' => LandingTestimonial::STATUS_PENDING,
            'source' => LandingTestimonial::SOURCE_COACH,
            'is_active' => false,
            'submitted_at' => now(),
        ]);

        // Notify all admins about the new testimonial
        $admins = User::where('role', 'admin')->get();
        foreach ($admins as $admin) {
            $admin->notify(new NewTestimonialSubmitted($testimonial));
        }

        return back()->with('success', '¡Gracias por tu testimonio! Será revisado por nuestro equipo.');
    }

    /**
     * Check if coach can submit a new testimonial.
     */
    protected function canSubmitTestimonial($coach): bool
    {
        // Coach can only have one pending or approved testimonial
        return !LandingTestimonial::where('coach_id', $coach->id)
            ->whereIn('status', [
                LandingTestimonial::STATUS_PENDING,
                LandingTestimonial::STATUS_APPROVED,
            ])
            ->exists();
    }

    /**
     * Delete a rejected testimonial.
     */
    public function destroy(Request $request, LandingTestimonial $testimonial)
    {
        $coach = $request->user();

        if ($testimonial->coach_id !== $coach->id) {
            abort(403);
        }

        if ($testimonial->status !== LandingTestimonial::STATUS_REJECTED) {
            return back()->withErrors([
                'delete' => 'Solo puedes eliminar testimonios rechazados.',
            ]);
        }

        $testimonial->delete();

        return back()->with('success', 'Testimonio eliminado.');
    }
}
