<?php

namespace App\Services\ClassProgress;

use App\Models\ClassProgressAttachment;
use App\Models\ClassProgressReport;
use App\Models\TeacherClass;
use App\Models\User;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class ClassProgressQueryService
{
    public function __construct(
        private ClassProgressRuleService $rules
    ) {}

    public function listReports(User $user, array $filters): LengthAwarePaginator
    {
        $query = ClassProgressReport::query()
            ->with('classSection')
            ->orderBy($filters['sort_by'] ?? 'week_start', $filters['sort_dir'] ?? 'desc');

        if (!$this->isAdmin($user)) {
            $query->where('teacher_id', $user->id);
        } elseif (!empty($filters['teacher_id'])) {
            $query->where('teacher_id', (int) $filters['teacher_id']);
        }

        if (!empty($filters['class_section_id'])) {
            $query->where('class_section_id', (int) $filters['class_section_id']);
        }

        if (!empty($filters['subject'])) {
            $query->where('subject', (string) $filters['subject']);
        }

        if (!empty($filters['status'])) {
            $query->where('status', (string) $filters['status']);
        }

        if (!empty($filters['week_start'])) {
            $query->whereDate('week_start', '>=', $filters['week_start']);
        }

        if (!empty($filters['week_end'])) {
            $query->whereDate('week_end', '<=', $filters['week_end']);
        }

        $perPage = (int) ($filters['per_page'] ?? 20);

        return $query->paginate($perPage);
    }

    public function getReport(User $user, int $reportId): ClassProgressReport
    {
        $query = ClassProgressReport::query()->with('classSection');
        if (!$this->isAdmin($user)) {
            $query->where('teacher_id', $user->id);
        }

        return $query->findOrFail($reportId);
    }

    public function weeklyReports(User $user, ClassProgressReport $report): array
    {
        $query = ClassProgressReport::query()
            ->with('classSection')
            ->where('class_section_id', $report->class_section_id)
            ->whereDate('week_start', $report->week_start)
            ->orderBy('subject', 'asc');

        if (!$this->isAdmin($user)) {
            $query->where('teacher_id', $user->id);
        }

        $rows = $query->get();
        $attachments = $this->attachmentMap($rows->pluck('id')->all());

        return $rows->map(function (ClassProgressReport $row) use ($attachments) {
            $row->setAttribute('status_label', $this->statusLabel($row->status));
            $row->setAttribute('attachments', $attachments[$row->id] ?? []);
            return $row;
        })->all();
    }

    public function attachmentMap(array $reportIds): array
    {
        $reportIds = array_values(array_filter(array_map('intval', $reportIds)));
        if ($reportIds === []) {
            return [];
        }

        $rows = ClassProgressAttachment::query()
            ->whereIn('report_id', $reportIds)
            ->orderBy('id', 'asc')
            ->get();

        $map = [];
        foreach ($rows as $row) {
            $map[$row->report_id][] = [
                'id' => $row->id,
                'name' => $row->original_name ?: basename((string) $row->file_path),
                'file_path' => $row->file_path,
            ];
        }

        return $map;
    }

    public function teacherAssignments(User $user, ?string $schoolYear, ?string $semester): array
    {
        if ($schoolYear === null || $schoolYear === '') {
            $schoolYear = (string) (config('school.school_year') ?? '');
        }

        return TeacherClass::getClassAssignmentsByUserId($user->id, $schoolYear, $semester);
    }

    private function statusLabel(?string $status): string
    {
        $options = (array) config('progress.status_options', []);
        return $options[$status] ?? 'Unknown';
    }

    private function isAdmin(User $user): bool
    {
        $roles = $user->roles()
            ->pluck('roles.name')
            ->map(fn ($name) => strtolower((string) $name))
            ->toArray();

        foreach (['administrator', 'admin', 'principal', 'vice_principal', 'vice-principal'] as $role) {
            if (in_array($role, $roles, true)) {
                return true;
            }
        }

        return false;
    }
}
