<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AddressController extends Controller
{

    public function index($code)
    {

        if (!empty($code)) {

            // $code = trim($code);

            $url = "https://api.addressian.co.uk/v2/autocomplete/" . str_replace(' ', '', $code);

            $curl = curl_init($url);
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

            $headers = array(
                "x-api-key: MxowUndV7X3FH9V3L0HvF2lBDyLsAaV77lPUCYO2",
                "Content-Type: application/json",
            );
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
            //for debug only!
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

            $resp = curl_exec($curl);
            curl_close($curl);
            $resp = json_decode($resp, true);

            $addresses = array();
            if (!empty($resp)) {

                $i = 0;
                foreach ($resp as $r) {

                    //$addresses[$i]["address"] = implode(", ", array_reverse($r["address"]));
                    $addresses[$i]["address"] = implode(", ", $r["address"]);
                    $addresses[$i]["city"] = $r["city"];
                    $addresses[$i]["postcode"] = $r["postcode"];
                    $i++;
                }

                $response["addresses"] = $addresses;
            } else {
                $response["addresses"] = array();
            }

            $response["success"] = TRUE;
            $header = 200;
        } else {
            $response["success"] = false;
            $header = 402;
        }
        return response()->json($response, $header);
    }

}