<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */
class Pruefziffer_51 implements IPruefziffer
{
  public static function check($pKtoNr, $pBlz, $pGewichtung = array(), $pPruefZifferStelle = 9)
  {
    $ktoNr = str_pad($pKtoNr, 10, '0', STR_PAD_LEFT);

    if ($ktoNr[2] == 9) {
      $result = self::variante1($ktoNr, $pPruefZifferStelle);
      if (!$result) {
        $result = self::variante2($ktoNr, $pPruefZifferStelle);
      }
    } else {
      $result = self::methodeA($ktoNr);
      if (!$result) {
        $result = self::methodeB($ktoNr);
      }
      if (!$result) {
        $result = self::methodeC($ktoNr);
      }
      if (!$result) {
        $result = self::methodeD($ktoNr, $pPruefZifferStelle);
      }
    }

    return $result;
  }

  private static function methodeA($pKtoNr)
  {
    $gewichtung = array(0, 2, 3, 4, 5, 6, 7, 0, 0, 0);

    return Pruefziffer_06::check($pKtoNr, null, $gewichtung);
  }

  private static function methodeB($pKtoNr)
  {
    return Pruefziffer_33::check($pKtoNr, null);
  }

  private static function methodeC($pKtoNr)
  {
    $gewichtung = array(0, 2, 1, 2, 1, 2, 1, 0, 0, 0);

    return Pruefziffer_00::check($pKtoNr, null, $gewichtung);
  }

  private static function methodeD($pKtoNr, $pPruefZifferStelle)
  {
    $gewichtung = array(0, 2, 3, 4, 5, 6, 0, 0, 0, 0);

    $strZahl = strrev($pKtoNr);
    $ary = PruefZiffHelpers::gewichten($strZahl, $gewichtung);

    $rest = array_sum($ary) % 7;

    $result = (7 - $rest) % 7;

    return ($result == $pKtoNr[$pPruefZifferStelle]);
  }

  private static function variante1($pKtoNr, $pPruefZifferStelle, $pGewichtung = array())
  {
    if (empty($pGewichtung)) {
      $gewichtung = array(0, 2, 3, 4, 5, 6, 7, 8, 0, 0);
    } else {
      $gewichtung = $pGewichtung;
    }

    $strZahl = strrev($pKtoNr);
    $ary = PruefZiffHelpers::gewichten($strZahl, $gewichtung);

    $rest = array_sum($ary) % 11;

    
    $result = ((11 - $rest) % 11) % 10;

    return ($result == $pKtoNr[$pPruefZifferStelle]);
  }

  private static function variante2($pKtoNr, $pPruefZifferStelle)
  {
    $gewichtung = array(0, 2, 3, 4, 5, 6, 7, 8, 9, 10);

    return self::variante1($pKtoNr, $pPruefZifferStelle, $gewichtung);
  }
}