<?php

namespace Modules\Documents\Services;

use App\Models\EmployeeDocumentModel;

class DocumentExpiryService
{
    protected EmployeeDocumentModel $documents;

    public function __construct()
    {
        $this->documents = new EmployeeDocumentModel();
    }

    public function summary(?string $today = null): array
    {
        $today = $today ?? date('Y-m-d');

        return [
            'expired'      => $this->documents->countExpired($today),
            'expiring_7'   => $this->documents->countExpiringWithin($today, 7),
            'expiring_30'  => $this->documents->countExpiringWithin($today, 30),
            'expiring_90'  => $this->documents->countExpiringWithin($today, 90),
            'upcoming'     => $this->documents->getExpiryList($today, 30, 8),
            'recently_expired' => $this->documents->getExpiryList($today, null, 5),
        ];
    }

    public function expiryStatus(?string $expiryDate, ?string $today = null): string
    {
        if (! $expiryDate) {
            return 'none';
        }

        $today = $today ?? date('Y-m-d');
        $days  = (int) floor((strtotime($expiryDate) - strtotime($today)) / 86400);

        if ($days < 0) {
            return 'expired';
        }

        if ($days <= 7) {
            return 'critical';
        }

        if ($days <= 30) {
            return 'warning';
        }

        return 'ok';
    }

    public function daysUntilExpiry(?string $expiryDate, ?string $today = null): ?int
    {
        if (! $expiryDate) {
            return null;
        }

        $today = $today ?? date('Y-m-d');

        return (int) floor((strtotime($expiryDate) - strtotime($today)) / 86400);
    }
}
