<?php

namespace App\Services;

use App\Models\ClientGroup;
use App\Models\Product;

class CommissionCalculationService
{
    public function calculateCommission(
        ClientGroup $group,
        float $amount,
        ?int $productId = null,
        ?int $productGroupId = null,
        ?string $tld = null
    ): float {
        if (! $group->commission_enabled) {
            return 0;
        }

        $rate = $this->resolveRate($group, $productId, $productGroupId, $tld);

        if ($group->commission_type === 'fixed') {
            return (float) $rate;
        }

        return round($amount * ($rate / 100), 2);
    }

    public function resolveRate(
        ClientGroup $group,
        ?int $productId = null,
        ?int $productGroupId = null,
        ?string $tld = null
    ): float {
        $rules = $group->commission_rules;

        if (! $rules) {
            return (float) $group->commission_rate;
        }

        if ($productId && isset($rules['products'][$productId])) {
            $val = $rules['products'][$productId];
            return (float) (is_array($val) ? ($val['rate'] ?? 0) : $val);
        }

        if ($productGroupId && isset($rules['product_groups'][$productGroupId])) {
            $val = $rules['product_groups'][$productGroupId];
            return (float) (is_array($val) ? ($val['rate'] ?? 0) : $val);
        }

        if ($tld && isset($rules['tlds'][$tld])) {
            $val = $rules['tlds'][$tld];
            return (float) (is_array($val) ? ($val['rate'] ?? 0) : $val);
        }

        return (float) $group->commission_rate;
    }

    /**
     * Build pricing + commission table for reseller panel (readonly).
     */
    public function getPricingTable(ClientGroup $group): array
    {
        $products = Product::where('status', 'active')->with('pricing')->get();
        $table = [];

        foreach ($products as $product) {
            $pricing = $product->pricing->first();
            if (! $pricing) {
                continue;
            }

            $basePrice = (float) $pricing->amount;
            $discount = $group->getProductDiscountPercentage($product->id, $pricing->period) ?? 0;
            $salePrice = $discount > 0 ? round($basePrice * (1 - $discount / 100), 2) : $basePrice;
            $commissionRate = $this->resolveRate($group, $product->id, $product->group_id);
            $earning = round($salePrice * ($commissionRate / 100), 2);

            $table[] = [
                'name' => $product->name,
                'type' => 'product',
                'base_price' => $basePrice,
                'discount' => $discount,
                'sale_price' => $salePrice,
                'commission_rate' => $commissionRate,
                'earning' => $earning,
            ];
        }

        return $table;
    }
}
