<?php

namespace App\Http\Controllers;

use App\Models\Donor;
use App\Models\Region;
use App\Models\School;
use Illuminate\Http\Request;

class DonorController extends Controller
{
    public function index(Request $request)
    {
        $query = Donor::with(['region', 'school', 'assignedIntern']);

        if ($request->filled('region_id')) {
            $query->where('region_id', $request->region_id);
        }
        if ($request->filled('school_id')) {
            $query->where('school_id', $request->school_id);
        }
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('intern_id')) {
            $query->where('assigned_intern_id', $request->intern_id);
        }

        $donors = $query->latest()->paginate(25);
        $regions = Region::all();
        $schools = School::all();

        return view('donors.index', compact('donors', 'regions', 'schools'));
    }

    public function show(Donor $donor)
    {
        $donor->load(['region', 'school', 'assignedIntern', 'donations', 'interactions']);
        return view('donors.show', compact('donor'));
    }

    public function analytics()
    {
        // Aggregates for tracking dashboard
        $stats = [
            'total' => Donor::count(),
            'active_month' => Donor::where('last_contacted_at', '>=', now()->subMonth())->count(),
            'avg_gift' => Donor::avg('total_donated') ?? 0,
            'retention' => 76.8, // placeholder – compute properly
        ];

        return view('donors.analytics', compact('stats'));
    }
}
