<?php

namespace App\Http\Controllers;

use App\Classes\Modules\AddressBook\DataTransferObjects\AddressBookObject;
use App\Classes\Modules\AddressBook\Services\CreatesAddress;
use App\Models\Company;
use Barryvdh\DomPDF\PDF;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Facades\Excel;
use App\Classes\Excel\Import\CompaniesImport;

class TestController extends Controller
{

    /** @var PDF */
    private $pdf;
    /** @var CreatesAddress */
    private $createsAddress;

    /**
     * TestController constructor.
     * @param PDF $pdf
     * @param CreatesAddress $createsAddress
     */
    public function __construct(PDF $pdf, CreatesAddress $createsAddress)
    {
        $this->pdf = $pdf;
        $this->createsAddress = $createsAddress;
    }


    public function index(Request $request){
//        return view('pages.pdf.qr');
        return $this->pdf->loadView('pages.pdf.qr')->stream();

        $companiesImport = Excel::toArray(new CompaniesImport(), $request->file('xsl'));
        $companies = new Collection();

        foreach ($companiesImport[0] as $key => $company){
            if($key !== 0) {
                try {
                    if(trim($company[1])){
                        $billingAddress = $this->convertAddress(trim($company[6]) .' '. trim($company[7]) .' '. trim($company[8]) .' '. trim($company[9]));
                        $newCompany = new Company();
                        $newCompany->name = ucwords(strtolower(trim($company[0])));
                        $newCompany->marking = trim($company[1]);
                        $newCompany->registration_no = trim($company[2]);
                        $newCompany->save();

                        $request->request->add(['street_one' => trim($billingAddress['street_address'])]);
                        $request->request->add(['city' => ucwords(trim($billingAddress['city']))]);
                        $request->request->add(['post_code' => ucwords(trim($billingAddress['post_code']))]);
                        $request->request->add(['country' => ucwords(trim($billingAddress['country']))]);

                        $billing = new AddressBookObject(null, $newCompany->id, 'Business Address', $company[5],
                            $billingAddress['street_address'], null, ucwords($billingAddress['city']),
                            ucwords($billingAddress['state']), $billingAddress['post_code'], ucwords($billingAddress['country']), false, true);

                        $this->createsAddress->execute($billing);

                        if (trim($company[6]) .' '. trim($company[7]) .' '. trim($company[8]) .' '. trim($company[9]) != trim($company[13]) .' '. trim($company[14]) .' '. trim($company[15]) .' '. trim($company[16])){
                            $deliveryAddress = $this->convertAddress(trim($company[13]) .' '. trim($company[14]) .' '. trim($company[15]) .' '. trim($company[16]));
                            $delivery = new AddressBookObject(null, $newCompany->id, 'Default Delivery Address', $company[5],
                                $deliveryAddress['street_address'], null, ucwords($deliveryAddress['city']),
                                ucwords($deliveryAddress['state']), $deliveryAddress['post_code'],  ucwords($deliveryAddress['country']), true, false);
                            $this->createsAddress->execute($delivery);
                        }

                    }
                } catch (QueryException $exception){

                }



//                $companies->push([
//                    'name' => ucwords(strtolower(trim($company[0]))),
//                    'marking' => trim($company[1]),
//                    'registration_no' => $company[2],
//                    'contact' => [
//                        'name' => $company[3],
//                        'email' => $company[4],
//                        'phone' => $company[5],
//                    ],
//                    'address' => $this->convertAddress(trim($company[6]) .' '. trim($company[7]) .' '. trim($company[8]) .' '. trim($company[9])),
//                    'address_book' => $this->convertAddress(trim($company[13]) .' '. trim($company[14]) .' '. trim($company[15]) .' '. trim($company[16]))
////                    'shipping_rate' => $company[17]
//                ]);
//                $companies->push($this->convertAddress(trim($company[6]) .' '. trim($company[7]) .' '. trim($company[8]) .' '. trim($company[9])));
            }
        }

        dd($companies);
    }

    private function cleanAddress(string $address){
        $string = strtolower($address);
        $string = str_replace(', ',' ',$string);
        $string = str_replace(',',' ',$string);
        $string = str_replace('no.','no|',$string);
        $string = str_replace('.','',$string);
        $string = str_replace('no|','no ',$string);
        $string = str_replace('，','',$string);
        $string = str_replace(' kl ',' kuala lumpur ', $string);
        $string = str_replace('selangor darul ehsan','selangor', $string);
        $string = str_replace('malaysia','',$string);
        $string = str_replace('wp','',$string);
        $string = str_replace('melaka','malacca',$string);
        $string = str_replace('pj','petaling jaya',$string);
        $string = str_replace('kualalumpur','kuala lumpur',$string);
        $string = str_replace('wilayah persekutuan','',$string);
        return trim($string);
    }

    private function convertAddress(string $string){
        $address = $this->cleanAddress($string);
        $postcode = '';

        $state = $this->addressState($address);
        if($state !== ''){
            $address = preg_replace('~'.' '.$state.'(?!.*'.' '.$state.')~', '', $address);
            if($state === 'penang'){
                $address =  preg_replace('~pulau pinang(?!.*'.' pulau pinang)~', '', $address);
            }
        }

        $city = '';

        if(preg_match('~\d{5,6}(?!.*'.'\d{5,6})~', $address, $postCodes)){
            $postcode = $postCodes[0];
            $array = explode($postcode.' ', $address);
            if(count($array) > 1){
                $city = $array[1];
                if(strpos($city, 'kuala lumpur')){
                    $city = str_replace(' kuala lumpur','', $city);
                    $state = 'kuala lumpur';
                    $address = str_replace(' kuala lumpur','', $address);
                }

            } else {
                if(strpos($address, 'kuala lumpur')){
                    $city = 'kuala lumpur';
                }
            }

            if($city !== ''){
                $address = str_replace(' '.$city,'', $address);
            }

            $address = str_replace(' '.$postcode,'', $address);
        }

        $country = 'malaysia';
        if(strpos($address, 'singapore')){
            $country = 'singapore';
            $address = str_replace(' singapore','', $address);
        }

        $address = preg_replace('/\s+/', ' ', $address);
        $address = ucwords($address);

        return [
            'street_address' => trim($address),
            'city' => $city,
            'post_code' => $postcode,
            'state' => $state,
            'country' => $country
        ];
    }

    private function addressState(string $string){
        $states = ['penang', 'selangor', 'johor', 'sabah', 'sarawak', 'malacca', 'perak', 'kelantan', 'kedah', 'pahang', 'terengganu', 'negeri sembilan', 'perlis', 'kuala lumpur', 'pulau pinang'];
        foreach ($states as $state){
            if(stripos($string, $state)){
                if($state === 'pulau pinang'){
                    return 'penang';
                }
                return $state;
            }
        }
        return '';
    }
}
