Files
kupshop/bundles/External/HannahBundle/Util/User/UserCardGenerator.php
2025-08-02 16:30:27 +02:00

77 lines
2.1 KiB
PHP

<?php
declare(strict_types=1);
namespace External\HannahBundle\Util\User;
use KupShop\KupShopBundle\Util\Pdf\HTMLToPDF;
class UserCardGenerator
{
/** Cislo na cvrte pozici EANu je na tvrdo. Zaciname na 9, aby se nemohlo stat, ze nastane kolize s aktualnima kartama */
public const EAN_FOURTH_POSITION_DIGIT = 9;
public function __construct(
private UserUtil $userUtil,
private HTMLToPDF $html2Pdf,
) {
}
public function generateUserCardPDF(int $userId, ?string $cardNumber = null): ?string
{
$card = $cardNumber ?: $this->userUtil->getUserCard($userId);
if (!$card) {
return null;
}
$smarty = createSmarty(false, true);
$smarty->assign([
'card' => $card,
]);
$html = $smarty->fetch('pdf/userCardPDF.tpl');
return $this->html2Pdf->generatePDF($html, return: true);
}
public function generateCustomerCardEAN(string $prefix, ?int $fourthPositionDigit = self::EAN_FOURTH_POSITION_DIGIT): int
{
$dbcfg = \Settings::getDefault();
$nextId = sqlGetConnection()->transactional(function () use ($dbcfg, $prefix) {
$series = $dbcfg->loadValue('oc_user_card_series') ?: [];
$series[$prefix] = $nextId = ($series[$prefix] ?? 0) + 1;
$dbcfg->saveValue('oc_user_card_series', $series, false);
return $nextId;
});
$eanPrefix = $prefix;
if ($fourthPositionDigit) {
$eanPrefix .= $fourthPositionDigit;
}
$ean12 = $eanPrefix.sprintf('%08d', $nextId);
return (int) ($ean12.$this->calculateEANChecksum($ean12));
}
private function calculateEANChecksum(string $ean): int
{
$sum = 0;
for ($i = 0; $i < strlen($ean); $i++) {
$digit = (int) $ean[$i];
if ($i % 2 == 0) {
// Odd position (0-based index), multiply by 1
$sum += $digit;
} else {
// Even position, multiply by 3
$sum += 3 * $digit;
}
}
return (10 - ($sum % 10)) % 10;
}
}