<?php

namespace Myvetshop\Module\Clinique\Import\Sync\Syncer;

use Myvetshop\Module\Clinique\Import\Model\RewardModel;

class RewardSyncer
{
    protected \Db $db;

    public function __construct(\Db $db)
    {
        $this->db = $db;
    }

    public function sync(\Customer $customer, RewardModel $rewardModel): void
    {
        $nbPoints = \number_format($rewardModel->getPointsMvs(), 2, '.', '');

        $row = $this->db->getRow(
            'SELECT l.*'
            . ' FROM ' . _DB_PREFIX_ . 'loyaltyeditpoints l'
            . ' WHERE id_customer = ' . (int) $customer->id
            . ' AND id_order = 0'
            . ' AND points = "' . $this->db->escape($nbPoints) . '"',
            false
        );

        $now = \date('Y-m-d H:i:s');

        if (!$row) {
            $this->db->execute(
                'INSERT INTO ' . _DB_PREFIX_ . 'loyaltyeditpoints'
                . '(id_shop, state, id_customer, id_order, id_cart_rule, points, expiry_days, date_validation, date_add, date_upd)'
                . ' VALUES ('
                . '1, 2, ' . (int) $customer->id . ', 0, 0, "' . $this->db->escape($nbPoints) . '", 0, "0000-00-00 00:00:00"'
                . ', "' . $this->db->escape($now) . '", "' . $this->db->escape($now) . '"'
                . ')'
            );
        }
    }
}
