<?php

class Client
{
    const apiURL = 'https://webservicesp.anaf.ro/PlatitorTvaRest/api/v4/ws/tva';
    const ANAF_CUI_LIMIT = 500;
    protected $cuis = array();
    public function addCui($fiscals, $date = null)
    {
        if (is_null($date)) {
            $date = date('Y-m-d');
        }
        if (!is_array($fiscals)) {
            $fiscals = [$fiscals];
        }
        foreach ($fiscals as $cui) {
            $cui = preg_replace('/\\D/', '', $cui);
            $this->cuis[] = ["cui" => $cui, "data" => $date];
        }
        return $this;
    }
    public function getResults()
    {
        $results = $this->callApi();
        foreach ($results as $company) {
            $company->adresa = $this->parseAddress($company->adresa);
        }
        return $results;
    }
    public function getOneResult()
    {
        $company = $this->callApi()[0];
        $company->adresa = $this->parseAddress($company->adresa);
        return $company;
    }
    public function callApi()
    {
        $curl = curl_init();
        curl_setopt_array($curl, array(CURLOPT_URL => self::apiURL, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => json_encode($this->cuis), CURLOPT_HTTPHEADER => array("Cache-Control: no-cache", "Content-Type: application/json")));
        $response = curl_exec($curl);
        $info = curl_getinfo($curl);
        curl_close($curl);
        if (!isset($info['http_code']) || $info['http_code'] !== 200) {
            wp_die("Response status: {$info['http_code']} | Response body: {$response}");
        }
        $items = json_decode($response);
        if (json_last_error() !== JSON_ERROR_NONE) {
            wp_die("Json parse error | Response body: {$response}");
        }
        if ("SUCCESS" !== $items->message || 200 !== $items->cod) {
            wp_die("Response message: {$items->message} | Response body: {$response}");
        }
        return $items->found;
    }
    private function parseAddress($raw)
    {
        if (empty($raw)) {
            return $raw;
        }
        $rawText = mb_convert_case($raw, MB_CASE_TITLE, 'UTF-8');
        $list = array_map('trim', explode(",", $rawText, 5));
        list($judet, $localitate, $strada, $numar, $altele) = array_pad($list, 5, '');
        $judet = trim(str_replace('Jud.', '', $judet));
        $localitate = trim(str_replace(['Mun.', 'Orş.'], ['', 'Oraş'], $localitate));
        $strada = trim(str_replace('Str.', '', $strada));
        $numar = trim(str_replace('Nr.', '', $numar));
        $address = new stdClass();
        $address->raw = $raw;
        $address->judet = $judet;
        $address->localitate = $localitate;
        $address->strada = $strada;
        $address->numar = $numar;
        $address->altele = $altele;
        return $address;
    }
}