<?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\Administrator\Models;

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();

use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Language\Text;
use Joomla\CMS\HTML\HTMLHelper;
use BlackSheepResearch\Component\UserPoints\Administrator\Model;
use BlackSheepResearch\Component\UserPoints\Site\Problems\SQL;
use BlackSheepResearch\Component\UserPoints\Site\Problems\Rule;
use BlackSheepResearch\Component\UserPoints\Site\Problems\Coupon;
use BlackSheepResearch\Component\UserPoints\Site\Problems\QRCodeTrack;

class Couponcodes extends Model {

    function __construct() {
        parent::__construct();
    }

    function _load_couponcodes() {
        $app = Factory::getApplication();
        $db = SQL::getInstance();
        // Get the pagination request variables
        list($limitstart, $limit) = Coupon::getLimitsFromRequest();
        $filter_state = $app->input->get('filter_state', '', 'string');
        $filter_category_id = $app->input->get('filter_category_id', 0, 'int');
        $filter = $filter_state ? "WHERE a.printable = {$db->quote($filter_state)}" : "WHERE (a.printable='1' OR a.printable='0')";

        if ($filter_category_id > 1) {
            $filter .= " AND a.category = $filter_category_id";
        }

        $query = "SELECT a.*, c.title AS category_title FROM #__alpha_userpoints_coupons AS a, #__categories AS c $filter AND c.id=a.category";
        $total = $this->_getListCount($query);
        $result = $this->_getList($query, $limitstart, $limit);

        // message if rule disabled
        $rule = Rule::withRuleName('sysplgup_couponpointscodes');
        if (!$rule->published) {
            $app->enqueueMessage(Text::_('AUP_THIS_RULE_IS_DISABLED'));
        }

        $lists = array();
        $options[] = HTMLHelper::_('select.option', '', Text::_('AUP_ALL'));
        $options[] = HTMLHelper::_('select.option', '1', Text::_('AUP_PRINTABLE'));
        $options[] = HTMLHelper::_('select.option', '0', Text::_('AUP_UNPRINTABLE'));
        $lists['filter_state'] = HTMLHelper::_('select.genericlist', $options, 'filter_state', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $filter_state);

        $lists['filter_category_id'] = $filter_category_id;
        $lists['public'] = HTMLHelper::_('select.booleanlist', 'public', 'class="inputbox"', 1);
        $lists['printable'] = HTMLHelper::_('select.booleanlist', 'printable', 'class="inputbox"', 0);
        $lists['enabledincrement'] = HTMLHelper::_('select.booleanlist', 'enabledincrement', 'class="inputbox"', 0);

        return array($result, $total, $limit, $limitstart, $lists);
    }

    function _edit_coupon() {
        $cid = Factory::getApplication()->input->get('cid', array(0), 'array');
        $option = Factory::getApplication()->input->get('option', '', 'cmd');

        if (!is_array($cid)) {
            $cid = array(0);
        }

        $row = new Coupon($cid[0]);

        $lists = array();
        $lists['public'] = HTMLHelper::_('select.booleanlist', 'public', 'class="inputbox"', $row->public);
        $lists['printable'] = HTMLHelper::_('select.booleanlist', 'printable', 'class="inputbox"', $row->printable);

        $lists['filter_category_id'] = $row->category;

        return array($row, $lists);
    }

    function _delete_coupon() {
        $app = Factory::getApplication();
        $cid = array_map('\\intval', $app->input->get('cid', array(), 'array'));
        if (count($cid)) {
            Coupon::deleteMany($cid);
        }
        $this->redirect('index.php?option=com_userpoints&task=couponcodes');
    }

    function _save_coupon($apply = 0) {
        $app = Factory::getApplication();
        //$post	= $app->input->post;
        $post = $app->input->post->getArray();
        $id = $app->input->get('id', 0, 'int');
        if ($post['couponcode'] == '') {
            $post['couponcode'] = $random = $this->createRandomCode();
        }

        $row = new Coupon();
        $row->save($post);
        if ($post['printable'] == 1) {
            // save QRCode png
        }
        // msg
        $msg = Text::_('AUP_DETAILSSAVED');
        if (!$apply) {
            $this->redirect('index.php?option=com_userpoints&task=couponcodes', $msg);
        } else {
            $this->redirect('index.php?option=com_userpoints&task=editcoupon&cid[]=' . $id, $msg);
        }
        //JControllerLegacy::redirect();
    }

    function _save_coupongenerator() {
        $app = Factory::getApplication();
        $post = $app->input->post->getArray();
        $numbercouponcode = $app->input->get('numbercouponcode', 20, 'int');
        $numrandomchars = $app->input->get('numrandomchars', 0, 'int');
        $enabledincrement = intval($app->input->get('enabledincrement', 0, 'int'));

        if ($post['points']) {
            for ($i = 0, $n = $numbercouponcode; $i < $n; $i++) {
                $couponcode = $post['prefixcouponcode'];
                if ($numrandomchars) {
                    $couponcode .= $this->createRandomCode($numrandomchars);
                }
                if ($enabledincrement) {
                    $couponcode .= ($i + 1);
                }
                if ($couponcode) {
                    $row = new Coupon();
                    $row->couponcode = $couponcode;
                    $row->description = $post['description'];
                    $row->points = $post['points'];
                    $row->expires = $post['expires'];
                    $row->public = $post['public'];
                    $row->printable = $post['printable'];
                    $row->save();
                    if ($post['printable'] == 1) {
                        // save QRCode png
                    }
                }
            }
        }

        $msg = Text::_('AUP_DETAILSSAVED');

        $this->redirect('index.php?option=com_userpoints&task=couponcodes', $msg);
    }

    function _load_qrcodestats(int $id) {
        // Get the pagination request variables
        list($limitstart, $limit) = QRCodeTrack::getLimitsFromRequest();
        $total = QRCodeTrack::countByFieldvalue('couponid', $id);
        $result = QRCodeTrack::getLimitedRange($limitstart, $limit, 'couponid', $id);
        return array($result, $total, $limit, $limitstart);
    }

    function createRandomCode($n = 8) {

        $chars = "ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
        srand((double) microtime() * 1000000);
        $i = 0;
        $code = "";

        while ($i < $n) {
            $num = rand() % 33;
            $tmp = substr($chars, $num, 1);
            $code = $code . $tmp;
            $i++;
        }

        return $code;
    }

    function _print_coupon() {
        return new Coupon(Factory::getApplication()->input->get('id', 0, 'int'));
    }

    protected function createURLQRcodePNG($url = '', $width = '200', $path = '') {
        if (!$url) {
            return;
        }
        require_once JPATH_SITE . '/components/com_userpoints/assets/barcode/BarcodeQR.php';
        $qrcode = new BarcodeQR();
        $qrcode->url($url);
        $qrcode->draw($width, $path);
    }
}
