<?php

namespace App\Services\Events;

use App\Models\EventCharges;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;

class EventChargeQueryService
{
    public function list(array $filters): array
    {
        $perPage = (int) ($filters['per_page'] ?? 25);
        $page = (int) ($filters['page'] ?? 1);

        $query = EventCharges::query()
            ->select([
                'event_charges.*',
                'users.firstname AS parent_firstname',
                'users.lastname AS parent_lastname',
                'students.firstname AS student_firstname',
                'students.lastname AS student_lastname',
                'events.event_name',
            ])
            ->leftJoin('users', 'users.id', '=', 'event_charges.parent_id')
            ->leftJoin('students', 'students.id', '=', 'event_charges.student_id')
            ->leftJoin('events', 'events.id', '=', 'event_charges.event_id');

        if (!empty($filters['school_year'])) {
            $query->where('event_charges.school_year', (string) $filters['school_year']);
        }
        if (!empty($filters['semester'])) {
            $query->where('event_charges.semester', (string) $filters['semester']);
        }
        if (!empty($filters['parent_id'])) {
            $query->where('event_charges.parent_id', (int) $filters['parent_id']);
        }
        if (!empty($filters['event_id'])) {
            $query->where('event_charges.event_id', (int) $filters['event_id']);
        }

        $paginator = $query->orderByDesc('event_charges.created_at')
            ->paginate($perPage, ['*'], 'page', $page);

        return [
            'charges' => $paginator,
            'pagination' => $this->paginationPayload($paginator),
        ];
    }

    private function paginationPayload(LengthAwarePaginator $paginator): array
    {
        return [
            'current_page' => $paginator->currentPage(),
            'per_page' => $paginator->perPage(),
            'total' => $paginator->total(),
            'total_pages' => $paginator->lastPage(),
        ];
    }
}
