<?php

namespace App\Services;

use App\Models\Addon;
use App\Models\SubscriptionPlan;

class PlanPricingService
{
    public function calculateTotal(
        SubscriptionPlan $plan,
        int $employeeCount,
        array $selectedAddons = [],
        string $billingCycle = 'monthly'
    ): array {
        $employeeCount = max(0, $employeeCount);
        $billingCycle = in_array($billingCycle, ['monthly', 'yearly'], true) ? $billingCycle : 'monthly';

        $basePrice = $billingCycle === 'yearly'
            ? (float) $plan->base_price_yearly
            : (float) $plan->base_price_monthly;

        $employeeCost = $employeeCount * (float) $plan->per_employee_price;

        $addons = Addon::query()
            ->whereIn('id', $selectedAddons)
            ->get(['id', 'pricing_type', 'price']);

        $addonsTotal = $addons->sum(function (Addon $addon) use ($employeeCount) {
            $price = (float) $addon->price;
            if ($addon->pricing_type === 'per_employee') {
                return $employeeCount * $price;
            }

            return $price;
        });

        $total = $basePrice + $employeeCost + (float) $addonsTotal;

        return [
            'base_price' => round($basePrice, 2),
            'employee_cost' => round($employeeCost, 2),
            'addons_total' => round((float) $addonsTotal, 2),
            'total' => round($total, 2),
            'billing_cycle' => $billingCycle,
            'employee_count' => $employeeCount,
            'selected_addons' => array_values(array_unique(array_map('intval', $selectedAddons))),
        ];
    }
}
