<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class LocationController extends Controller
{
    public function getCountries()
    {
        try {
            // Try RESTCountries with fallback
            $response = Http::get('https://restcountries.com/v3.1/all?fields=name,cca2');

            if ($response->failed()) {
                // Fallback API
                $fallback = Http::get('https://countriesnow.space/api/v0.1/countries/iso');

                if ($fallback->failed()) {
                    return response()->json([
                        'status' => false,
                        'message' => 'Failed to fetch countries',
                    ], 400);
                }

                $countries = collect($fallback['data'])->map(fn($c) => [
                    'name' => $c['name'],
                    'iso2' => $c['Iso2'],
                ]);
            } else {
                $countries = collect($response->json())->map(fn($country) => [
                    'name' => $country['name']['common'] ?? null,
                    'iso2' => $country['cca2'] ?? null,
                ]);
            }

            return response()->json([
                'status' => true,
                'message' => 'Countries fetched successfully',
                'data' => $countries->sortBy('name')->values(),
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    public function getStates($country)
    {
        try {
            $response = Http::post('https://countriesnow.space/api/v0.1/countries/states', [
                "country" => $country
            ]);

            if ($response->failed() || !$response['data']) {
                return response()->json([
                    'status' => false,
                    'message' => "Failed to fetch states for {$country}",
                ], 400);
            }

            return response()->json([
                'status' => true,
                'message' => 'States fetched successfully',
                'data' => $response['data']['states'],
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    public function getCities($country, $state)
    {
        try {
            $url = "https://countriesnow.space/api/v0.1/countries/state/cities";

            $response = Http::post($url, [
                "country" => $country,
                "state"   => $state
            ]);

            if ($response->failed() || !$response['data']) {
                return response()->json([
                    'status' => false,
                    'message' => "Failed to fetch cities for {$state}, {$country}",
                ], 400);
            }

            return response()->json([
                'status' => true,
                'message' => 'Cities fetched successfully',
                'data' => $response['data'],
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => $e->getMessage(),
            ], 500);
        }
    }
}
