<?php

namespace App\Http\Controllers\Store;

use App\Helpers\VisitorHelper;
use App\Http\Controllers\Controller;
use App\Models\Currency;
use App\Models\Language;
use App\Services\Store\LocaleSiblingResolver;
use App\Services\VisitorService;
use Illuminate\Http\Request;

class PreferenceController extends Controller
{
    public function __construct(private VisitorService $visitorService) {}

    public function language()
    {
        $languages = Language::active()->get(['a2_iso', 'native_name', 'site_default']);

        return view('preferences.language', compact('languages'));
    }

    public function setLocale(Request $request)
    {
        // PRC-507 — login kullanıcıda dil/currency Client kaydından gelir ve
        // hiçbir yerden değiştirilemez (read-only). Switcher inert; server no-op.
        if (auth('client')->check()) {
            return back();
        }

        $validated = $request->validate([
            'locale' => ['required', 'string', 'in:'.Language::active()->pluck('a2_iso')->implode(',')],
        ]);

        $locale = $validated['locale'];

        // Visitor ID'sini al
        $visitorId = VisitorHelper::getVisitorId($request);

        // Visitor'a tercih edilen dili kaydet
        if ($visitorId) {
            VisitorHelper::updateVisitorInfo($visitorId, [
                'preferredLanguage' => $locale,
                'languageSetAt' => now()->toISOString(),
            ]);

            // Visitor detail'ları da güncelle
            $this->visitorService->setVisitorPreferredLanguage($visitorId, $locale);
            $this->visitorService->setVisitorDeterminedLanguage($visitorId, $locale);
        }

        app()->setLocale($locale);

        // Authenticated client için language_id'yi de senkronize et — emailler
        // ve diğer async job'lar Client::language_id okuyor.
        $client = auth('client')->user();
        if ($client) {
            $language = Language::where('a2_iso', $locale)->first();
            if ($language && $client->language_id !== $language->id) {
                $client->update(['language_id' => $language->id]);
            }
        }

        // Slug-locale-lock'lu sayfada (örn /urunler) dil değiştirince hedef
        // dilin slug'ına git — yoksa LockStoreLocale tercihi anında ezer (PRC-534).
        $sibling = app(LocaleSiblingResolver::class)->resolve(url()->previous(), $locale);

        return $sibling ? redirect($sibling) : back();
    }

    public function currency()
    {
        $currencies = Currency::query()->where('status', true)->get(['code', 'name', 'prefix', 'suffix', 'is_default']);

        return view('preferences.currency', compact('currencies'));
    }

    public function setCurrency(Request $request)
    {
        // PRC-507 — login kullanıcıda dil/currency Client kaydından gelir ve
        // hiçbir yerden değiştirilemez (read-only). Switcher inert; server no-op.
        if (auth('client')->check()) {
            return back();
        }

        $validated = $request->validate([
            'currency' => ['required', 'string', 'in:'.Currency::where('status', true)->pluck('code')->implode(',')],
        ]);

        $currencyCode = $validated['currency'];

        // Currency modelini al
        $currency = Currency::where('status', true)
            ->where('code', $currencyCode)
            ->first();

        if (! $currency) {
            return back()->with('error', __('store.preference_invalid_currency'));
        }

        // CRITICAL: Currency değiştirme kuralları
        $client = auth()->guard('client')->user();
        if ($client) {
            // Kullanıcının faturası var mı kontrol et
            $hasInvoices = \App\Models\Invoice::where('client_id', $client->id)->exists();

            if ($hasInvoices) {
                // Kullanıcının faturası varsa currency değiştirmeye izin verme
                \Log::warning('PreferenceController: Currency change blocked - client has invoices', [
                    'client_id' => $client->id,
                    'attempted_currency' => $currencyCode,
                    'current_currency_id' => $client->currency_id,
                ]);

                return back()->with('error', __('store.preference_currency_change_blocked_invoices'));
            }

            // Faturası yoksa currency değiştirilebilir
            $client->update([
                'currency_id' => $currency->id,
            ]);

            \Log::info('PreferenceController: Updated client currency', [
                'client_id' => $client->id,
                'old_currency_id' => $client->currency_id,
                'new_currency_id' => $currency->id,
                'currency_code' => $currencyCode,
            ]);
        }

        // Visitor ID'sini al
        $visitorId = VisitorHelper::getVisitorId($request);

        // Visitor'a tercih edilen para birimini kaydet
        if ($visitorId) {
            VisitorHelper::setVisitorPreferredCurrency($visitorId, $currencyCode);

            // Visitor detail'ları da güncelle
            $this->visitorService->setVisitorPreferredCurrency($visitorId, $currencyCode);
            $this->visitorService->setVisitorDeterminedCurrency($visitorId, $currencyCode);

            // Visitor info'ya da kaydet
            $this->visitorService->updateVisitorInfo($visitorId, [
                'currency' => $currencyCode,
                'currencySetFrom' => $client ? 'user_preference' : 'visitor_preference',
                'currencyUpdatedAt' => now()->toISOString(),
            ]);
        }

        return back();
    }
}
