<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class GhanaPhoneNumber implements ValidationRule
{
    private $networkCodes = ['024', '025', '054', '055', '059', '023', '053', '026', '056', '027', '057', '028', '020', '050'];


    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (empty($value)) {
            $fail('The :attribute field is required.');
        }

        $numberString = str_replace(' ', '', (string) $value);

        // Normalize phone number
        if (strlen($numberString) === 9 && $numberString[0] !== '0') {
            $numberString = "0{$numberString}";
        } elseif (strlen($numberString) > 10 && substr($numberString, 0, 3) === '233') {
            $numberString = "0{$numberString}";
        }

        if (strlen($numberString) !== 10) {
            $fail('The :attribute must be 10 digits long.');
        }

        if ($numberString[0] !== '0') {
            $fail('The :attribute must start with 0.');
        }

        $networkCode = substr($numberString, 0, 3);
        if (!in_array($networkCode, $this->networkCodes, true)) {
            $fail('The :attribute must be a valid Ghana phone number.');
        }
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be a valid Ghana phone number.';
    }

    /**
     * Get the network information for a valid phone number.
     *
     * @param string $phoneNumber
     * @return array|null
     */
    public static function getNetworkInfo($phoneNumber)
    {
        $mtn = ["name" => "MTN", "slug" => "mtn"];
        $glo = ["name" => "Globacom", "slug" => "glo"];
        $airtelTigo = ["name" => "AirtelTigo", "slug" => "airteltigo"];
        $expresso = ["name" => "Expresso", "slug" => "expresso"];
        $vodafone = ["name" => "Vodafone", "slug" => "vodafone"];
        $inValid = ["name" => null, "slug" => null];

        $self = new static;
        $isValid = true;
        $self->validate('phone', $phoneNumber, function ($message) use (&$isValid) {
            $isValid = false;
        });

        if (!$isValid) {
            return $inValid;
        }

        $networkCode = substr($phoneNumber, 0, 3);

        if (in_array($networkCode, ['024', '054', '055'], true)) {
            return $mtn;
        } elseif (in_array($networkCode, ['023'], true)) {
            return $glo;
        } elseif (in_array($networkCode, ['026', '056', '027', '057'], true)) {
            return $airtelTigo;
        } elseif (in_array($networkCode, ['028'], true)) {
            return $expresso;
        } elseif (in_array($networkCode, ['020', '050'], true)) {
            return $vodafone;
        }

        return $inValid;
    }
}