<?php

namespace App\Http\Controllers\Component3;

use App\Http\Controllers\Controller;
use App\Models\Component3\C3HotlineRegister as HotlineRegister;
use App\Models\Component3\C3PreventionRegister as PreventionRegister;
use App\Models\Component3\C3CallLog as CallLog;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function index()
    {
        // ── Hotline Quick Stats ──
        $totalIncidents       = HotlineRegister::count();
        $incidentsLast30Days  = HotlineRegister::where('date_of_report', '>=', now()->subDays(30))->count();
        $withConsent          = HotlineRegister::where('consent_given_for_information_sharing', true)->count();
        $withoutConsent       = $totalIncidents - $withConsent;

        // GBV Types Distribution
        $gbvTypes = HotlineRegister::select('gbv_type', DB::raw('count(*) as total'))
                    ->groupBy('gbv_type')
                    ->pluck('total', 'gbv_type');

        // ── Prevention Quick Stats ──
        $totalBeneficiaries   = PreventionRegister::count();
        $femaleBeneficiaries  = PreventionRegister::where('gender', 'F')->count();
        $maleBeneficiaries    = PreventionRegister::where('gender', 'M')->count();

        $sessionsByType = PreventionRegister::selectRaw(
                "
                    SUM(prevention_messages) as prevention_messages,
                    SUM(referral_pathways) as referral_pathways,
                    SUM(conflict_resolution) as conflict_resolution,
                    SUM(male_engagement_dialogue) as male_engagement,
                    SUM(positive_masculinity_activity) as positive_masculinity
                "
            )->first();

        $iri_3_1 = \App\Models\Component3\CallLog::where('satisfaction_feedback', true)->count(); // Satisfied survivors

        $iri_3_2 = \App\Models\Component3\C3PreventionRegister::count(); // People reporting increased awareness

        $iri_3_3 = \App\Models\Component3\C3PreventionRegister::where('gender', 'F')
                    ->orWhere('gender', 'M')
                    ->count(); // Total people benefitting from actions to end GBV

        $iri_3_4 = \App\Models\Component3\C3PreventionRegister::where('gender', 'F')->count(); // Female

        $iri_3_5 = \App\Models\Component3\C3PreventionRegister::whereIn('category_of_participants', [
                        'Adolescent Girl', 'Adolescent Boy'
                    ])->orWhere(function($q) {
                        $q->where('age', '>=', 10)->where('age', '<=', 24);
                    })->count(); // Youth (10–24 years)

        return view('component3.dashboard', compact(
            'totalIncidents', 'incidentsLast30Days', 'withConsent', 'withoutConsent',
            'gbvTypes', 'totalBeneficiaries', 'femaleBeneficiaries', 'maleBeneficiaries',
            'sessionsByType','iri_3_1', 'iri_3_2', 'iri_3_3', 'iri_3_4', 'iri_3_5'
        ));
    }
}