<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\FeasibilityReport;
use App\Models\State;
use App\Services\ReportGeneratorService;
use Illuminate\Http\Request;

class FeasibilityController extends Controller
{
    public function __construct(private readonly ReportGeneratorService $generator) {}
    public function index(Request $request)
    {
        $query = FeasibilityReport::with(['user', 'state', 'city', 'zone']);
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('state_id')) {
            $query->where('state_id', $request->state_id);
        }
        $reports = $query->latest()->paginate(20)->withQueryString();
        $states  = State::orderBy('name')->get();
        return view('admin.feasibility.index', compact('reports', 'states'));
    }

    public function show(FeasibilityReport $feasibility)
    {
        $feasibility->load(['user', 'state', 'city', 'zone', 'zoneRule']);
        // The view uses $report variable name
        $report = $feasibility;
        return view('admin.feasibility.show', compact('report'));
    }

    public function pdf(int $id)
    {
        $report = FeasibilityReport::findOrFail($id);
        if ($report->status !== 'completed') {
            return back()->with('error', 'PDF only available for completed reports.');
        }
        return $this->generator->download($report);
    }

    public function destroy(FeasibilityReport $feasibility)
    {
        $feasibility->delete();
        return redirect()->route('admin.feasibility.index')->with('success', 'Report deleted.');
    }
}
