<?php
/**
 * Created by PhpStorm.
 * User: Omair Saleh
 * Date: 20/8/2021
 * Time: 1:05 AM
 */

namespace App\Classes\Modules\Addresses\Services;


use App\Classes\Modules\Addresses\DataTransferObjects\AddressObject;
use App\Models\District;
use App\Models\OldAddress;

class CleansOldAddress
{

    public function execute(OldAddress $address){
        if($address->street_one === '' && $address->street_two === ''){
            return null;
        }

        if(!$address->post_code){
            return null;
        }

        $district = District::where('postcode', 'like', '%'. $address->post_code .'%')->first();

        if(!$district) {
            return null;
        }

        return new AddressObject($this->cleanAddress($address->street_one, $district, $address->post_code), $this->cleanAddress($address->street_two, $district, $address->post_code), $district->country_id, $district->state_id, $district->id, $address->post_code, 'Delivery Address');

    }

    public function cleanAddress($address, $district, $postcode){
        $address = str_replace('Malaysia', '', str_replace('malaysia', '', str_replace('MALAYSIA', '', $address)));
        $address = str_replace($district->state->name, '',str_replace($district->name, '', $address));
        $address = str_replace(strtolower($district->state->name), '',str_replace(strtolower($district->name), '', $address));
        $address = str_replace(strtoupper($district->state->name), '',str_replace(strtoupper($district->name), '', $address));
        $address = str_replace($postcode, '', $address);
        $address = str_replace(', ,', ',', str_replace(', ,', ',', str_replace(', ,', ',', $address)));
        $address = str_replace(',', ', ', $address);
        $address = preg_replace('!\s+!', ' ', $address);
        $address = preg_replace("/,+/", ",", $address);
        return rtrim(rtrim(rtrim(rtrim($address, '.')), ','));

    }

}