<?php

namespace App\Http\Controllers;

use Exception;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;


class bulutController extends Controller
{
    private function client()
    {
        return new Client(array(
            'timeout' => 15,
            'headers' => array(
                'x-rapidapi-host' => env('BULUT_RAPIDAPI_HOST'),
                'x-rapidapi-key'  => env('BULUT_RAPIDAPI_KEY'),
            ),
        ));
    }

    /**
     * ADIM 1: Otel adına göre ara → hotel_id al
     * GET /bulut/search?name=Grand Yavuz Hotel Istanbul
     */
    public function search(Request $request)
    {
        $name = $request->query('name', '');

        if (!$name) {
            return response()->json(array('status' => false, 'message' => 'name parametresi gerekli'), 422);
        }

        try {
            $response = $this->client()->get(
                'https://' . env('BULUT_RAPIDAPI_HOST') . '/locations/auto-complete',
                array('query' => array('text' => $name, 'languagecode' => 'en-us'))
            );

            $data = json_decode($response->getBody()->getContents(), true);

            return response()->json(array('status' => true, 'raw' => $data));
        } catch (Exception $e) {
            Log::error('search error: ' . $e->getMessage());
            return response()->json(array('status' => false, 'message' => $e->getMessage()), 500);
        }
    }

    /**
     * ADIM 2: Otel detayları
     * GET /bulut/hotel-data?hotel_id=1234567&checkin=2026-06-01&checkout=2026-06-02
     */
    public function hotelData(Request $request)
    {
        $hotelId  = $request->query('hotel_id');
        $checkin  = $request->query('checkin');
        $checkout = $request->query('checkout');

        if (!$hotelId) {
            return response()->json(array('status' => false, 'message' => 'hotel_id gerekli'), 422);
        }

        try {
            $response = $this->client()->get(
                'https://' . env('BULUT_RAPIDAPI_HOST') . '/properties/detail',
                array('query' => array(
                    'hotel_id'       => $hotelId,
                    'arrival_date'   => $checkin,
                    'departure_date' => $checkout,
                    'languagecode'   => 'en-us',
                    'currency_code'  => 'USD',
                ))
            );

            $data = json_decode($response->getBody()->getContents(), true);
            return response()->json(array('status' => true, 'data' => $data));
        } catch (Exception $e) {
            Log::error('hotelData error: ' . $e->getMessage());
            return response()->json(array('status' => false, 'message' => $e->getMessage()), 500);
        }
    }

    public function hotelPhotos(Request $request)
    {
        $hotelIds = $request->query('hotel_ids');
        $hotelName = $request->query('hotel_name', 'hotel');
        $propertyId = $request->query('property_id', $hotelIds);

        if (!$hotelIds) {
            return response()->json(array(
                'status' => false,
                'message' => 'hotel_ids gerekli'
            ), 422);
        }

        try {
            $response = $this->client()->get(
                'https://' . env('BULUT_RAPIDAPI_HOST') . '/properties/get-hotel-photos',
                array(
                    'query' => array(
                        'hotel_ids'    => $hotelIds,
                        'languagecode' => 'en-us',
                    )
                )
            );

            $data = json_decode($response->getBody()->getContents(), true);

            $savedImages = $this->saveHotelPhotosFromResponse($data, $hotelName, $propertyId);
            Log::info('BULUT RAW RESPONSE KEYS', array(
                'main_keys' => array_keys($data),
                'data_keys' => isset($data['data']) && is_array($data['data']) ? array_keys($data['data']) : array(),

            ));

            return response()->json(array(
                'status' => true,
                'message' => 'Otel görselleri başarıyla indirildi ve gruplandı.',
                'debug' => array(
                    'main_keys' => array_keys($data),
                    'data_keys' => isset($data['data']) && is_array($data['data']) ? array_keys($data['data']) : array(),
                    'data_data_keys' => isset($data['data']['data']) && is_array($data['data']['data']) ? array_keys($data['data']['data']) : array(),
                ),
                'saved_images' => $savedImages
            ));
        } catch (Exception $e) {
            Log::error('hotelPhotos error: ' . $e->getMessage());

            return response()->json(array(
                'status' => false,
                'message' => $e->getMessage()
            ), 500);
        }
    }

    private function saveHotelPhotosFromResponse(array $responseData, string $hotelName, $propertyId)
    {
        $result = array();

        $urlPrefix = 'https://cf.bstatic.com';

        if (isset($responseData['url_prefix'])) {
            $urlPrefix = $responseData['url_prefix'];
        }

        if (isset($responseData['data']['url_prefix'])) {
            $urlPrefix = $responseData['data']['url_prefix'];
        }

        $hotels = $this->extractHotelsFromPhotoResponse($responseData);

        Log::info('BULUT PHOTO HOTELS EXTRACTED', array(
            'hotel_count' => count($hotels),
            'hotel_keys' => array_keys($hotels),
            'url_prefix' => $urlPrefix
        ));

        $uploadRootPath = rtrim(Config::get('app.fileSystemDriver'), '/');

        $propertyBasePath = $uploadRootPath . '/property-photos/' . $propertyId;

        if (!File::exists($propertyBasePath)) {
            File::makeDirectory($propertyBasePath, 0777, true);
        }

        foreach ($hotels as $hotelId => $photos) {
            $hotelFolderName = Str::slug($hotelName) . '-' . $hotelId;

            $basePath = $propertyBasePath . '/bulut/' . $hotelFolderName;

            if (!File::exists($basePath)) {
                File::makeDirectory($basePath, 0777, true);
            }

            $result[$hotelId] = array(
                'hotel_name' => $hotelName,
                'property_id' => $propertyId,
                'folder' => '/property-photos/' . $propertyId . '/bulut/' . $hotelFolderName,
                'physical_path' => $basePath,
                'groups' => array()
            );

            foreach ($photos as $photo) {
                $photoId = isset($photo[2]) ? $photo[2] : uniqid();
                $tags = isset($photo[3]) ? $photo[3] : array();
                $imagePath = isset($photo[4]) ? $photo[4] : null;

                if (!$imagePath) {
                    continue;
                }

                $groupName = $this->detectPhotoGroup($tags);

                $groupPath = $basePath . '/' . $groupName;

                if (!File::exists($groupPath)) {
                    File::makeDirectory($groupPath, 0777, true);
                }

                $imageUrl = $urlPrefix . $imagePath;

                $fileName = $photoId . '.jpg';
                $savePath = $groupPath . '/' . $fileName;

                try {
                    $this->downloadImage($imageUrl, $savePath);

                    $relativePath = '/property-photos/' . $propertyId . '/bulut/' . $hotelFolderName . '/' . $groupName . '/' . $fileName;

                    if (!isset($result[$hotelId]['groups'][$groupName])) {
                        $result[$hotelId]['groups'][$groupName] = array();
                    }

                    $result[$hotelId]['groups'][$groupName][] = array(
                        'photo_id' => $photoId,
                        'file_name' => $fileName,
                        'photo_path' => '/property-photos/' . $propertyId . '/bulut/' . $hotelFolderName . '/' . $groupName . '/',
                        'relative_path' => $relativePath,
                        'physical_path' => $savePath,
                        'source_url' => $imageUrl,
                        'tags' => $tags
                    );
                } catch (Exception $e) {
                    Log::error('BULUT IMAGE DOWNLOAD ERROR: ' . $e->getMessage(), array(
                        'image_url' => $imageUrl,
                        'save_path' => $savePath
                    ));
                }
            }
        }

        return $result;
    }

    private function detectPhotoGroup(array $tags)
    {
        $tagNames = array();

        foreach ($tags as $tag) {
            if (isset($tag['tag'])) {
                $tagNames[] = strtolower($tag['tag']);
            }
        }

        $tagText = implode(' ', $tagNames);

        if (
            strpos($tagText, 'room') !== false ||
            strpos($tagText, 'bedroom') !== false ||
            strpos($tagText, 'bed') !== false ||
            strpos($tagText, 'living room') !== false
        ) {
            return 'rooms';
        }

        if (
            strpos($tagText, 'bathroom') !== false ||
            strpos($tagText, 'shower') !== false ||
            strpos($tagText, 'toilet') !== false
        ) {
            return 'bathroom';
        }

        if (
            strpos($tagText, 'breakfast') !== false ||
            strpos($tagText, 'buffet') !== false
        ) {
            return 'breakfast';
        }

        if (
            strpos($tagText, 'restaurant') !== false ||
            strpos($tagText, 'food') !== false ||
            strpos($tagText, 'drinks') !== false ||
            strpos($tagText, 'lunch') !== false ||
            strpos($tagText, 'dinner') !== false
        ) {
            return 'restaurant';
        }

        if (
            strpos($tagText, 'lobby') !== false ||
            strpos($tagText, 'reception') !== false ||
            strpos($tagText, 'lounge') !== false ||
            strpos($tagText, 'seating area') !== false
        ) {
            return 'lobby';
        }

        if (
            strpos($tagText, 'spa') !== false ||
            strpos($tagText, 'wellness') !== false ||
            strpos($tagText, 'public bath') !== false
        ) {
            return 'spa';
        }

        if (
            strpos($tagText, 'balcony') !== false ||
            strpos($tagText, 'terrace') !== false ||
            strpos($tagText, 'garden') !== false ||
            strpos($tagText, 'sea view') !== false ||
            strpos($tagText, 'city view') !== false
        ) {
            return 'view-and-outdoor';
        }

        if (
            strpos($tagText, 'property building') !== false ||
            strpos($tagText, 'property') !== false
        ) {
            return 'property';
        }

        return 'other';
    }

    private function downloadImage(string $imageUrl, string $savePath)
    {
        $client = new Client(array(
            'timeout' => 30,
            'verify' => false,
            'headers' => array(
                'User-Agent' => 'Mozilla/5.0'
            )
        ));

        $response = $client->get($imageUrl);

        if ($response->getStatusCode() !== 200) {
            throw new Exception('Image download failed: ' . $imageUrl);
        }

        File::put($savePath, $response->getBody()->getContents());

        return true;
    }

    private function extractHotelsFromPhotoResponse(array $responseData)
    {
        if (isset($responseData['data']) && is_array($responseData['data'])) {
            foreach ($responseData['data'] as $key => $value) {
                if (is_numeric($key) && is_array($value)) {
                    return $responseData['data'];
                }
            }
        }

        if (isset($responseData['data']['data']) && is_array($responseData['data']['data'])) {
            return $responseData['data']['data'];
        }

        if (isset($responseData['data']['data']['data']) && is_array($responseData['data']['data']['data'])) {
            return $responseData['data']['data']['data'];
        }

        return array();
    }
}
