<?php

/*
 * @component UserPoints
 * @copyright Copyright (C) 2015-2022 Bernard Gilly - Adrien Roussel - Martin Brampton
 * @license : GNU/GPL
 * @Website : https://remository.com
 */

namespace BlackSheepResearch\Component\UserPoints\Site\Problems;

defined('_JEXEC') or die;

use BlackSheepResearch\Component\UserPoints\Site\UserPoints;

// Look at https://github.com/picqer/php-barcode-generator 

class Coupon extends ProblemBase {

    protected static $fieldnames = [];
    protected static $fieldtypes = [];
    protected static $count = -1;
    protected static $tablename = '#__alpha_userpoints_coupons';
    protected static $updatetable = '#__alpha_userpoints_coupons';
    protected static $keyname = 'id';

    public function __construct(int $id = 0) {
        parent::__construct();
        if ($id) {
            $this->getOneRow($id);
        }
    }

    public static function withCouponcode($couponcode) {
        $coupon = new self();
        $db = SQL::getInstance();
        $db->setQuery(sprintf("SELECT * FROM `%s` WHERE couponcode LIKE %s", self::$tablename, $db->quote($couponcode)));
        $object = $db->loadObject();
        if (is_object($object)) {
            $coupon->problem_object = $object;
        }
        return $coupon;
    }

    public function hasExpired() : bool {
        return ($this->expires == SQL::nulldatetimeSQL() OR $this->expires < SQL::datetimeSQL());
    }

    public function hasBeenUsed() : bool {
        $db = SQL::getInstance();
        $query = "SELECT count(*) FROM #__alpha_userpoints_details WHERE `keyreference` LIKE {$db->quote($this->couponcode)} AND `enabled`='1'";
        $db->setQuery($query);
        return $db->loadResult() ? true : false;
    }

    public function redeem(string $referrerid) : bool {
        return UserPoints::newpoints('sysplgup_couponpointscodes', $referrerid, $this->couponcode, $this->description, $this->points);
    }
    
    public function QR (int $size = 200) : string {
        $encoupon = urlencode($this->couponcode);
        return "https://quickchart.io/qr?text={$encoupon}&caption=UserPoints&size=$size";
    }
}
