<?php

namespace App\Services\Attendance;

use Illuminate\Contracts\Auth\Authenticatable;

class AttendancePolicyService
{
    public function canEditDay(array $dayRow, array $currentUser): bool
    {
        $status = strtolower((string)($dayRow['status'] ?? 'draft'));
        $roles = array_map([$this, 'normalizeRole'], (array)($currentUser['roles'] ?? []));
        $permissions = array_map('strtolower', (array)($currentUser['permissions'] ?? []));

        $isAdmin = $this->isAdminLike($roles, $permissions);
        $isTeacher = in_array('teacher', $roles, true) || in_array('ta', $roles, true) || in_array('teacher_assistant', $roles, true);

        if ($status === 'finalized' || $status === 'published') {
            return $isAdmin;
        }

        if ($status === 'submitted') {
            return $isAdmin;
        }

        if ($status === 'draft') {
            return $isAdmin || $isTeacher;
        }

        return $isAdmin;
    }

    public function isTeacher(array $roles): bool
    {
        $roles = array_map([$this, 'normalizeRole'], $roles);
        return in_array('teacher', $roles, true)
            || in_array('ta', $roles, true)
            || in_array('teacher_assistant', $roles, true)
            || in_array('assistant_teacher', $roles, true);
    }

    public function isAdminLike(array $roles, array $permissions = []): bool
    {
        $roles = array_map([$this, 'normalizeRole'], $roles);

        $excluded = [
            'parent',
            'guest',
            'teacher',
            'teacher_assistant',
            'assistant_teacher',
            'ta',
        ];

        foreach ($roles as $role) {
            if ($role !== '' && !in_array($role, $excluded, true)) {
                return true;
            }
        }

        foreach ($permissions as $permission) {
            $permission = strtolower(trim((string)$permission));
            if (str_contains($permission, 'attendance.manage') || str_contains($permission, 'attendance.admin')) {
                return true;
            }
        }

        return false;
    }

    public function normalizeRole(?string $role): string
    {
        return str_replace([' ', '-'], '_', strtolower(trim((string)$role)));
    }
}