<?php

declare(strict_types=1);

/*
 * This file is part of alox bundle for Contao.
 *
 * (c) Benjamin Roth
 *
 * @license commercial
 */

namespace vossmedien\AloxBundle\Controller\Frontend;

use Contao\CoreBundle\Controller\AbstractController;
use Contao\CoreBundle\Framework\ContaoFramework;
use Doctrine\DBAL\Connection;
use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\Translation\TranslatorInterface;

class GeodbAjaxController extends AbstractController
{

    /**
     * @var TranslatorInterface
     */
    protected $translator;
    /**
     * @var Request
     */
    protected $request;
    /**
     * @var ContaoFramework
     */
    protected $framework;
    /**
     * @var Connection
     */
    protected $db;



    public function __construct(ContainerInterface $container, TranslatorInterface $translator, RequestStack $request, ContaoFramework $framework, Connection $connection)
    {
        $this->container = $container;
        $this->initializeContaoFramework();
        $this->translator = $translator;
        $this->request = $request->getCurrentRequest();
        $this->framework = $framework;
        $this->db = $connection;
    }


    /**
     * @Route("/_geodb/getLatLon", name="geodb_latlon", defaults={"_scope" = "frontend", "_token_check" = false})
     *
     * @return Response
     */
    public function getLatLon()
    {
        global $objPage;

        if (isset($_REQUEST['q']))
        {
            $result = [
                'items' => []
            ];

            $query = $this->db->executeQuery("SELECT lat, lon, postal, name FROM tl_ab_geodb WHERE (name LIKE ? OR postal LIKE ?) AND type IN ('Dorf','Ortsteil','Ortschaft','Ort','Kreisstadt','Gemeinde','Stadt','Stadtteil') AND invalid != '1' AND postal != ''",[
                '%' . $_REQUEST['q'] . '%',
                '%' . $_REQUEST['q'] . '%',
            ]);

            if ($query->rowCount())
            {
                foreach ($query->fetchAllAssociative() as $item)
                {
                    $result['items'][] = [
                        'latLon' => $item['lat'].','.$item['lon'],
                        'name' => $item['postal'].' '.$item['name']
                    ];
                }
            }

            return new JsonResponse($result);
        }


        return new Response('Required parameter missing',412);
    }
}