<?php

namespace App\Exports;

use App\Models\CheckinHistory;
use DateTime;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;

class HistoryCheckInExport implements FromQuery, WithMapping, WithHeadings
{

    public function headings(): array
    {
        if (app()->isLocale('en')) {

            return [
                'datetime',
                'in/out',
                'device',
                'userid',
                'username',
                'img'
            ];
        }
        else {
            return [
                '日時',
                'チェックイン/チェックアウト',
                'デバイス',
                'ユーザーID',
                'ユーザー名',
                '画像'
            ];
        }

    }
    
    private const STATUS_TRANSLATIONS = [
        'in' => [
            'en' => 'In',
            'ja' => '出勤'
        ],
        'out' => [
            'en' => 'Out',
            'ja' => '退勤'
        ]
    ];

    private function translateStatus(string $status): string
    {
        $locale = app()->getLocale();
        return self::STATUS_TRANSLATIONS[$status][$locale] ?? $status;
    }

    public function query()
    {
        $time = request()->only('time')['time'];
        list($year, $month) = explode('/', $time);

        return CheckinHistory::query()
            ->whereYear('checkin_at_time', $year)
            ->whereMonth('checkin_at_time', $month);
    }

    /**
     * @var Invoice $invoice
     */
    public function map($checkin): array
    {
//        return [
//            $checkin->checkin_at_time->format('Y/m/d H:i:s.v'),
//            $checkin->in_or_out ? 'in' : 'out',
//            $checkin->userWithTrashed->username,
//            $checkin->userWithTrashed->name,
//            $checkin->image,
//        ];
        $ret = [];
        $ret[] = $checkin->checkin_at_time->format('Y/m/d H:i:s');
        // $ret[] = $checkin->in_or_out ? 'in' : 'out';
        $ret[] = $this->translateStatus($checkin->in_or_out ? 'in' : 'out');
		$ret[] = $checkin->device;
        if(is_null($checkin->userWithTrashed)) {
            $ret[] = '';
            $ret[] = '';
        }else{
            $ret[] = $checkin->userWithTrashed->username;
            $ret[] = $checkin->userWithTrashed->name;
        }
        $ret[] = $checkin->image;
        return $ret;
    }
}
