<?php

namespace App\Http\Controllers\Agency;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\Customer\CustomerFieldDefinition;
use App\Models\Customer\CustomerDocumentType;
use App\Models\Agency\Currency;
use App\Models\Agency\Marketplace;
use App\Models\Definition\Language;

class SettingsController extends Controller
{
    public function index()
    {
        $agency = auth()->user()->agency;
        $agencyId = $agency?->id;

        $stats = [
            'custom_fields' => $agencyId ? CustomerFieldDefinition::byAgency($agencyId)->count() : 0,
            'active_custom_fields' => $agencyId ? CustomerFieldDefinition::byAgency($agencyId)->active()->count() : 0,
            'document_types' => $agencyId ? CustomerDocumentType::byAgency($agencyId)->count() : 0,
            'active_document_types' => $agencyId ? CustomerDocumentType::byAgency($agencyId)->active()->count() : 0,
        ];

        return view('agency.settings.index', compact('stats', 'agency'));
    }

    /**
     * Display the currencies dashboard.
     */
    public function currenciesIndex()
    {
        $agency = auth()->user()->agency;
        if (!$agency) {
            abort(404);
        }

        $currencies = $agency->currencies()->orderBy('is_base', 'desc')->orderBy('code')->get();
        if ($currencies->isEmpty()) {
            $agency->currencies()->createMany([
                ['code' => 'TRY', 'symbol' => '₺', 'exchange_rate' => 1.0, 'is_active' => true, 'is_base' => true],
                ['code' => 'USD', 'symbol' => '$', 'exchange_rate' => 32.5, 'is_active' => true, 'is_base' => false],
                ['code' => 'EUR', 'symbol' => '€', 'exchange_rate' => 35.2, 'is_active' => true, 'is_base' => false],
            ]);
            $currencies = $agency->currencies()->orderBy('is_base', 'desc')->orderBy('code')->get();
        }

        return view('agency.settings.currencies.index', compact('currencies'));
    }

    /**
     * Update global agency settings.
     */
    public function update(Request $request)
    {
        return back()->with('success', 'Ayarlar güncellendi.');
    }

    /**
     * Store or update a currency definition.
     */
    public function storeCurrency(Request $request)
    {
        $agency = auth()->user()->agency;
        if (!$agency) {
            return back()->with('error', 'Acente bulunamadı.');
        }

        $validated = $request->validate([
            'code' => 'required|string|max:3',
            'symbol' => 'required|string|max:5',
            'exchange_rate' => 'required|numeric|min:0.0001',
            'is_active' => 'nullable',
            'is_base' => 'nullable'
        ]);

        $code = strtoupper($validated['code']);
        $isBase = $request->has('is_base');
        $isActive = $request->has('is_active') || $isBase;

        if ($isBase) {
            $agency->currencies()->update(['is_base' => false]);
            $validated['exchange_rate'] = 1.0;
        }

        $agency->currencies()->updateOrCreate(
            ['code' => $code],
            [
                'symbol' => $validated['symbol'],
                'exchange_rate' => (float)$validated['exchange_rate'],
                'is_active' => $isActive,
                'is_base' => $isBase
            ]
        );

        return back()->with('success', "{$code} para birimi başarıyla eklendi.");
    }

    /**
     * Delete a currency.
     */
    public function destroyCurrency(Currency $currency)
    {
        if ($currency->agency_id !== auth()->user()->agency_id) {
            abort(403);
        }

        if ($currency->is_base) {
            return back()->with('error', 'Varsayılan para birimi silinemez.');
        }

        $currency->delete();

        return back()->with('success', 'Para birimi silindi.');
    }

    /**
     * Bulk update exchange rates and status.
     */
    public function bulkUpdateCurrencies(Request $request)
    {
        $agency = auth()->user()->agency;
        if (!$agency) {
            return back()->with('error', 'Acente bulunamadı.');
        }

        $request->validate([
            'rates' => 'required|array',
            'rates.*' => 'required|numeric|min:0.0001',
            'active' => 'nullable|array',
        ]);

        $rates = $request->input('rates', []);
        $activeIds = $request->input('active', []);

        foreach ($rates as $id => $rate) {
            $currency = $agency->currencies()->find($id);
            if ($currency) {
                $currency->exchange_rate = $currency->is_base ? 1.0 : (float)$rate;
                $currency->is_active = $currency->is_base ? true : in_array($id, $activeIds);
                $currency->save();
            }
        }

        return back()->with('success', 'Para birimleri ve kurlar güncellendi.');
    }

    /**
     * Display settings marketplaces dashboard.
     */
    public function marketplacesIndex()
    {
        $agency = auth()->user()->agency;
        if (!$agency) {
            abort(404);
        }

        $marketplaces = $agency->marketplaces()->with(['languages', 'currencies', 'defaultLanguage', 'defaultCurrency'])->get();
        $currencies = $agency->getActiveCurrencies();
        $languages = Language::all();

        return view('agency.settings.marketplaces.index', compact('marketplaces', 'currencies', 'languages'));
    }

    /**
     * Store a new marketplace.
     */
    public function storeMarketplace(Request $request)
    {
        $agency = auth()->user()->agency;
        if (!$agency) {
            return back()->with('error', 'Acente bulunamadı.');
        }

        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'default_language_id' => 'required|exists:languages,id',
            'default_currency_id' => 'required|exists:currencies,id',
            'languages' => 'required|array|min:1',
            'languages.*' => 'exists:languages,id',
            'currencies' => 'required|array|min:1',
            'currencies.*' => 'exists:currencies,id',
            'is_active' => 'nullable'
        ]);

        $marketplace = $agency->marketplaces()->create([
            'name' => $validated['name'],
            'slug' => \Illuminate\Support\Str::slug($validated['name']),
            'default_language_id' => $validated['default_language_id'],
            'default_currency_id' => $validated['default_currency_id'],
            'is_active' => $request->has('is_active') || $request->ajax() || $request->wantsJson()
        ]);

        $marketplace->languages()->sync($validated['languages']);
        $marketplace->currencies()->sync($validated['currencies']);

        if ($request->ajax() || $request->wantsJson()) {
            $marketplace->load(['languages', 'currencies']);
            return response()->json([
                'success' => true,
                'message' => 'Pazaryeri başarıyla eklendi.',
                'marketplace' => $marketplace
            ]);
        }

        return back()->with('success', 'Pazaryeri başarıyla eklendi.');
    }

    /**
     * Update an existing marketplace.
     */
    public function updateMarketplace(Request $request, Marketplace $marketplace)
    {
        if ($marketplace->agency_id !== auth()->user()->agency_id) {
            abort(403);
        }

        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'default_language_id' => 'required|exists:languages,id',
            'default_currency_id' => 'required|exists:currencies,id',
            'languages' => 'required|array|min:1',
            'languages.*' => 'exists:languages,id',
            'currencies' => 'required|array|min:1',
            'currencies.*' => 'exists:currencies,id',
            'is_active' => 'nullable'
        ]);

        $marketplace->update([
            'name' => $validated['name'],
            'slug' => \Illuminate\Support\Str::slug($validated['name']),
            'default_language_id' => $validated['default_language_id'],
            'default_currency_id' => $validated['default_currency_id'],
            'is_active' => $request->has('is_active')
        ]);

        $marketplace->languages()->sync($validated['languages']);
        $marketplace->currencies()->sync($validated['currencies']);

        return back()->with('success', 'Pazaryeri başarıyla güncellendi.');
    }

    /**
     * Delete a marketplace.
     */
    public function destroyMarketplace(Marketplace $marketplace)
    {
        if ($marketplace->agency_id !== auth()->user()->agency_id) {
            abort(403);
        }

        $marketplace->languages()->detach();
        $marketplace->currencies()->detach();
        $marketplace->products()->detach();
        $marketplace->delete();

        return back()->with('success', 'Pazaryeri başarıyla silindi.');
    }
}
