<?php

namespace App\Modules\Exports\ExportHandlers;

use App\Modules\Exports\ExportHandlers\Contracts\ExportHandlerInterface;
use App\Modules\Exports\Models\Export;
use App\Modules\Exports\Repositories\ExportRepository;
use App\Modules\Exports\Support\CsvStreamWriter;
use App\Modules\HR\Attendance\Repositories\AttendanceRecordRepository;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Storage;

class AttendanceReportExportHandler implements ExportHandlerInterface
{
    public function __construct(
        private readonly AttendanceRecordRepository $records,
        private readonly ExportRepository $exports,
    ) {}

    public function handle(Export $export): void
    {
        $filters = $export->filters ?? [];
        $from = (string) ($filters['from'] ?? now()->subMonth()->toDateString());
        $to = (string) ($filters['to'] ?? now()->toDateString());
        $tenantId = (int) $export->tenant_id;
        $relPath = 'exports/'.$tenantId.'/'.$export->id.'.csv';
        $abs = Storage::disk('local')->path($relPath);
        $csv = new CsvStreamWriter($abs);
        $csv->open();
        $csv->writeRow([
            'attendance_date',
            'employee_code',
            'employee_name',
            'check_in_at',
            'check_out_at',
            'status',
            'source',
            'missing_checkout',
            'overtime_minutes',
        ]);
        $rows = 0;
        foreach ($this->records->cursorForTenantDateRange($tenantId, $from, $to) as $r) {
            $csv->writeRow([
                $r->attendance_date?->format('Y-m-d'),
                $r->employee?->employee_code,
                $r->employee?->full_name,
                $r->check_in_at?->format('Y-m-d H:i:s'),
                $r->check_out_at?->format('Y-m-d H:i:s'),
                $r->status,
                $r->source,
                $r->missing_checkout ? '1' : '0',
                $r->overtime_minutes,
            ]);
            $rows++;
        }
        $csv->close();
        $name = 'attendance_'.$from.'_'.$to.'_'.CarbonImmutable::now()->format('Ymd_His').'.csv';
        $this->exports->update($export, [
            'file_path' => $relPath,
            'file_name' => $name,
            'mime_type' => 'text/csv; charset=UTF-8',
            'total_rows' => $rows,
        ]);
    }
}
