<?php
/**
 * _             _       _
 * | |____      _| | __ _| |__
 * | '_ \ \ /\ / / |/ _` | '_ \
 * | |_) \ V  V /| | (_| | |_) |
 * |_.__/ \_/\_/ |_|\__,_|_.__/.
 *
 * @author    Bwlab di Luigi Massa <info@bwlab.it>
 * @copyright since 2014 Bwlab
 * @license   proprietary
 */

declare(strict_types=1);

namespace Bwlab\Withdrawal\Hook;

if (!defined('_PS_VERSION_')) {
    exit;
}


use Bwlab\Withdrawal\Service\PrestashopVersionChecker;

class DashboardHookHandler
{
    private const DISPLAY_DELAY_DAYS = 20;
    private const INSTALL_DATE_KEY = 'BWWITHDRAWAL_INSTALL_DATE';

    public function __construct(
        private readonly PrestashopVersionChecker $versionChecker,
    ) {
    }

    /** The card only shows starting 20 days after the module was installed. */
    public function shouldDisplay(): bool
    {
        $installTs = (int) \Configuration::get(self::INSTALL_DATE_KEY);
        if ($installTs === 0) {
            // backfill for instances installed before this key existed: start the clock now
            $installTs = time();
            \Configuration::updateValue(self::INSTALL_DATE_KEY, $installTs);
        }

        return time() >= $installTs + self::DISPLAY_DELAY_DAYS * 86400;
    }

    /** @return array<string, mixed> template variables for the dashboard card */
    public function getTemplateVars(): array
    {
        return [
            'bwwithdrawal_installed_version' => $this->versionChecker->getInstalledVersion(),
            'bwwithdrawal_latest_version' => $this->versionChecker->getLatestVersion(),
            'bwwithdrawal_up_to_date' => $this->versionChecker->isUpToDate(),
        ];
    }
}
