<?php

$text = $languageForm['changeCreditCard'];

$error['changeCreditCard']['form'] = [];

function validateExpiryDate($input)
{
    $month_year = explode("/", $input);
    $month = (int)$month_year[0];
    $year = (int)$month_year[1];

    if ($year < date("y") ||  $year == date("y") && $month < date("n")) {
        return false;
    }

    return true;
}

do {
    if (isset($_POST) && isset($_POST['submitChangeCreditCard'])) {
        $rules = [
            'cardHolder' => [ "regex" => REGEX_UNIVERSAL_NAME_EXTRA ],
            'cvcNumber' => [ "regex" => REGEX_CVC_NUMBER ],
            'cardNumber' => [
                "regex" => REGEX_CREDIT_CARD,
                "replace"  => [" ", ""]
            ],
            'expiryDate' => [
                "regex" => REGEX_EXPIRY_DATE,
                "replace"  => [" ", ""],
                "custom" => "validateExpiryDate"
            ]
        ];

        $data = ['id' => $_SESSION['id']];

        foreach ($rules as $field => $rule) {
            if (!isset($_POST[$field])) {
                $error['changeCreditCard']['form'][$field][] = $languageStd['missing'] . $languageValidation[$field]['name'];
            } else {
                $input = isset($rule['replace']) ? str_replace($rule['replace'][0], $rule['replace'][1], $_POST[$field]) : $_POST[$field];

                if (empty($input)) {
                    $error['changeCreditCard']['form'][$field][] = $languageValidation[$field]['name'] . $languageStd['empty'];
                }

                if (isset($rule['regex']) && !preg_match($rule['regex'], $input) ||
                    isset($rule['custom']) && !$rule['custom']($input)) {
                    $error['changeCreditCard']['form'][$field][] = $languageValidation[$field]['validation'];
                }
            }

            if (!isset($error['changeCreditCard']['form'][$field])) {
                $data[$field] = $input;
            }
        }

        if (count($error['changeCreditCard']['form'])) {
            break;
        }

        if (api(API_REQ_CHANGE_CREDIT_CARD, $data, $json)) {
            $success['changeCreditCard'][] = $languageSuccess['changeCreditCard']['changed'];

            $_POST['cardHolder'] = "";
            $_POST['cardNumber'] = "";
            $_POST['expiryDate'] = "";
            $_POST['cvcNumber'] = "";

            break;
        }

        $data['cardHolder'] = "";
        $data['cardNumber'] = "";
        $data['expiryDate'] = "";
        $data['cvcNumber'] = "";

        $error['changeCreditCard']['form']['invalidCreditCard'][] = $languageError['changeCreditCard']['invalidCreditCard'];
    }
} while (0);
