<?php

namespace App\Http\Controllers\Store;

use App\Http\Controllers\Controller;
use App\Models\Currency;
use App\Models\Pricing;
use App\Models\Product;
use App\Models\ProductConfigOption;
use App\Models\ProductConfigOptionValue;
use App\Models\ProductGroup;
use App\Models\Setting;
use App\Models\TaxRule;
use App\Models\Tld;
use App\Services\PricingService;
use App\Services\Store\BrandContext;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function index()
    {
        // PRC-840 — branded storefront'ta yalnız vitrine seçili gruplar (null = kısıt yok)
        $visibleGroupIds = app(BrandContext::class)->visibleProductGroupIds();

        $groups = ProductGroup::query()
            ->where('hidden', false)
            ->when($visibleGroupIds !== null, fn ($q) => $q->whereIn('id', $visibleGroupIds))
            ->orderBy('order')
            ->get(['id', 'slug', 'name']);

        $selectedGroup = $groups->first();

        $products = Product::query()
            ->where('status', 'active')
            ->where('hidden', false)
            ->when($selectedGroup, fn ($q) => $q->where('group_id', $selectedGroup->id))
            ->when(Setting::get('hide_out_of_stock_products', false), fn ($q) => $q->inStock())
            ->orderBy('order')
            ->get(['id', 'slug', 'name', 'description', 'trial_mode', 'trial_period_days', 'trial_paid_discount_percent', 'trial_paid_discount_periods', 'stock_control', 'total_stock', 'used_stock']);

        // Apply translations to groups
        $groups = $groups->map(function ($group) {
            $group->translated_name = $group->getTranslation('name') ?: $group->name;

            return $group;
        });

        // Apply translations to products
        $products = $products->map(function ($product) {
            $product->translated_name = $product->getTranslation('name') ?: $product->name;
            $product->translated_description = $product->getTranslation('description') ?: $product->description;

            return $product;
        });

        return view('products.index', compact('groups', 'selectedGroup', 'products'));
    }

    public function group(ProductGroup $group)
    {
        abort_if($group->hidden, 404);

        // PRC-840 — vitrine dahil olmayan grup URL tahminiyle açılamaz
        $brandCtx = app(BrandContext::class);
        abort_unless($brandCtx->productGroupVisible($group->id), 404);
        $visibleGroupIds = $brandCtx->visibleProductGroupIds();

        $groups = ProductGroup::query()
            ->where('hidden', false)
            ->when($visibleGroupIds !== null, fn ($q) => $q->whereIn('id', $visibleGroupIds))
            ->orderBy('order')
            ->get(['id', 'slug', 'name']);

        $products = Product::query()
            ->where('status', 'active')
            ->where('hidden', false)
            ->where('group_id', $group->id)
            ->when(Setting::get('hide_out_of_stock_products', false), fn ($q) => $q->inStock())
            ->orderBy('order')
            ->get(['id', 'slug', 'name', 'description', 'trial_mode', 'trial_period_days', 'trial_paid_discount_percent', 'trial_paid_discount_periods', 'stock_control', 'total_stock', 'used_stock']);

        $selectedGroup = $group;

        // Apply translations to groups
        $groups = $groups->map(function ($group) {
            $group->translated_name = $group->getTranslation('name') ?: $group->name;

            return $group;
        });

        // Apply translations to products
        $products = $products->map(function ($product) {
            $product->translated_name = $product->getTranslation('name') ?: $product->name;
            $product->translated_description = $product->getTranslation('description') ?: $product->description;

            return $product;
        });

        // Apply translation to selected group
        $selectedGroup->translated_name = $selectedGroup->getTranslation('name') ?: $selectedGroup->name;

        return view('products.index', compact('groups', 'selectedGroup', 'products'));
    }

    public function show(Request $request,Product $product)
    {
        // PRC-570 — gizli/pasif ürünün detay sayfası direkt URL ile açılmamalı.
        // Listeleme scope'ları (hidden/status) detay route-binding'ine uygulanmıyor;
        // burada açıkça reddet.
        abort_if($product->hidden || $product->status !== 'active', 404);

        // PRC-840 — branded storefront'ta vitrine dahil olmayan ürün 404 (URL tahmini kapalı)
        abort_unless(app(BrandContext::class)->productGroupVisible($product->group_id), 404);

        $product->load(['options.configValues', 'customFields', 'pricing', 'group']);
        $productData = $product->only(['id', 'slug', 'name']);
        // Description çevirisi aktif dile göre
        $productDescription = $product->getTranslation('description');

        // Name çevirisi de aktif dile göre
        $productName = $product->getTranslation('name') ?: $product->name;

        // Currency'e göre uygun pricingleri hazırla
        // Öncelik sırası: 1. Logged-in user currency, 2. Session currency, 3. Default currency
        $currency = null;

        // 1. Authenticated user için client currency'yi kullan
        $client = auth()->guard('client')->user();
        if ($client && $client->currency_id) {
            $currency = Currency::where('status', true)
                ->where('id', $client->currency_id)
                ->first();

            \Log::info('ProductController: Using authenticated user currency', [
                'client_id' => $client->id,
                'currency_id' => $client->currency_id,
                'currency_code' => $currency?->code,
            ]);
        }

        // 2. Session currency'yi kullan (anonim kullanıcılar veya currency_id yoksa)
        if (! $currency) {
            $currencyCode = app(\App\Services\Store\StorePreferenceResolver::class)->currentCurrencyCode();
            if ($currencyCode) {
                $currency = Currency::where('status', true)
                    ->where('code', $currencyCode)
                    ->first();

                \Log::info('ProductController: Using session currency', [
                    'currency_code' => $currencyCode,
                    'found' => $currency ? true : false,
                ]);
            }
        }

        // 3. Varsayılan currency'yi kullan
        if (! $currency) {
            $currency = Currency::where('status', true)
                ->where('is_default', true)
                ->first();

            \Log::info('ProductController: Using default currency', [
                'currency_code' => $currency?->code,
            ]);
        }



        $pricing = $product->pricing()
            ->when($currency, fn ($q) => $q->where('currency_id', $currency->id))
            ->orderBy('order')
            ->get(['period', 'time', 'amount', 'setup_amount', 'currency_id']);

        // Apply client group custom pricing if applicable
        if ($client && $client->group_id && $client->group && $client->group->hasCustomPricing()) {
            $pricing = $pricing->map(function ($price) use ($client, $product) {
                $originalAmount = $price->amount;

                // 1. Check for product-specific discount percentage from pricing_overrides
                $productDiscount = $client->group->getProductDiscountPercentage($product->id, $price->period);
                if ($productDiscount !== null) {
                    $price->amount = $originalAmount * (1 - ($productDiscount / 100));
                    $price->has_group_pricing = true;
                    $price->discount_percentage = $productDiscount;
                } else {
                    // 2. Apply global percentage discount from pricing_rules
                    $discountPercentage = $client->group->getDiscountPercentage();
                    if ($discountPercentage !== null) {
                        $price->amount = $originalAmount * (1 - ($discountPercentage / 100));
                        $price->has_group_pricing = true;
                        $price->discount_percentage = $discountPercentage;
                    } else {
                        // 3. Apply global fixed discount from pricing_rules
                        $discountAmount = $client->group->getDiscountAmount();
                        if ($discountAmount !== null) {
                            $price->amount = max(0, $originalAmount - $discountAmount);
                            $price->has_group_pricing = true;
                        }
                    }
                }
                return $price;
            });

            \Log::info('ProductController: Group pricing applied', [
                'client_id' => $client->id,
                'group_id' => $client->group_id,
                'group_name' => $client->group->group_name,
                'product_id' => $product->id,
            ]);
        }

        // Görünebilir custom field'lar
        $visibleCustomFields = $product->customFields()
            ->where('visible_on_client', true)
            ->where('status', true)
            ->orderBy('order')
            ->get();

        // JSON olarak JS'e verilecek veri (configurable options verileri çıkarıldı)
        $productJson = [
            'id' => $product->id,
            'slug' => $product->slug,
            'name' => $productName, // Çevrilmiş isim
            'require_domain' => (bool) $product->require_domain,
            'trial_mode' => $product->trial_mode ?? 'none',
            'trial_period_days' => (int) ($product->trial_period_days ?? 0),
            'trial_paid_discount_percent' => (float) ($product->trial_paid_discount_percent ?? 0),
            // PRC-544 — null = tüm periyotlar; dizi = sadece bu period (ay) değerleri.
            'trial_paid_discount_periods' => is_array($product->trial_paid_discount_periods)
                ? array_map('intval', $product->trial_paid_discount_periods)
                : null,
            'trial_default_period' => $product->trial_default_period ?? null,
            'pricing' => $pricing->toArray(),
            'currency_code' => $currency?->code,
            'currency_id' => $currency?->id,
            'custom_fields' => $visibleCustomFields->map(function ($f) {
                return [
                    'id' => $f->id,
                    'type' => $f->type,
                    'required' => (bool) $f->required_from_client,
                    'label' => method_exists($f, 'getTranslation') ? ($f->getTranslation('label') ?? 'Field') : 'Field',
                    'placeholder' => method_exists($f, 'getTranslation') ? ($f->getTranslation('placeholder') ?? '') : '',
                    'options' => is_array($f->dropdown_options) ? $f->dropdown_options : [],
                    'default_value' => $f->default_value, // PRC-786 — order-form ön-doldurma
                ];
            })->values()->toArray(),
        ];

        foreach ($productJson['pricing'] as $k => $v) {
            $productJson['pricing'][$k]['time'] = __('store.basket_period_'.$v['time']);
        }

        app(\App\Core\Hook\HookManager::class)->action('StoreProductDetails', [
            'product' => $product,
            'client' => auth()->guard('client')->user(),
        ]);

        return view('products.show', [
            'product' => $product,
            'productData' => $productJson,
            'productDescription' => $productDescription,
            'customFields' => $visibleCustomFields,
            'outOfStock' => ! $product->isInStock(), // PRC-787
        ]);
    }

    /**
     * Ürün detay sayfası için configurable options'ları getir
     */
    public function getConfigurableOptions(Request $request, $productId)
    {
        $product = Product::with(['configOptions.configValues'])
            ->findOrFail($productId);

        // Query parameter'lardan currency ve period'u al
        $requestedCurrency = $request->get('currency');
        $requestedPeriod = $request->get('period');

        if (! $requestedCurrency || ! $requestedPeriod) {
            return response()->json([
                'success' => false,
                'message' => 'Currency ve period parametreleri gerekli',
            ], 400);
        }

        // Currency'yi bul
        $currency = Currency::where('status', true)
            ->where('id', $requestedCurrency)
            ->first(['id', 'code', 'prefix', 'suffix', 'is_default']);

        if (! $currency) {
            return response()->json([
                'success' => false,
                'message' => 'Geçersiz currency',
            ], 400);
        }

        // PRC-432 — Build from $product->configOptions via ProductConfigOptionResolver.
        // (Original inline block extracted to shared service for reuse in quote builder.)
        $configOptions = app(\App\Services\Product\ProductConfigOptionResolver::class)
            ->resolve($product, $currency, (int) $requestedPeriod);

        // Custom fields'ları da hazırla
        $customFields = collect($product->customFields)
            ->where('status', 'active')
            ->where('admin_only', false)
            ->map(function ($field) {
                return [
                    'id' => $field->id,
                    'type' => $field->type,
                    'label' => $field->label,
                    'placeholder' => $field->placeholder,
                    // PRC-786 — accessor'sız alanlar null dönüyordu (options/required);
                    // gerçek kolonlara bağla (dropdown select boş kalıyordu).
                    'required' => (bool) $field->required_from_client,
                    'options' => is_array($field->dropdown_options) ? $field->dropdown_options : [],
                    'default_value' => $field->default_value,
                ];
            });

        // PRC-686 — Bağımlı (dependent) configurable option kuralları. Store JS
        // aynı serilizasyonu okuyup koşullu görünürlük/zorunluluk uygular; sunucu
        // tarafı ConfigOptionDependencyGuard ile aynı mantığı doğrular.
        $dependencies = app(\App\Services\Product\ConfigOptionDependencyEvaluator::class)
            ->rulesForProduct($product);

        return response()->json([
            'success' => true,
            'data' => [
                'product_id' => $product->id,
                'product_name' => $product->name,
                'currencies' => [
                    [
                        'id' => $currency->id,
                        'code' => $currency->code,
                        'prefix' => $currency->prefix,
                        'suffix' => $currency->suffix,
                        'is_default' => (bool) $currency->is_default,
                    ],
                ],
                'config_option_groups' => $configOptions,
                'config_option_dependencies' => $dependencies,
                'custom_fields' => $customFields,
            ],
        ]);
    }

    /**
     * Ürün fiyat hesaplama
     */
    public function calculate(Request $request, $productId)
    {
        // Request verilerini al (JSON request için)
        $selectedPeriod = $request->json('period');
        $selectedCurrency = $request->json('currency');
        $configOptions = $request->json('config_options', []);
        $domainAction = $request->json('domain_action'); // register, transfer, use
        $domainName = $request->json('domain_name');
        $customFields = $request->json('custom_fields', []);

        // PricingService kullan
        $pricingService = app(PricingService::class);
        $result = $pricingService->calculateProductPrice(
            $productId,
            $selectedPeriod,
            $selectedCurrency,
            $configOptions,
            $domainAction,
            $domainName,
            $customFields,
            $request
        );

        if (! $result['success']) {
            return response()->json($result, 400);
        }

        return response()->json([
            'success' => true,
            'data' => $result['data'],
        ]);
    }

    /**
     * Eski calculate metodu - PricingService'e taşındı
     */
    public function calculateOld(Request $request, $productId)
    {
        $product = Product::findOrFail($productId);

        // Request verilerini al (JSON request için)
        $selectedPeriod = $request->json('period');
        $selectedCurrency = $request->json('currency');
        $configOptions = $request->json('config_options', []);
        $domainAction = $request->json('domain_action'); // register, transfer, use
        $domainName = $request->json('domain_name');
        $customFields = $request->json('custom_fields', []);

        // Currency'yi bul
        $currency = Currency::where('status', true)
            ->where('id', $selectedCurrency)
            ->first();

        if (! $currency) {
            return response()->json([
                'success' => false,
                'message' => 'Geçersiz currency',
            ], 400);
        }

        // Ürün fiyatını bul
        $productPrice = Pricing::where('type', 'product')
            ->where('relation_id', $product->id)
            ->where('currency_id', $currency->id)
            ->where('time', 'month')
            ->where('period', $selectedPeriod)
            ->first();

        if (! $productPrice) {
            return response()->json([
                'success' => false,
                'message' => 'Ürün fiyatı bulunamadı',
            ], 400);
        }

        $subtotal = (float) $productPrice->amount;
        // Ürün ismini çevir
        $productName = $product->getTranslation('name') ?: $product->name;

        $items = [
            [
                'type' => 'product',
                'name' => $productName,
                'price' => $subtotal,
                'period' => $selectedPeriod,
                'period_text' => $selectedPeriod.' ay',
            ],
        ];

        // Configurable options fiyatlarını hesapla
        if (! empty($configOptions)) {
            $configOptionsArray = is_string($configOptions) ? json_decode($configOptions, true) : $configOptions;

            // Debug log - gelen veriyi kontrol et
            \Log::info('Config options received', [
                'raw' => $configOptions,
                'parsed' => $configOptionsArray,
                'count' => count($configOptionsArray),
            ]);

            foreach ($configOptionsArray as $optionId => $value) {
                // Debug log - her iteration için
                \Log::info('Loop iteration', [
                    'option_id' => $optionId,
                    'value' => $value,
                    'value_empty' => empty($value),
                    'value_not_zero' => $value !== '0',
                ]);

                if (empty($value)) {
                    \Log::info('Option skipped - empty value', ['option_id' => $optionId]);

                    continue;
                }

                $option = ProductConfigOption::find($optionId);
                if (! $option) {
                    \Log::warning('Option not found in database', ['option_id' => $optionId]);

                    continue;
                }

                // Debug log - her option için
                \Log::info('Processing option', [
                    'option_id' => $optionId,
                    'option_type' => $option->type,
                    'value' => $value,
                    'option_name' => $option->name,
                ]);

                if ($option->type === 'select' || $option->type === 'checkboxgroup') {
                    // Value-based pricing
                    if (is_array($value)) {
                        foreach ($value as $valueId) {
                            $optionValue = ProductConfigOptionValue::find($valueId);
                            if (! $optionValue) {
                                continue;
                            }

                            $price = Pricing::where('type', 'product_config')
                                ->where('relation_id', $optionValue->id)
                                ->where('currency_id', $currency->id)
                                ->where('time', 'month')
                                ->where('period', $selectedPeriod)
                                ->first(['amount']);

                            if ($price) {
                                $subtotal += (float) $price->amount;
                                $items[] = [
                                    'type' => 'config_option',
                                    'name' => ($option->getTranslation('name') ?: $option->name).' - '.($optionValue->getTranslation('value') ?: $optionValue->value),
                                    'price' => (float) $price->amount,
                                    'period' => $selectedPeriod,
                                    'period_text' => $selectedPeriod.' ay',
                                ];
                            }
                        }
                    } else {
                        $optionValue = ProductConfigOptionValue::find($value);
                        if ($optionValue) {
                            $price = Pricing::where('type', 'product_config')
                                ->where('relation_id', $optionValue->id)
                                ->where('currency_id', $currency->id)
                                ->where('time', 'month')
                                ->where('period', $selectedPeriod)
                                ->first(['amount']);

                            if ($price) {
                                $subtotal += (float) $price->amount;
                                $items[] = [
                                    'type' => 'config_option',
                                    'name' => ($option->getTranslation('name') ?: $option->name).' - '.($optionValue->getTranslation('value') ?: $optionValue->value),
                                    'price' => (float) $price->amount,
                                    'period' => $selectedPeriod,
                                    'period_text' => $selectedPeriod.' ay',
                                ];
                            }
                        }
                    }
                } elseif ($option->type === 'checkbox') {
                    // Checkbox için sadece seçili olanları hesapla
                    if ($value === '1' || $value === true) {
                        $price = Pricing::where('type', 'product_config')
                            ->where('relation_id', $optionId)
                            ->where('currency_id', $currency->id)
                            ->where('time', 'month')
                            ->where('period', $selectedPeriod)
                            ->first(['amount']);

                        if ($price) {
                            $subtotal += (float) $price->amount;
                            $items[] = [
                                'type' => 'config_option',
                                'name' => $option->getTranslation('name') ?: $option->name,
                                'price' => (float) $price->amount,
                                'period' => $selectedPeriod,
                                'period_text' => $selectedPeriod.' ay',
                            ];
                        }
                    }
                } elseif ($option->type === 'number') {
                    // Number için sadece değer girilmişse hesapla
                    if (! empty($value) && $value !== '0') {
                        $valueId = $option->configValues->first()->id ?? null;
                        $price = Pricing::where('type', 'product_config')
                            ->where('relation_id', $valueId)
                            ->where('currency_id', $currency->id)
                            ->where('time', 'month')
                            ->where('period', $selectedPeriod)
                            ->first(['amount']);

                        if ($price) {
                            // Number tipi için: değer x fiyat
                            $totalPrice = (float) $price->amount * (float) $value;
                            $subtotal += $totalPrice;
                            $items[] = [
                                'type' => 'config_option',
                                'name' => ($option->getTranslation('name') ?: $option->name).' (x'.$value.')',
                                'price' => $totalPrice,
                                'period' => $selectedPeriod,
                                'period_text' => $selectedPeriod.' ay',
                            ];
                        }
                    }
                }
            }
        }

        // Domain fiyatını hesapla
        $domainPrice = 0;
        if ($domainAction && $domainName) {
            \Log::info('Domain fiyat hesaplama başladı', [
                'domain_action' => $domainAction,
                'domain_name' => $domainName,
                'currency_id' => $currency->id,
            ]);

            $tld = $this->extractTLD($domainName);
            \Log::info('TLD çıkarıldı', ['tld' => $tld]);

            if ($tld) {
                $tldModel = Tld::where('tld', '.'.$tld)->where('status', 'active')->first();
                \Log::info('TLD model bulundu', ['tld_model' => $tldModel ? $tldModel->toArray() : null]);

                if ($tldModel) {
                    if ($domainAction === 'register') {
                        $domainPrice = Pricing::where('type', 'domain')
                            ->where('relation_id', $tldModel->id)
                            ->where('currency_id', $currency->id)
                            ->where('segment', 'register')
                            ->where('period', 1)
                            ->first();
                        \Log::info('Register pricing arandı', ['pricing' => $domainPrice ? $domainPrice->toArray() : null]);
                    } elseif ($domainAction === 'transfer') {
                        $domainPrice = Pricing::where('type', 'domain')
                            ->where('relation_id', $tldModel->id)
                            ->where('currency_id', $currency->id)
                            ->where('segment', 'transfer')
                            ->where('period', 1)
                            ->first();
                        \Log::info('Transfer pricing arandı', ['pricing' => $domainPrice ? $domainPrice->toArray() : null]);
                    } elseif ($domainAction === 'use') {
                        // use_existing için fiyat 0
                        $domainPrice = (object) ['amount' => 0];
                        \Log::info('Use domain - fiyat 0 olarak ayarlandı');
                    }

                    if ($domainPrice) {
                        $domainPrice = (float) $domainPrice->amount;
                        $subtotal += $domainPrice;

                        // Mevcut domain için süre bilgisi gösterme
                        $subtitle = $this->getDomainActionText($domainAction);
                        if ($domainAction !== 'use') {
                            $subtitle .= ' - 1 yıl';
                        }

                        $items[] = [
                            'type' => 'domain',
                            'name' => $domainName,
                            'subtitle' => $subtitle,
                            'price' => $domainPrice,
                            'period' => $domainAction === 'use' ? null : 12,
                            'period_text' => $domainAction === 'use' ? null : '1 yıl',
                        ];
                        \Log::info('Domain fiyat eklendi', [
                            'domain_price' => $domainPrice,
                            'subtotal' => $subtotal,
                        ]);
                    } else {
                        \Log::warning('Domain pricing bulunamadı', [
                            'tld_id' => $tldModel->id,
                            'currency_id' => $currency->id,
                            'domain_action' => $domainAction,
                        ]);
                    }
                } else {
                    \Log::warning('TLD model bulunamadı', ['tld' => $tld]);
                }
            } else {
                \Log::warning('TLD çıkarılamadı', ['domain_name' => $domainName]);
            }
        } else {
            \Log::info('Domain bilgileri eksik', [
                'domain_action' => $domainAction,
                'domain_name' => $domainName,
            ]);
        }

        // Vergi ayarlarını kontrol et
        $taxSettings = $this->getTaxSettings();

        $countryCode = 'TR';
        $taxRule = TaxRule::where(function ($q) use ($countryCode) {
            $q->whereJsonContains('countries', $countryCode)
                ->orWhere('all_countries', 1);
        })
            ->first();

        // Vergi hesaplama
        $taxAmount = 0;
        $taxRate = $taxRule->rate ?? 0;
        $taxName = $taxRule->name ?? '-';

        // Vergi aktif mi kontrol et
        if (! ($taxSettings['tax_enabled'] ?? false)) {
            $taxAmount = 0;
        } else {
            // Her kalem için ayrı vergi hesaplama
            $taxableItems = [];
            $nonTaxableItems = [];

            foreach ($items as $item) {
                $isItemTaxable = $this->isItemTaxable($item, $taxSettings, $product);

                if ($isItemTaxable) {
                    $taxableItems[] = $item;
                } else {
                    $nonTaxableItems[] = $item;
                }
            }

            // \Illuminate\Support\Facades\Log::info($nonTaxableItems);

            // Sadece vergilendirilebilir kalemlerin toplamını hesapla
            $taxableSubtotal = array_sum(array_column($taxableItems, 'price'));

            if ($taxableSubtotal > 0) {
                // Vergi hesapla - use 'client' guard for store
                $client = auth()->guard('client')->user();
                if ($client) {
                    // Logged in user - use TaxCalculationService for proper tax exemption check
                    $taxService = app(\App\Services\TaxCalculationService::class);
                    $taxInfo = $taxService->calculateTax(
                        client: $client,
                        productType: 'hosting',
                        product: null,
                        countryCode: null
                    );
                    if ($taxInfo['taxable']) {
                        $taxComputed = \App\Services\TaxCalculationService::computeTax($taxableSubtotal, $taxInfo['rate'], $taxInfo['tax_method'] ?? 'exclusive');
                        $taxAmount = $taxComputed['tax_amount'];
                    }
                } else {
                    // Anonymous user - varsayılan vergi
                    $taxMethod = $taxService->getTaxMethod();
                    $taxComputed = \App\Services\TaxCalculationService::computeTax($taxableSubtotal, $taxRate, $taxMethod);
                    $taxAmount = $taxComputed['tax_amount'];
                }
            }
        }

        $total = $subtotal + $taxAmount;

        return response()->json([
            'success' => true,
            'data' => [
                'items' => $items,
                'subtotal' => round($subtotal, 2),
                'tax_amount' => round($taxAmount, 2),
                'tax_rate' => $taxRate,
                'tax_name' => $taxName,
                'total' => round($total, 2),
                'currency' => [
                    'id' => $currency->id,
                    'code' => $currency->code,
                    'prefix' => $currency->prefix,
                    'suffix' => $currency->suffix,
                ],
            ],
        ]);
    }

    /**
     * TLD çıkar
     */
    private function extractTLD($domainName)
    {
        $parts = explode('.', $domainName);

        return end($parts);
    }

    /**
     * Domain action text
     */
    private function getDomainActionText($action)
    {
        switch ($action) {
            case 'register': return 'Yeni Kayıt';
            case 'transfer': return 'Transfer';
            case 'use': return 'Mevcut Domain';
            default: return '';
        }
    }

    /**
     * Vergi ayarlarını getir
     */
    private function getTaxSettings()
    {
        $settings = Setting::where('group', 'taxes')->get();
        $result = [];

        foreach ($settings as $setting) {
            $result[$setting->key] = $setting->value;
        }

        // Varsayılan değerleri ekle
        $result['tax_enabled'] = $result['tax_enabled'] ?? true;
        $result['default_tax_rate'] = $result['default_tax_rate'] ?? 18.0;

        return $result;
    }

    /**
     * Kalem vergilendirilebilir mi kontrol et
     */
    private function isItemTaxable($item, $taxSettings, $product)
    {

        switch ($item['type']) {
            case 'product':
                // Ürün tipini belirle
                $productType = 'product';
                if ($product->tax_excluded === 1) {
                    return false;
                }

                return $this->isProductTypeTaxable($productType, $taxSettings);

            case 'domain':
                // Domain fiyatı 0 ise (use domain) vergilendirme yapma
                if ($item['price'] == 0) {
                    return false;
                }

                // Domain kalemleri için domain vergi ayarını kontrol et
                return ($taxSettings['taxable_types_domain'] ?? false) == '1';

            case 'config_option':
                if ($product->tax_excluded === 1) {
                    return false;
                }

                // Configurable options ürünle aynı vergi kuralını takip eder
                return 'other';

            default:
                return true; // Diğer kalemler varsayılan olarak vergilendirilebilir
        }
    }

    /**
     * Ürün tipi vergilendirilebilir mi kontrol et
     */
    private function isProductTypeTaxable($productType, $taxSettings)
    {
        switch ($productType) {
            case 'domain':
                return ($taxSettings['taxable_types_domain'] ?? false) == '1';
            case 'hosting':
                return ($taxSettings['taxable_types_hosting'] ?? false) == '1';
            default:
                return true; // Diğer ürünler varsayılan olarak vergilendirilebilir
        }
    }
}
