<?php

namespace App\Modules\HR\Attendance\Repositories;

use App\Modules\HR\Attendance\Models\AttendanceImport;
use App\Modules\HR\Attendance\Models\AttendanceImportRow;
use App\Modules\HR\Employees\Models\Employee;
use Illuminate\Support\Collection;

class AttendanceImportRepository
{
    public function create(array $data): AttendanceImport
    {
        return AttendanceImport::query()->create($data);
    }

    public function addRow(AttendanceImport $import, array $data): AttendanceImportRow
    {
        return $import->rows()->create($data);
    }

    public function update(AttendanceImport $import, array $data): AttendanceImport
    {
        $import->update($data);

        return $import->fresh() ?? $import;
    }

    public function find(int $tenantId, int $id): ?AttendanceImport
    {
        return AttendanceImport::query()
            ->where('tenant_id', $tenantId)
            ->with('rows')
            ->find($id);
    }

    public function employeeByCode(int $tenantId, string $code): ?Employee
    {
        return Employee::query()
            ->where('tenant_id', $tenantId)
            ->where('employee_code', $code)
            ->first();
    }

    /** @return Collection<int, AttendanceImportRow> */
    public function validRows(AttendanceImport $import): Collection
    {
        return $import->rows()->where('is_valid', true)->orderBy('row_number')->get();
    }
}
