<?php
// retour array('label'=>'', 'amount'=>0)
/** Order */
function discount($order)
{
    $ret = ['label' => '', 'amount' => 0];
    $variables = $order->getRequest()->getVariables();
    $codes = $variables->getValueByName('promo');

    $key = strtoupper($order->codepromo);
    if (is_array($codes) && array_key_exists($key, $codes)) {
        $amount=0;
        foreach($codes[$key] as $code) {
            $start = convertDte($code['start'] . ' 00:00:00');
            $end = convertDte($code['end'] . ' 23:59:59');
            $minAmount = $code['amount'];
            $now = new \DateTime();
            if ((!$start || $now >= $start) && (!$end || $now < $end) && $minAmount > $amount && $order->getSubTotal() > $minAmount) {
                $amount=$minAmount;
                $ret['label'] = $code['label'];
                $ret['amount'] = $code['rate'] * $order->getSubTotal();
            }
        }
    }
    return $ret;
}
function convertDte($dte)
{
    $d=\DateTime::createFromFormat('Y-m-d H:i:s',$dte);
    return ($d && $dte==$d->format('Y-m-d H:i:s'))? new \DateTime($dte):null;
}