<?php
namespace GlobalPayments\Api\Terminals\PAX\SubGroups;

use GlobalPayments\Api\Terminals\Abstractions\IResponseSubGroup;
use GlobalPayments\Api\Terminals\Enums\ControlCodes;
use GlobalPayments\Api\Utils\EnumUtils;
use GlobalPayments\Api\Terminals\PAX\Entities\Enums\PaxEntryMode;
use GlobalPayments\Api\Terminals\Enums\TerminalCardType;

class AccountResponse implements IResponseSubGroup
{

    public ?string $accountNumber = null;

    public ?string $entryMode = null;

    public ?string $expireDate = null;

    public ?string $ebtType = null;

    public ?string $voucherNumber = null;

    public ?string $newAccountNumber = null;

    public ?string $cardType = null;

    public ?string $cardHolder = null;

    public ?string $cvdApprovalCode = null;

    public ?string $cvdMessage = null;

    public ?string $cardPresent = null;

    public function __construct($messageReader)
    {
        $responseString = $messageReader->readToCode(ControlCodes::FS);
        // Split using ControlCodes::US
        $response = preg_split('/[\x1F;]/', $responseString);
        try {
            $responseIndexMapping = [
                'accountNumber' => 0,
                'expireDate' => 2,
                'ebtType' => 3,
                'voucherNumber' => 4,
                'newAccountNumber' => 5,
                'cardHolder' => 7,
                'cvdApprovalCode' => 8,
                'cvdMessage' => 9,
                'cardPresent' => 10
            ];

            foreach ($responseIndexMapping as $property => $index) {
                $this->{$property} = (isset($response[$index])) ? $response[$index] : '';
            }

            // entry mode and card Type
            if (isset($response[1])) {
                $entryMode = EnumUtils::parse(new PaxEntryMode(), $response[1]);
                $this->entryMode = str_replace('_', ' ', $entryMode);
            }

            if (isset($response[6])) {
                $cardType = EnumUtils::parse(new TerminalCardType(), $response[6]);
                $this->cardType = str_replace('_', ' ', $cardType);
            }
        } catch (\Exception $e) {
        }
    }
}
