<?php

namespace App\Services\Admin\Master;

use App\Models\AcademicTerm;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;

class AcademicTermService
{
    public function getAllForSelect(): Collection
    {
        return AcademicTerm::select(['id', 'name', 'semester', 'start_date', 'end_date', 'is_active'])->latest()->get();
    }

    /**
     * The academic term currently marked active, falling back to the one with
     * the latest start date if none is explicitly active.
     */
    public function getActive(): ?AcademicTerm
    {
        return AcademicTerm::where('is_active', true)->first()
            ?? AcademicTerm::orderByDesc('start_date')->first();
    }

    public function paginated(int $perPage = 25, string $search = '', ?string $semester = null, ?bool $isActive = null): LengthAwarePaginator
    {
        return AcademicTerm::query()
            ->select(['id', 'name', 'semester', 'start_date', 'end_date', 'is_active'])
            ->when($search, fn ($q) => $q->where('name', 'like', "%{$search}%"))
            ->when($semester, fn ($q) => $q->where('semester', $semester))
            ->when($isActive !== null, fn ($q) => $q->where('is_active', $isActive))
            ->latest()
            ->paginate($perPage);
    }

    public function create(array $data): AcademicTerm
    {
        return AcademicTerm::create($data);
    }

    public function update(AcademicTerm $academicTerm, array $data): AcademicTerm
    {
        $academicTerm->name = $data['name'];
        $academicTerm->semester = $data['semester'];
        $academicTerm->start_date = $data['start_date'];
        $academicTerm->end_date = $data['end_date'];
        $academicTerm->is_active = $data['is_active'];
        $academicTerm->update();

        return $academicTerm;
    }

    public function delete(AcademicTerm $academicTerm): bool
    {
        return $academicTerm->delete();
    }

    public function updateActiveStatus(AcademicTerm $academicTerm, bool $isActive): void
    {
        DB::transaction(function () use ($academicTerm, $isActive) {
            if ($isActive) {
                AcademicTerm::where('id', '!=', $academicTerm->id)->update(['is_active' => false]);
            }

            $academicTerm->update(['is_active' => $isActive]);
        });
    }
}
