<?php

namespace App\Libs;

use App\Entity\Location;
use App\Entity\Messages;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;

class Libs extends AbstractController
{
    public static function getLatLonFromGeoapify($address): ?array
    {
        $address = urlencode($address);
        $url = "https://api.geoapify.com/v1/geocode/search?text={$address}&format=json&apiKey={$_ENV['GEOAPIFY_API_KEY']}";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $result = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($result, true);
        if (isset($result['results'][0]['lat']) && isset($result['results'][0]['lon'])) {
            $lat = $result['results'][0]['lat'];
            $lon = $result['results'][0]['lon'];
            return [number_format($lat, 6), number_format($lon, 6)];
        }
        return null;
    }

    public static function getRoute($lat1, $lon1, $lat2, $lon2): ?Route
    {
        $params = [
            'waypoints' => "{$lat1},{$lon1}|{$lat2},{$lon2}",
            'mode' => 'drive',
            'units' => 'imperial',
            'format' => 'json',
            'apiKey' => $_ENV['GEOAPIFY_API_KEY']
        ];

        $url = "https://api.geoapify.com/v1/routing?".http_build_query($params);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $result = curl_exec($ch);
        curl_close($ch);
        $route = new Route(json_decode($result));

        if (is_a($route, Route::class)) {
            return $route;
        }
        return null;
    }

    public static function getRouteDistance(Location $origin, Location $destination): ?Route
    {
        $route = self::getRoute($origin->getLat(), $origin->getLon(), $destination->getLat(), $destination->getLon());
        if ($route) {
            return $route;
        }
        return null;
    }

    #[Route('/api/autocomplete-address/{searchText}', name: 'app_api_autocomplete_address')]
    public function autocompleteAddress(string $searchText): Response
    {
        $params = [
            'text' => $searchText,
            'format' => 'json',
            'apiKey' => $_ENV['GEOAPIFY_API_KEY']
        ];

        $url = "https://api.geoapify.com/v1/autocomplete?".http_build_query($params);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $result = curl_exec($ch);
        curl_close($ch);

        return AbstractController::json($result);
    }

    public static function Phone(string $phone): string
    {
        $phone = preg_replace('/[^0-9]/', '', $phone);
        if(strlen($phone) > 10 && substr($phone, 0, 1) == '1') {
            $phone = substr($phone, 1);
        }
        return $phone;
    }

    public static function formatPhone(string $phone): string
    {
        $phone = self::Phone($phone);
        return "(".substr($phone, 0, 3).") ".substr($phone, 3, 3)."-".substr($phone, 6);
    }

    public static function getMessages(User $user, EntityManagerInterface $em): array
    {
        $msgs = $em->getRepository(Messages::class)->getUnreadMessages($user);

        return $msgs;
    }
}
