<?php

namespace App\Services\Admin\Services;

use App\Models\AcademicAdvisingLog;
use App\Models\Lecturer;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;

class AcademicAdvisingLogService
{
    /**
     * @return Collection<int, AcademicAdvisingLog>
     */
    public function forLecturer(Lecturer $lecturer): Collection
    {
        return AcademicAdvisingLog::query()
            ->where('lecturer_id', $lecturer->id)
            ->with('student.user.profile')
            ->latest()
            ->get();
    }

    public function paginated(int $perPage = 25, string $search = '', ?int $lecturerId = null): LengthAwarePaginator
    {
        return AcademicAdvisingLog::query()
            ->select(['id', 'student_id', 'lecturer_id', 'topic', 'notes', 'session_date', 'created_at'])
            ->with([
                'student.user.profile',
                'student.department',
                'lecturer.user.profile',
            ])
            ->when($search, fn ($q) => $q->where('topic', 'like', "%{$search}%")
                ->orWhereHas('student', fn ($q) => $q->where('student_number', 'like', "%{$search}%")
                    ->orWhereHas('user.profile', fn ($q) => $q->where('full_name', 'like', "%{$search}%"))))
            ->when($lecturerId, fn ($q) => $q->where('lecturer_id', $lecturerId))
            ->latest()
            ->paginate($perPage);
    }

    public function create(array $data): AcademicAdvisingLog
    {
        return AcademicAdvisingLog::create([
            'student_id' => $data['student_id'],
            'lecturer_id' => $data['lecturer_id'],
            'topic' => $data['topic'] ?? null,
            'notes' => $data['notes'] ?? null,
            'session_date' => $data['session_date'] ?? now(),
        ]);
    }

    public function update(AcademicAdvisingLog $log, array $data): AcademicAdvisingLog
    {
        $log->student_id = $data['student_id'];
        $log->lecturer_id = $data['lecturer_id'];
        $log->topic = $data['topic'] ?? null;
        $log->notes = $data['notes'] ?? null;
        $log->session_date = $data['session_date'] ?? now();
        $log->update();

        return $log;
    }

    public function delete(AcademicAdvisingLog $log): bool
    {
        return $log->delete();
    }
}
