<?php
namespace App\Http\Controllers;
use App\Models\{Activity,AuditLog,AttendanceSession,Letter,Member,News,Organization,PopupAnnouncement,Program,WhatsAppLog};
use App\Services\OrganizationAccess;
use Illuminate\Http\Request;
class DashboardController extends Controller {
    public function index(Request $request){
        $u=$request->user();
        $orgs=$u->isSuperAdmin()?Organization::where('is_active',true)->orderBy('type')->orderBy('name')->get():Organization::whereKey($u->organization_id)->get();
        $programQ=OrganizationAccess::apply(Program::query(),$u); $letterQ=OrganizationAccess::apply(Letter::query(),$u); $newsQ=OrganizationAccess::apply(News::query(),$u); $memberQ=OrganizationAccess::apply(Member::query(),$u); $activityQ=OrganizationAccess::apply(Activity::query(),$u); $waQ=OrganizationAccess::apply(WhatsAppLog::query(),$u);
        $stats=[
            'members'=>(clone $memberQ)->where('is_active',true)->count(),
            'rantings'=>$u->isSuperAdmin()?Organization::where('type','ranting')->where('is_active',true)->count():0,
            'units'=>$u->isSuperAdmin()?Organization::whereIn('type',['banom','lembaga'])->where('is_active',true)->count():1,
            'programs'=>(clone $programQ)->count(), 'program_progress'=>(int)round((clone $programQ)->avg('progress')??0),
            'letters_pending'=>(clone $letterQ)->whereIn('status',['draft','pending','disposition'])->count(),
            'news_month'=>(clone $newsQ)->whereMonth('created_at',now()->month)->count(),
            'activities_month'=>(clone $activityQ)->whereMonth('start_at',now()->month)->count(),
            'wa_clicks'=>(clone $waQ)->whereDate('clicked_at','>=',now()->subDays(7))->count(),
            'attendance_open'=>$u->isSuperAdmin()?AttendanceSession::where('is_active',true)->count():AttendanceSession::where('organization_id',$u->organization_id)->where('is_active',true)->count(),
            'popup_active'=>$u->isSuperAdmin()?PopupAnnouncement::currentlyActive()->count():0,
        ];
        $programs=(clone $programQ)->with('organization')->orderByDesc('progress')->limit(8)->get();
        $attention=(clone $programQ)->with('organization')->where(function($q){$q->where('status','late')->orWhere(fn($x)=>$x->whereNotNull('due_date')->whereDate('due_date','<',now())->where('status','!=','done'));})->limit(6)->get();
        $activities=(clone $activityQ)->with('organization')->whereNotNull('start_at')->where('start_at','>=',now()->subDay())->orderBy('start_at')->limit(5)->get();
        $audit=OrganizationAccess::apply(AuditLog::with(['organization','user'])->latest('created_at'),$u)->limit(12)->get();
        return view('admin.dashboard.index',compact('orgs','stats','programs','attention','activities','audit'));
    }
}
