<?php

namespace App\Http\Controllers\API\GYG;

use App\Http\Controllers\Controller;
use App\Models\Tour;
use App\Models\TourDate;
use Illuminate\Http\Request;

class GYGController extends Controller
{
    /**
     * GetYourGuide için aktif turları listeler (Discovery)
     */
    public function index()
    {
        $tours = Tour::where('is_active', true)
            ->where('gyg_is_active', true)
            ->get(['id', 'title', 'code']);

        $products = $tours->map(function ($tour) {
            $title = is_string($tour->title) ? json_decode($tour->title, true) : $tour->title;
            return [
                'productId' => (string)$tour->id,
                'productTitle' => $title['en'] ?? ($title['tr'] ?? 'Tour #' . $tour->id)
            ];
        });

        return response()->json([
            'data' => [
                'supplierId' => (string)(config('services.gyg.supplier_id', '1')),
                'supplierName' => config('app.name'),
                'products' => $products
            ]
        ]);
    }

    /**
     * Seçilen turun temel detaylarını verir (Mapping Asistanı için)
     */
    public function show($id)
    {
        $tour = Tour::find($id);

        if (!$tour) {
            return response()->json(['error' => 'Product not found'], 404);
        }

        $title = is_string($tour->title) ? json_decode($tour->title, true) : $tour->title;
        $description = is_string($tour->description) ? json_decode($tour->description, true) : $tour->description;

        return response()->json([
            'data' => [
                'supplierId' => (string)(config('services.gyg.supplier_id', '1')),
                'productTitle' => $title['en'] ?? ($title['tr'] ?? ''),
                'productDescription' => mb_substr(strip_tags($description['en'] ?? ($description['tr'] ?? '')), 0, 500),
                'destinationLocation' => [
                    'city' => 'Unknown',
                    'country' => 'TR'
                ],
                'configuration' => [
                    'participantsConfiguration' => [
                        'min' => 1,
                        'max' => 50
                    ]
                ]
            ]
        ]);
    }

    /**
     * Get availability for a specific tour.
     * GYG identifies products by their Supplier Product ID (which we store as gyg_product_id)
     */
    public function availability(Request $request)
    {
        $gygProductId = $request->query('activity_id');
        
        if (!$gygProductId) {
            return response()->json(['error' => 'activity_id is required'], 400);
        }

        $tour = Tour::where('gyg_product_id', $gygProductId)
                    ->where('gyg_is_active', true)
                    ->first();

        if (!$tour) {
            return response()->json(['error' => 'Product not found or not active for GYG'], 404);
        }

        $dates = $tour->dates()
            ->where('start_date', '>=', now()->toDateString())
            ->where('status', 'active')
            ->get()
            ->map(function ($date) {
                return [
                    'date' => $date->start_date->format('Y-m-d'),
                    'slots' => $date->available_spots,
                    'is_available' => $date->available_spots > 0,
                    'retail_price' => (float)($date->adult_discounted_price ?: $date->adult_price),
                    'currency' => 'EUR'
                ];
            });

        return response()->json([
            'status' => 'success',
            'product_id' => $gygProductId,
            'availabilities' => $dates
        ]);
    }

    /**
     * Handle booking from GetYourGuide.
     * This endpoint receives reservation details from GetYourGuide.
     */
    public function booking(Request $request)
    {
        // Validation and reservation logic will be implemented here
        // For now, logging the request and returning a success message
        \Log::info('GYG Booking Request Received', $request->all());

        return response()->json([
            'status' => 'success',
            'booking_id' => 'GYG-' . uniqid(),
            'message' => 'Booking request captured and pending processing'
        ]);
    }
}
