<?php

namespace App\Services\Admin\Services;

use App\Models\AcademicAdvisingLog;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class AcademicAdvisingLogService
{
    public function paginated(int $perPage = 25, string $search = '', ?int $lecturerId = null): LengthAwarePaginator
    {
        $user = auth()->user();

        return AcademicAdvisingLog::query()
            ->select(['id', 'lecturer_id', 'topic', 'notes', 'created_at'])
            ->with([
                'students.user.profile',
                'students.department',
                'lecturer.user.profile',
                'lecturer.departments',
            ])
            ->when($search, fn ($q) => $q->where('topic', 'like', "%{$search}%")
                ->orWhereHas('students', 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))
            ->when($user->hasRole('dosen'), fn ($q) => $q->where('lecturer_id', $user->lecturer?->id))
            ->latest()
            ->paginate($perPage);
    }

    public function create(array $data): AcademicAdvisingLog
    {
        $log = AcademicAdvisingLog::create([
            'lecturer_id' => $data['lecturer_id'],
            'topic' => $data['topic'] ?? null,
            'notes' => $data['notes'] ?? null,
        ]);

        $log->students()->attach($data['student_ids']);

        return $log;
    }

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

        $log->students()->sync($data['student_ids']);

        return $log;
    }

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