<?php

namespace App\Http\Controllers\Component3;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Component3\C3PreventionRegister;
use App\Http\Requests\StoreC3PreventionRegisterRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class C3PreventionRegisterController extends Controller
{
    public function index()
    {
        $registers = C3PreventionRegister::latest('session_date')
            ->paginate(25);

        return view('component3.prevention.index', compact('registers'));
    }

    public function create()
    {
        return view('component3.prevention.create');
    }

    public function store(StoreC3PreventionRegisterRequest $request)
    {
        $data = $request->validated();
        $data['created_by'] = auth()->id();

        C3PreventionRegister::create($data);

        return redirect()->route('component3.prevention.index')
            ->with('success', 'Prevention session recorded successfully.');
    }
    public function edit($id)
    {
        $register = C3PreventionRegister::findOrFail($id);

        return view('component3.prevention.edit', compact('register'));
    }
    public function update(StoreC3PreventionRegisterRequest $request, $id)
    {
        $register = C3PreventionRegister::findOrFail($id);
        $data = $request->validated();
        $register->update($data);

        return redirect()->route('component3.prevention.index')
            ->with('success', 'Prevention session updated successfully.');
    }
    public function show($id)
    {
        $register = C3PreventionRegister::findOrFail($id);

        return view('component3.prevention.show', compact('register'));
    }

    public function reports()
    {
        // 1. Monthly trend: sessions count + total participants
        $monthlyData = C3PreventionRegister::selectRaw('
                DATE_FORMAT(session_date, "%Y-%m") as month,
                COUNT(*) as total_participants,
                COUNT(DISTINCT session_date, county, payam) as estimated_sessions
            ')
            ->where('session_date', '>=', now()->subYear())
            ->groupBy('month')
            ->orderBy('month')
            ->get();

        // 2. County breakdown
        $counties = C3PreventionRegister::select('county', \DB::raw('COUNT(*) as participants'))
            ->groupBy('county')
            ->orderByDesc('participants')
            ->take(10)
            ->get();

        // 3. Top topics/activities (based on boolean flags)
        $activities = [
            'Prevention Messages' => C3PreventionRegister::where('prevention_messages', 1)->count(),
            'Referral Pathways' => C3PreventionRegister::where('referral_pathways', 1)->count(),
            'Conflict Resolution' => C3PreventionRegister::where('conflict_resolution', 1)->count(),
            'Male Engagement Dialogue' => C3PreventionRegister::where('male_engagement_dialogue', 1)->count(),
            'Positive Masculinity' => C3PreventionRegister::where('positive_masculinity_activity', 1)->count(),
            'Received IEC Materials' => C3PreventionRegister::where('received_iec_materials', 1)->count(),
            'Radio Talkshows' => C3PreventionRegister::where('received_radio_talkshows', 1)->count(),
        ];
        arsort($activities);
        $topActivities = collect($activities)->take(8);

        // 4. Gender breakdown
        $totalFemale = C3PreventionRegister::where('gender', 'F')->count();
        $totalMale = C3PreventionRegister::where('gender', 'M')->count();
        $totalParticipants = $totalFemale + $totalMale;
        $femalePercent = $totalParticipants > 0 ? round(($totalFemale / $totalParticipants) * 100) : 0;

        // 5. Estimate total sessions (distinct session_date + location)
        $totalSessions = C3PreventionRegister::select('session_date', 'county', 'payam')
            ->distinct()
            ->whereNotNull('session_date')
            ->count();

        $avgPerSession = $totalSessions > 0 ? round($totalParticipants / $totalSessions, 1) : 0;

        // 6. Recent sessions (group by session_date + location for display)
        $recentSessions = C3PreventionRegister::select(
                'session_date',
                'county',
                'payam',
                \DB::raw('COUNT(*) as total_participants'),
                \DB::raw('SUM(gender = "F") as females'),
                \DB::raw('SUM(gender = "M") as males')
            )
            ->groupBy('session_date', 'county', 'payam')
            ->orderByDesc('session_date')
            ->take(15)
            ->get();

        $chartData = [
            'months' => $monthlyData->pluck('month')->map(fn($m) => date('M Y', strtotime($m))),
            'participantsByMonth' => $monthlyData->pluck('total_participants'),
            'sessionsByMonth' => $monthlyData->pluck('estimated_sessions'),
            'counties' => $counties->map(fn($c) => ['county' => $c->county, 'count' => $c->participants]),
            'topics' => $topActivities->map(fn($count, $topic) => ['topic' => $topic, 'count' => $count]),
            'genderData' => ['male' => $totalMale,'female' => $totalFemale],
            'topCounties' => [
                'names' => $counties->pluck('county')->toArray(),
                'values' => $counties->pluck('participants')->toArray()
            ],
            'topActivities' => [
                'names' => $topActivities->keys()->toArray(),
                'values' => $topActivities->values()->toArray()
            ]
        ];

        return view('component3.prevention.reports', compact(
            'chartData',
            'totalSessions',
            'totalParticipants',
            'totalFemale',
            'totalMale',
            'femalePercent',
            'avgPerSession',
            'recentSessions',
        ));
    }
}