<?php

namespace App\Modules\HR\Reports\Data;

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

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

        // Date filter via attendance relationship
        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 — branch_id is on attendance table, not attendance_details
        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']);
            });
        }

        // Core condition: exactly one of in_time or out_time is missing (not both)
        $query->where(function ($q) {
            $q->where(function ($q2) {
                $q2->whereNull('in_time')->whereNotNull('out_time');
            })->orWhere(function ($q2) {
                $q2->whereNotNull('in_time')->whereNull('out_time');
            });
        });

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

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

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