<?php

namespace App\Modules\HR\Reports\Data;

use App\Modules\HR\Attendance\Models\AttendanceDetail;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class SubsequentAbsenteeismSummaryReport
{
    public function getData($filters)
    {
        $toDate     = Carbon::parse($filters['to_date'])->endOfDay();
        $noOfDays   = (int) $filters['no_of_days'];

        $fromDate = $toDate->copy()->subDays($noOfDays - 1)->startOfDay();

        $query = AttendanceDetail::with([
            'employee.department',
            'employee.designation',
            'attendance',
            'shift'
        ]);

        // ✅ Date Range
        $query->whereHas('attendance', function ($q) use ($fromDate, $toDate) {
            $q->whereBetween('attendance_date', [$fromDate, $toDate]);
        });

        // ✅ Branch Filter
        if (!empty($filters['branch_id'])) {
            $query->whereHas('employee', function ($q) use ($filters) {
                $q->where('branch_id', $filters['branch_id']);
            });
        }

        // ✅ Department Filter
        if (!empty($filters['department_id'])) {
            $query->whereHas('employee', function ($q) use ($filters) {
                $q->where('department_id', $filters['department_id']);
            });
        }

        // ✅ Absent Condition
        $query->whereHas('shift', function ($q) {
            $q->whereColumn('attendance_details.attendance_status', 'shifts.absent_status');
        });

        $records = $query->get();

        // 🔥 Group by Employee
        $grouped = $records->groupBy('employee_id');

        // 🔥 Only employees absent for ALL days
        $final = $grouped->filter(function ($items) use ($noOfDays) {
            return $items->count() == $noOfDays;
        });

        return [
            'employees' => $final->values()
        ];
    }
}
