<?php

namespace App\Domain\Shared\Services;

use App\Domain\Shared\DTOs\ProrationResult;
use Carbon\Carbon;

class ProrationService
{
    public function __construct(
        private readonly SettingsService $settings,
    ) {}

    public function isEnabled(): bool
    {
        return (bool) $this->settings->get('enrollment.allow_proration', false);
    }

    public function renewalDay(): int
    {
        return (int) $this->settings->get('enrollment.renewal_day', 1);
    }

    /**
     * Calculate prorated fee for a mid-month enrollment.
     * If today is on or before the renewal day, no proration applies (full price).
     */
    public function calculate(int $baseAmount, ?Carbon $enrollmentDate = null): ProrationResult
    {
        $today = $enrollmentDate ?? now();
        $renewalDay = $this->renewalDay();
        $currentDay = (int) $today->day;

        // No proration if enrolling on or before the renewal day
        if ($currentDay <= $renewalDay) {
            return new ProrationResult(
                applied: false,
                originalAmount: $baseAmount,
                proratedAmount: $baseAmount,
                remainingDays: 30,
                renewalDay: $renewalDay,
                description: '',
            );
        }

        // Days remaining until next renewal: renewal_day + 30 - today
        $remainingDays = $renewalDay + 30 - $currentDay;
        $remainingDays = max(1, $remainingDays);

        $proratedAmount = (int) ceil($baseAmount * $remainingDays / 30);

        $description = "متناسب: {$remainingDays} من 30 يوم";

        return new ProrationResult(
            applied: true,
            originalAmount: $baseAmount,
            proratedAmount: $proratedAmount,
            remainingDays: $remainingDays,
            renewalDay: $renewalDay,
            description: $description,
        );
    }
}
