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

// no direct access
defined('_JEXEC') or die('Restricted access');

use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use BlackSheepResearch\Component\UserPoints\Site\UserPoints;
use BlackSheepResearch\Component\UserPoints\Site\Problems\QRCodeTrack;
use BlackSheepResearch\Component\UserPoints\Site\Problems\SQL;

class Registerqrcode extends UserModel {

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

    function attribPoints() {
        $app = Factory::getApplication();
        $db = SQL::getInstance();

        $login = $app->input->get('login', '', 'username');
        $coupon = $app->input->get('couponCode', '', 'string');
        $trackID = $app->input->get('trackID', '', 'string');

        $idTrack = QRCodeTrack::withTrackid($trackID)->id;

        $q = "SELECT id FROM #__users WHERE `username` = {$db->quote($login)} AND `block`='0'";
        $db->setQuery($q);
        $userID = $db->loadResult();

        if ($userID) {
            $referrerid = UserPoints::getAnyUserReferreID($userID);

            $now = QRCodeTrack::datetimeSQL();

            $q = "SELECT * FROM #__alpha_userpoints_coupons WHERE `couponcode` = {$db->quote($coupon)} AND (`expires`>='$now' OR `expires`='1000-01-01 00:00:00')";
            $db->setQuery($q);
            $result = $db->loadObjectList();
            if ($result) {
                $resultCouponExist = 0;

                // check if public or private coupon
                if (!$result[0]->public) {
                    // private -> usable once per one user
                    $q = "SELECT count(*) FROM #__alpha_userpoints_details WHERE `keyreference`={$db->quote($coupon)} AND `enabled`='1'";
                    $db->setQuery($q);
                    $resultCouponExist = $db->loadResult();
                    if (!$resultCouponExist) {
                        // insert points
                        UserPoints::newpoints('sysplgup_couponpointscodes', $referrerid, $result[0]->couponcode, $result[0]->description, $result[0]->points);
                        //if ( UserPoints::newpoints( 'sysplgup_couponpointscodes', $referrerid, $result[0]->couponcode, $result[0]->description, $result[0]->points, true )===true ){
                        // insert confirmed in track table
                        $this->updateTableQRTrack($idTrack);
                        return $result[0]->points;
                        //}
                    } else {
                        $msg = (Text::_('AUP_THIS_COUPON_WAS_ALREADY_USED'));
                        $this->redirect('index.php?option=com_userpoints&view=registerqrcode&QRcode=' . $coupon . '&trackID=' . $trackID, $msg);
                    }
                } elseif ($result[0]->public) {
                    // public -> usable once per all users
                    $keyreference = $coupon . "##" . $userID;
                    $q = "SELECT count(*) FROM #__alpha_userpoints_details WHERE `keyreference` = {$db->quote($keyreference)} AND `enabled`='1'";
                    $db->setQuery($q);
                    $resultCouponExist = $db->loadResult();
                    if (!$resultCouponExist) {
                        // insert points
                        UserPoints::newpoints('sysplgup_couponpointscodes', $referrerid, $keyreference, $result[0]->description, $result[0]->points);
                        //if ( UserPoints::newpoints( 'sysplgup_couponpointscodes', $referrerid, $keyreference, $result[0]->description, $result[0]->points, true )===true ){
                        // insert confirmed in track table
                        $this->updateTableQRTrack($idTrack);
                        return $result[0]->points;
                        //}
                    } else {
                        $msg = (Text::_('AUP_THIS_COUPON_WAS_ALREADY_USED'));
                        $this->redirect('index.php?option=com_userpoints&view=registerqrcode&QRcode=' . $coupon . '&trackID=' . $trackID, $msg);
                    }
                }
            } else {
                $msg = (Text::_('AUP_COUPON_NOT_AVAILABLE'));
                $this->redirect('index.php?option=com_userpoints&view=registerqrcode&QRcode=' . $coupon . '&trackID=' . $trackID, $msg);
            }
        } else {
            // no username
            $msg = Text::_('AUP_ALERT_NOT_AUTH');
            $this->redirect('index.php?option=com_userpoints&view=registerqrcode&QRcode=' . $coupon . '&trackID=' . $trackID, $msg);
        }
    }

    function trackQRcode($trackID = '', $couponCode = '') {
        if (!$trackID || !$couponCode) {
            return;
        }

        $db = SQL::getInstance();

        //already inserted (e.g. error login)
        $alreadytrackid = QRCodeTrack::withTrackid($trackID)->trackid;
        if (!$alreadytrackid) {
            $now = QRCodeTrack::datetimeSQL();

            $q = "SELECT id FROM #__alpha_userpoints_coupons WHERE `couponcode` = {$db->quote($couponCode)} AND `printable`='1'";
            $db->setQuery($q);
            $couponID = $db->loadResult();

            $ip = IpHelper::getIp();
            $device = $_SERVER['HTTP_USER_AGENT'];

            $ipDetail = countryCityFromIP($ip);
            $country = $ipDetail['country'];
            $city = $ipDetail['city'];

            $row = new QRCodeTrack();
            $row->id = NULL;
            $row->couponid = $couponID;
            $row->trackid = $trackID;
            $row->trackdate = $now;
            $row->country = $country;
            $row->city = $city;
            $row->device = $device;
            $row->ip = $ip;
            $row->confirmed = 0;
            $row->save();
        }
    }

    function updateTableQRTrack(int $idTrack) {
        $row = new QRCodeTrack($idTrack);
        $row->confirmed = 1;
        $row->save();
    }

}
