<?php

namespace App\Modules\HR\Training\Repositories;

use App\Modules\HR\Training\Models\TrainingCourse;
use App\Modules\HR\Training\Models\TrainingEnrollment;
use App\Modules\HR\Training\Models\TrainingSession;

class TrainingRepository
{
    public function courses(int $tenant)
    {
        return TrainingCourse::query()->where('tenant_id', $tenant)->latest()->paginate();
    }

    public function sessions(int $tenant)
    {
        return TrainingSession::query()->where('tenant_id', $tenant)->latest('starts_at')->paginate();
    }

    public function saveCourse(int $tenant, array $data, ?TrainingCourse $course = null): TrainingCourse
    {
        $course ??= new TrainingCourse(['tenant_id' => $tenant]);
        $course->fill($data)->save();

        return $course;
    }

    public function saveSession(int $tenant, array $data, ?TrainingSession $session = null): TrainingSession
    {
        $session ??= new TrainingSession(['tenant_id' => $tenant]);
        $session->fill($data)->save();

        return $session;
    }

    public function enroll(int $tenant, int $session, array $employeeIds): void
    {
        foreach ($employeeIds as $employee) {
            TrainingEnrollment::query()->firstOrCreate(
                ['session_id' => $session, 'employee_id' => $employee],
                ['tenant_id' => $tenant, 'status' => 'enrolled'],
            );
        }
    }

    public function deleteCourse(TrainingCourse $course): void
    {
        $course->delete();
    }

    public function deleteSession(TrainingSession $session): void
    {
        $session->delete();
    }
}
