<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use Inertia\Inertia;

/**
 * WorkoutController
 * Handles client workout views with support for JSON-based workout days
 */
class WorkoutController extends Controller
{
    /**
     * Display the client's workout routines
     */
    public function index()
    {
        $user = auth()->user();
        $client = $user->clientProfile ?? $user->client;
        
        if (!$client) {
            return Inertia::render('Client/Workout/Index', [
                'client' => null,
                'workouts' => [],
                'compliance_logs' => [],
                'no_profile' => true,
            ]);
        }
        
        $workouts = $client->workouts()
            ->with('exercises')
            ->where('is_active', true)
            ->get();
            
        $complianceLogs = $client->complianceLogs()
            ->where('resource_type', 'workout')
            ->whereDate('completed_at', '>=', now()->subDays(30))
            ->get();
        
        // Calculate total completions per workout
        $completionCounts = $complianceLogs->groupBy('resource_id')
            ->map(fn($logs) => $logs->count());
        
        return Inertia::render('Client/Workout/Index', [
            'client' => $client,
            'workouts' => $workouts,
            'compliance_logs' => $complianceLogs,
            'completion_counts' => $completionCounts,
        ]);
    }
    
    /**
     * Generate PDF for a workout
     */
    public function pdf($workoutId)
    {
        $user = auth()->user();
        $client = $user->clientProfile ?? $user->client;
        
        if (!$client) {
            abort(404);
        }
        
        $workout = $client->workouts()->findOrFail($workoutId);
        
        // Use PdfService to generate the PDF
        $pdfService = app(\App\Services\PdfService::class);
        $path = $pdfService->generateWorkout($workout);
        
        return $pdfService->download($path);
    }
}
