<?php

namespace App\Modules\HR\Reports\Data;

use App\Modules\HR\Attendance\Models\AttendanceDetail;
use Carbon\Carbon;

class PresenteeismSummaryReport
{
    public function getData($filters)
    {
        $from = Carbon::parse($filters['from_date'])->startOfDay();
        $to   = Carbon::parse($filters['to_date'])->endOfDay();

        $query = AttendanceDetail::with(['employee.department', 'employee.designation'])
            ->join('attendance', 'attendance.id', '=', 'attendance_details.attendance_id')
            ->join('employees', 'employees.id', '=', 'attendance_details.employee_id')
            ->join('shifts', 'shifts.id', '=', 'attendance_details.shift_id')
            ->whereBetween('attendance.attendance_date', [$from, $to])
            ->whereColumn('attendance_details.attendance_status', '!=', 'shifts.absent_status');

        if (!empty($filters['branch_id'])) {
            $query->where('employees.branch_id', $filters['branch_id']);
        }

        if (!empty($filters['department_id'])) {
            $query->where('employees.department_id', $filters['department_id']);
        }

        $records = $query
            ->select(
                'attendance_details.*',
                'attendance.attendance_date as attendance_date'
            )
            ->orderBy('attendance.attendance_date')
            ->orderBy('employees.employee_code')
            ->get();

        $grouped = $records->groupBy(function ($row) {
            $date = $row->attendance_date;
            return $date instanceof Carbon ? $date->format('Y-m-d') : substr($date, 0, 10);
        });

        return [
            'grouped' => $grouped,
            'filters' => $filters,
        ];
    }
}
