<?php

namespace App\Http\Controllers\Coach;

use App\Http\Controllers\Controller;
use App\Models\CoachResult;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\Storage;

class ResultController extends Controller
{
    public function index()
    {
        $results = auth()->user()->coachResults()->latest()->get();
        return Inertia::render('Coach/Results/Index', [
            'results' => $results
        ]);
    }

    public function create()
    {
        return Inertia::render('Coach/Results/Create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'before_image' => 'required|image|max:10240', // 10MB
            'after_image' => 'required|image|max:10240', // 10MB
            'description' => 'nullable|string',
        ]);

        $beforePath = $request->file('before_image')->store('results/before', 'public');
        $afterPath = $request->file('after_image')->store('results/after', 'public');

        auth()->user()->coachResults()->create([
            'title' => $request->title,
            'before_image' => $beforePath,
            'after_image' => $afterPath,
            'description' => $request->description,
        ]);

        return redirect()->route('coach.results.index')->with('success', 'Resultado publicado correctamente.');
    }

    public function destroy(CoachResult $result)
    {
        // Ensure result belongs to coach
        if ($result->user_id !== auth()->id()) {
            abort(403);
        }

        // Delete images
        Storage::disk('public')->delete([$result->before_image, $result->after_image]);

        $result->delete();

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