<?php

namespace App\Helpers;

use App\Models\Configuration;
use App\Models\GoldPriceWeightRule;

class GoldPriceHelper
{
    /**
     * Calculate gold price per gram based on collection name and material type
     * 
     * @param string $collectionName
     * @param string $materialType '10k' or '14k'
     * @param float $goldPriceTroyOunce The price of gold per troy ounce
     * @param float|null $weightInGrams Optional weight in grams to apply weight-based rules
     * @param string|null $collectionId Optional Shopify collection ID for weight-based rules
     * @return float
     */
    public static function calculateGoldPricePerGram(string $collectionName, string $materialType, float $goldPriceTroyOunce, ?float $weightInGrams = null, ?string $collectionId = null): float
    {
        // Convert collection name to lowercase for case-insensitive comparison
        $collectionNameLower = strtolower($collectionName);
        $materialTypeLower = strtolower($materialType);

        // Base calculation: troy ounce to grams
        $basePricePerGram = $goldPriceTroyOunce / 31.1035;

        // Get configuration to check for collection fees
        $config = Configuration::getInstance();
        $collections = $config->collections ?? [];

        // Try to find the collection in configuration
        $collectionData = null;
        foreach ($collections as $collection) {
            if (strtolower($collection['name'] ?? '') === $collectionNameLower) {
                $collectionData = $collection;
                break;
            }
        }

        // Determine material multiplier
        $materialMultiplier = 0.417; // Default to 10k
        if ($materialTypeLower === '14k') {
            $materialMultiplier = 0.583; // 14k = 58.3% pure gold
        }

        // Calculate base price with material multiplier
        $priceWithMultiplier = $basePricePerGram * $materialMultiplier;

        // Determine fee to apply
        $fee = 0;

        // First, check if weight-based rules apply
        if ($weightInGrams !== null && $weightInGrams > 0 && $collectionId) {
            // Search for weight rule for this specific collection
            $weightRule = GoldPriceWeightRule::findRuleForWeight($collectionId, $weightInGrams);

            if ($weightRule) {
                // Use fee from weight rule
                if ($materialTypeLower === '10k') {
                    $fee = (float) $weightRule->fee_10k;
                } elseif ($materialTypeLower === '14k') {
                    $fee = (float) $weightRule->fee_14k;
                }
            } elseif ($collectionData) {
                // No weight rule matches for this collection, use collection general fees
                if ($materialTypeLower === '10k' && isset($collectionData['fee_10k'])) {
                    $fee = (float) $collectionData['fee_10k'];
                } elseif ($materialTypeLower === '14k' && isset($collectionData['fee_14k'])) {
                    $fee = (float) $collectionData['fee_14k'];
                }
            }
        } elseif ($collectionData) {
            // No weight provided or no collection_id, use collection general fees
            if ($materialTypeLower === '10k' && isset($collectionData['fee_10k'])) {
                $fee = (float) $collectionData['fee_10k'];
            } elseif ($materialTypeLower === '14k' && isset($collectionData['fee_14k'])) {
                $fee = (float) $collectionData['fee_14k'];
            }
        }

        return $priceWithMultiplier + $fee;
    }
}
