<?php

namespace App\Modules\HR\Reports\Data;

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

class OvertimeDetailsReport
{
    public function getData($filters)
    {
        $query = AttendanceDetail::with([
            'employee.department',
            'employee.designation',
            'attendance',
            'shift'
        ]);

        // ✅ Date Filter
        $from = Carbon::parse($filters['from_date'])->startOfDay();
        $to   = Carbon::parse($filters['to_date'])->endOfDay();

        $query->whereHas('attendance', function ($q) use ($from, $to) {
            $q->whereBetween('attendance_date', [$from, $to]);
        });

        // ✅ 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']);
            });
        }

        // ✅ Employee Filter (Optional)
        if (!empty($filters['employee_id'])) {
            $query->where('employee_id', $filters['employee_id']);
        }

        // ✅ Only Overtime Records
        $query->where(function ($q) {
            $q->where('ot_minutes', '>', 0)
              ->orWhere('dot_minutes', '>', 0);
        });

        $records = $query->get();

        // 🔥 If employee selected → no grouping
        if (!empty($filters['employee_id'])) {
            return [
                'single_employee' => true,
                'records' => $records
            ];
        }

        // 🔥 Else group by Department
        $grouped = $records->groupBy(function ($item) {
            return optional($item->employee->department)->name;
        });

        return [
            'single_employee' => false,
            'grouped' => $grouped
        ];
    }
}