<?php

namespace App\Http\Controllers\Agency\Tour;

use App\Http\Controllers\Controller;
use App\Models\Tour\Tour;
use App\Models\Product\ProductMarketplaceTranslation;
use Illuminate\Http\Request;

class TourTranslationController extends Controller
{
    public function index(Tour $tour)
    {
        $marketplaces = $tour->product->marketplaces()->with('languages')->where('is_active', true)->get();

        return view('agency.products.kultur-turlari.translations', compact('tour', 'marketplaces'));
    }

    public function fetch(Request $request, Tour $tour)
    {
        $marketplaceId = $request->query('marketplace_id');
        $languageId = $request->query('language_id');

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

        // Try specific marketplace translation first
        $translation = ProductMarketplaceTranslation::where([
            'product_id' => $tour->product_id,
            'marketplace_id' => $marketplaceId,
            'language_id' => $languageId
        ])->first();

        // Fallback: If not found, look for any marketplace translation for the same language
        if (!$translation) {
            $translation = ProductMarketplaceTranslation::where([
                'product_id' => $tour->product_id,
                'language_id' => $languageId
            ])->first();
        }

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

    public function save(Request $request, Tour $tour)
    {
        $request->validate([
            'marketplace_id' => 'required|integer',
            'language_id' => 'required|integer',
            'name' => 'nullable|string|max:255',
            'short_description' => 'nullable|string',
            'description' => 'nullable|string',
            'highlights' => 'nullable|string',
            'inclusions' => 'nullable|string',
            'exclusions' => 'nullable|string',
            'cancellation_policy' => 'nullable|string',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string',
        ]);

        try {
            $productId = $tour->product_id;
            $languageId = $request->input('language_id');
            $currentMarketplaceId = $request->input('marketplace_id');
            $data = $request->only([
                'name',
                'description',
                'short_description',
                'highlights',
                'inclusions',
                'exclusions',
                'cancellation_policy',
                'meta_title',
                'meta_description',
            ]);

            // Save for the selected marketplace
            $translation = ProductMarketplaceTranslation::updateOrCreate([
                'product_id' => $productId,
                'marketplace_id' => $currentMarketplaceId,
                'language_id' => $languageId,
            ], $data);

            // Sync with other active marketplaces of this tour's product that support this language
            $otherMarketplaces = $tour->product->marketplaces()
                ->where('is_active', true)
                ->where('marketplaces.id', '!=', $currentMarketplaceId)
                ->whereHas('languages', function($q) use ($languageId) {
                    $q->where('languages.id', $languageId);
                })
                ->get();

            foreach ($otherMarketplaces as $otherMp) {
                ProductMarketplaceTranslation::updateOrCreate([
                    'product_id' => $productId,
                    'marketplace_id' => $otherMp->id,
                    'language_id' => $languageId,
                ], $data);
            }

            return response()->json([
                'success' => true,
                'message' => 'Çeviriler başarıyla kaydedildi.',
                'translation' => $translation
            ]);
        } catch (\Exception $e) {
            \Log::error('Tour translation save error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Çeviriler kaydedilirken bir hata oluştu: ' . $e->getMessage()
            ], 500);
        }
    }
}
