<?php

namespace App\Modules\HR\Reports\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class AttendanceDetailsExport implements FromCollection, WithHeadings
{
    protected $grouped;

    public function __construct($data)
    {
        $this->grouped = $data['grouped'];
    }

    public function collection()
    {
        $rows = collect();

        foreach ($this->grouped as $department => $records) {

            // Department Row
            $rows->push([$department, '', '', '', '', '', '', '', '', '']);

            foreach ($records as $row) {

                $shiftStart = optional($row->shift)->work_start_time;
                $shiftEnd   = optional($row->shift)->work_end_time;

                $shiftHrs = ($shiftStart && $shiftEnd)
                    ? \Carbon\Carbon::parse($shiftStart)
                        ->diffInMinutes(\Carbon\Carbon::parse($shiftEnd)) / 60
                    : 0;

                $totalOt = $row->ot_hrs + $row->dot_hrs;

                $rows->push([
                    $row->employee->employee_code,
                    $row->employee->first_name.' '.$row->employee->last_name,
                    optional($row->employee->department)->name,
                    optional($row->employee->designation)->name,
                    $row->attendance->attendance_date->format('Y-m-d'),
                    optional($row->shift)->name,
                    $row->in_time ? $row->in_time->format('H:i') : '',
                    $row->out_time ? $row->out_time->format('H:i') : '',
                    number_format($shiftHrs, 2),
                    $row->ot_hrs,
                    $row->dot_hrs,
                    number_format($totalOt, 2),
                ]);
            }
        }

        return $rows;
    }

    public function headings(): array
    {
        return [
            'Department / Emp Code',
            'Name',
            'Department',
            'Designatoin',
            'Date',
            'Shift',
            'In Time',
            'Out Time',
            'Shift Hrs',
            'OT Hrs',
            'DOT Hrs',
            'Total OT',
        ];
    }
}
