<?php

namespace App\Traits;

trait VehicleRegistrationDateFinderTrait
{
    public function getRegistrationDateFromRegistrationNumber(?string $regNumber)
    {
        // unsupported VRM format
        if (is_numeric($regNumber)) {
            return null;
        }

        if (is_numeric(substr((string) $regNumber, 0, 2)) || is_numeric(substr((string) $regNumber, 0, 3))) {
            $num = (int)substr((string) $regNumber, 0, 3);
            return $this->getIrelandRegistrationDate($num);
        } elseif (preg_match('/^[A-Za-z]{2}\d{2}/', (string) $regNumber)) {
            $num = substr((string) $regNumber, 2, 2);
            return $this->getUKRegistrationDate($num);
        }
        return null;
    }

    private function getUKRegistrationDate($num): ?string
    {
        // I.E if a num is for instance 52, based on that table, 52 falls under 2002/03 for year,
        // and 1 September – 28/29 February for month.
        // Earliest date for this would be 2002-09-01

        // Handle special cases
        if ($num == 'Y') {
            // This should most likely not run, but we keep it here
            // Because any vehicle < 2001 will most likely not qualify for financing
            // which is the main purpose we set up this registration date finder
            return '2001-03-01';
        }

        if ($num == '00') {
            return '2050-09-01';
        }

        if (is_numeric($num)) {
            $start = 2;
            $end = 99;
            for ($i = $start; $i <= $end; $i++) {
                if ((int)$num === $i) {
                    if ($i <= 50) {
                        $iFormatted = $this->iFormat($i);
                        $yearToUse = '20' . $iFormatted;
                        return $yearToUse . '-03-01';
                    } elseif ($i >= 51 && $i <= 99) {
                        $iFormatted = $this->iFormat($i - 50);
                        $yearToUse = '20' . $iFormatted;
                        return $yearToUse . '-09-01';
                    }
                }
            }
        }

        return null;
    }

    private function getIrelandRegistrationDate($num): string
    {
        // https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_the_Republic_of_Ireland#Format_and_specifications

        //cast num back to string
        $num = (string)$num;

        if (strlen($num) === 2) {
            // this must be the old format for cars <= 2012
            $iFormatted = $this->iFormat($num);
            return '20' . $iFormatted . '-01-01';
        } else {
            $iFormatted = $this->iFormat(substr($num, 0, 2));
            $yearToUse = '20' . $iFormatted;
            if (str_ends_with($num, '1')) {
                return $yearToUse . '-01-01';
            } else {
                return $yearToUse . '-07-01';
            }
        }
    }


    private function iFormat(string $i): string
    {
        return strlen($i) >= 2 ? $i : '0' . $i;
    }
}
