<?php

class PaxyprestaPaxypostcodesModuleFrontController extends ModuleFrontController
{
    public function __construct()
    {
        parent::__construct();
    }

    public function initContent(){
        $this->ajax = true;

        $country = Tools::getValue('country', null);
        $city = Tools::getValue('city', null);
        $address = Tools::getValue('address', null);

        if (empty($country)) {
            die(json_encode([
                'success' => false,
                'message' => 'Missing country!'
            ]));
        } else if (!in_array($country, ['ro'])) {
            die(json_encode([
                'success' => false,
                'message' => 'Selected country is not supported!'
            ]));
        }

        if (empty($city)) {
            die(json_encode([
                'success' => false,
                'message' => 'Missing city!'
            ]));
        }

        $data = [];
        switch ($country) {
            case 'ro':
                $data = $this->readRo();
                break;
        }

        $suggestedPostcodes = [];
        array_filter($data, function ($item) use ($city, $address, &$suggestedPostcodes) {
            $cityRegExp = '/' . $city . '/i';
            if (!!preg_match($cityRegExp, $item['city'])) {
                if (!empty($address)) {
                    $addressRegExp = '/' . $address . '/i';
                    if (!!preg_match($addressRegExp, $item['address'])) {
                        $suggestedPostcodes[] = $item['postcode'];
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    $suggestedPostcodes[] = $item['postcode'];
                    return true;
                }
            }
            return false;
        });


        die(json_encode([
            'success' => true,
            'country' => $country,
            'city' => $city,
            'address' => $address,
            'suggestedPostcodes' => array_values(array_unique($suggestedPostcodes)),
        ]));
    }

    public function readRo() {
        $rows = [];
        if (($handle = fopen(implode(DIRECTORY_SEPARATOR, [__DIR__, '..', '..', 'inc', 'addresses-ro.csv']), "r")) !== false) {
            $rowIndex = 0;
            while (($row = fgetcsv($handle, null, ';')) !== false) {
                if ($rowIndex === 0) {
                    $rowIndex++;
                    continue;
                }

                $rows[] = [
                    'city' => $row[0],
                    'postcode' => $row[1],
                    'address' => $row[2],
                ];

                $rowIndex++;
            }
        }

        return $rows;
    }
}
