<?php

namespace PortalPeople\GetAddressAutocomplete\Controller\Checkout;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;

class Autocomplete extends Action
{
    private $resultJsonFactory;
    private $scopeConfig;

    public function __construct(
        Context $context,
        JsonFactory $resultJsonFactory,
        ScopeConfigInterface $scopeConfig
    ) {
        parent::__construct($context);
        $this->resultJsonFactory = $resultJsonFactory;
        $this->scopeConfig = $scopeConfig;
    }

    public function execute()
    {
        $resultJson = $this->resultJsonFactory->create();
        
        try {
            // Get the search term from request
            $term = trim($this->getRequest()->getParam('term', ''));
            
            if (empty($term)) {
                return $resultJson->setData([
                    'suggestions' => [],
                    'error' => 'Search term is required'
                ]);
            }
            
            // Get Domain Token from config (safe to use server-side)
            $domainToken = $this->scopeConfig->getValue(
                'checkout/getaddress_autocomplete/api_key',
                ScopeInterface::SCOPE_STORE
            );
            
            if (empty($domainToken)) {
                return $resultJson->setData([
                    'suggestions' => [],
                    'error' => 'Domain Token not configured'
                ]);
            }
            
            // Format postcode: UK postcodes need a space before last 3 chars
            $formattedTerm = strtoupper(preg_replace('/\s+/', '', $term));
            if (strlen($formattedTerm) > 3) {
                $formattedTerm = substr($formattedTerm, 0, -3) . ' ' . substr($formattedTerm, -3);
            }
            
            // Call GetAddress.io API from backend (no CORS issues)
            // Use rawurlencode to encode spaces as %20 (not + which urlencode produces)
            $url = 'https://api.getaddress.io/autocomplete/' . rawurlencode($formattedTerm) . '?api-key=' . rawurlencode($domainToken);
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 10,
                CURLOPT_SSL_VERIFYPEER => true,
                CURLOPT_USERAGENT => 'Magento2-GetAddressAutocomplete/1.0.38'
            ]);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($httpCode === 200) {
                $data = json_decode($response, true);
                return $resultJson->setData($data ?: ['suggestions' => []]);
            } else {
                return $resultJson->setData([
                    'suggestions' => [],
                    'error' => 'API returned status ' . $httpCode,
                    'detail' => $response,
                    'url_used' => $url
                ]);
            }
            
        } catch (\Exception $e) {
            return $resultJson->setData([
                'suggestions' => [],
                'error' => $e->getMessage()
            ]);
        }
    }
}
