<?php

namespace App\Http\Controllers;

use App\Models\Attendance;
use App\Models\Batch;
use App\Models\Course;
use App\Models\Student;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function index()
    {
        $today = now()->toDateString();

        // Stat cards
        $totalCourses  = Course::count();
        $totalBatches  = Batch::where('status', 'Running')->count();
        $totalStudents = Student::where('status', 'Active')->count();

        // Today's attendance %
        $todayRecords = Attendance::where('date', $today)->get();
        $todayPct     = null;
        if ($todayRecords->count() > 0) {
            $good     = $todayRecords->whereIn('status', ['present', 'late'])->count();
            $todayPct = round(($good / $todayRecords->count()) * 100);
        }

        // Today's attendance batch-wise breakdown — only batches with records today
        $todayBatchBreakdown = Attendance::where('date', $today)
            ->selectRaw('batch_id, COUNT(*) as total_records,
                SUM(CASE WHEN status IN ("present","late") THEN 1 ELSE 0 END) as present_count')
            ->groupBy('batch_id')
            ->get()
            ->map(function($row) {
                $batch = \App\Models\Batch::find($row->batch_id);
                $totalStudents = $batch ? $batch->students()->count() : $row->total_records;
                return [
                    'batch'   => $batch?->name ?? '—',
                    'present' => $row->present_count,
                    'total'   => $totalStudents,
                ];
            })
            ->filter(fn($b) => $b['total'] > 0)
            ->values();

        // Current active batch — Running batch with most students
        $currentBatch = Batch::where('status', 'Running')
            ->withCount('students')
            ->orderByDesc('students_count')
            ->first();
        $currentBatchPresent = $currentBatch
            ? Attendance::where('batch_id', $currentBatch->id)
                ->where('date', $today)
                ->whereIn('status', ['present','late'])
                ->count()
            : 0;
        $currentBatchTotal = $currentBatch?->students_count ?? 0;

        // Overall batch-wise split
        $overallBatchBreakdown = Batch::withCount(['students as total_students'])
            ->get()
            ->map(function($b) {
                $recs    = Attendance::where('batch_id', $b->id)->get();
                $present = $recs->where('status','present')->count();
                $late    = $recs->where('status','late')->count();
                $absent  = $recs->where('status','absent')->count();
                $total   = $present + $late + $absent;
                return [
                    'batch'   => $b->name,
                    'present' => $present,
                    'late'    => $late,
                    'absent'  => $absent,
                    'total'   => $total,
                    'pct'     => $total > 0 ? round(($present+$late)/$total*100) : 0,
                ];
            })
            ->filter(fn($b) => $b['total'] > 0)
            ->values();

        // Last 7 days attendance trend
        $weeklyTrend = [];
        for ($i = 6; $i >= 0; $i--) {
            $date    = now()->subDays($i)->toDateString();
            $dayName = now()->subDays($i)->format('D');
            $recs    = Attendance::where('date', $date)->get();
            $pct     = $recs->count() > 0
                ? round(($recs->whereIn('status', ['present', 'late'])->count() / $recs->count()) * 100)
                : 0;
            $weeklyTrend[] = ['day' => $dayName, 'pct' => $pct, 'total' => $recs->count()];
        }

        // Overall attendance split (all time)
        $allAtt = Attendance::select('status', DB::raw('count(*) as cnt'))
            ->groupBy('status')->pluck('cnt', 'status');
        $present = $allAtt['present'] ?? 0;
        $late    = $allAtt['late']    ?? 0;
        $absent  = $allAtt['absent']  ?? 0;
        $total   = $present + $late + $absent;
        $overallPct = $total > 0 ? round((($present + $late) / $total) * 100) : 0;

        // Recent activity (last 5 attendance saves)
        $recentActivity = Attendance::with(['student:id,name', 'batch:id,name'])
            ->orderBy('updated_at', 'desc')
            ->limit(5)
            ->get()
            ->map(fn($a) => [
                'student' => $a->student->name ?? '—',
                'batch'   => $a->batch->name   ?? '—',
                'status'  => $a->status,
                'date'    => $a->date->format('d M'),
                'time'    => $a->updated_at->diffForHumans(),
            ]);

        return view('dashboard', compact(
            'totalCourses', 'totalBatches', 'totalStudents',
            'todayPct', 'todayBatchBreakdown',
            'currentBatch', 'currentBatchPresent', 'currentBatchTotal',
            'weeklyTrend',
            'present', 'late', 'absent', 'overallPct', 'overallBatchBreakdown',
            'recentActivity'
        ));
    }
}
