<?php

namespace App\Http\Controllers;

use App\Models\Inspection;
use App\Models\Issue;
use App\Models\Project;
use Illuminate\Support\Facades\Auth;

class ProjectReportController extends Controller
{
    public function show(Project $project)
    {
        $user = Auth::user();
        if (! $user->can('manage all') && ! $project->users()->where('user_id', $user->id)->exists()) {
            abort(403);
        }

        $phases = $project->phases()
            ->with(['layers.features.inspections', 'layers.features.issues'])
            ->orderBy('order')
            ->get();

        $stats = [
            'total_features' => $phases->flatMap(fn ($p) => $p->layers)->flatMap(fn ($l) => $l->features)->count(),
            'completed_features' => $phases->flatMap(fn ($p) => $p->layers)->flatMap(fn ($l) => $l->features)->where('status', 'completed')->count(),
            'total_inspections' => Inspection::where('project_id', $project->id)->count(),
            'open_issues' => Issue::where('project_id', $project->id)->where('status', 'open')->count(),
            'avg_progress' => round($phases->avg('progress_percent') ?? 0),
        ];

        $pdf_data = compact('project', 'phases', 'stats');

        // Use Blade to render HTML, then return as "print" view
        // (barryvdh/laravel-dompdf is not installed, so we render a printable HTML page)
        return view('reports.project-report', $pdf_data);
    }
}
