<?php

namespace App\Modules\HR\Reports\Data;

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

class PresenteeismDetailsReport
{
    // Statuses where employee was present for at least part of the day
    const PRESENT_STATUSES = ['P', 'HP+HA', 'HA+HP', 'HP+HDF', 'HDF+HP'];

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

        // Date filter
        if (!empty($filters['from_date']) && !empty($filters['to_date'])) {
            $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 — via attendance table
        if (!empty($filters['branch_id'])) {
            $query->whereHas('attendance', 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
        if (!empty($filters['employee_id'])) {
            $query->where('employee_id', $filters['employee_id']);
        }

        // Present condition
        $query->whereIn('attendance_status', self::PRESENT_STATUSES);

        $records = $query->orderBy('attendance_id')->get();

        // Group by date
        $grouped = $records->groupBy(function ($row) {
            return optional($row->attendance)->attendance_date
                ? $row->attendance->attendance_date->format('Y-m-d')
                : 'Unknown';
        })->sortKeys();

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