// File: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: @openzeppelin/contracts/utils/Context.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

// File: contracts/DAXLicensing.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

// Import the subscription smart contract
import "./DAXLicensingERC20.sol";


contract DAXLicensing is DAXLicensingERC20 {

  uint256 public c = 0;

  constructor(){

  }

  // We use the "userPaid" modifier and we allow only users with valid subscriptions to call this function
  function increaseC() public userPaid {
      c++;
  }
}
// File: contracts/DAXLicensingERC20.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

import "@openzeppelin/contracts/access/Ownable.sol";

interface IERC20Token {
    function balanceOf(address account) external view returns (uint256);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
interface IDAXConfig {
    function getTokenAddress() external view returns (address);
    function getTokenDecimals() external view returns (uint256);
    function getBasePrice() external view returns (uint256);
    function BasePrice() external view returns (uint256);

}

// interface IDaxioCoreConfiguration {
//     function BasePrice() external view returns (uint256);
// }

// contract BasePriceGetter {
//     IDaxioCoreConfiguration private config;

//     function getBasePrice() public view returns (uint256) {
//         return config.BasePrice();
//     }
// }


abstract contract DAXLicensingERC20 is Ownable {

    IERC20Token public erc20Token;
    IDAXConfig public daxConfig;
    address public feeCollector;
    uint256 public multiplier;
    uint256 public BasePrice;

    /// @dev Struct for payments
    /// @param user Who made the payment
    /// @param paymentMoment When the last payment was made
    /// @param paymentExpire When the user needs to pay again
    struct Erc20Payment {
        address user; // Who made the payment
        uint256 paymentMoment; // When the last payment was made
        uint256 paymentExpire; // When the user needs to pay again
    }

    /// @dev Array of erc20 payments
    Erc20Payment[] public erc20Payments;

    /// @dev Link an EOA to an ERC20 payment
    mapping ( address => Erc20Payment ) public userPaymentErc20;

    /// @dev The subscription fee
    //uint256 public erc20Fee;

    /// @dev Variables for analytics
    uint256 public totalPaymentsErc20;
    mapping (address => uint256) public userTotalPaymentsErc20;

    /// @dev Events
    event UserPaidLicense(address indexed user, uint256 indexed fee, uint256 indexed period);

    /// @dev Errors
    error NotEOA();
    error SubscriptionNotPaid();
    error FailedErc20Transfer();

    /// @dev We transfer the ownership to a given owner
    constructor() {
        _transferOwnership(_msgSender());
        feeCollector = _msgSender();
    }

    /// @dev Modifier to check if user's subscription is still active
    modifier userPaid() {
        if(block.timestamp >= userPaymentErc20[msg.sender].paymentExpire) revert SubscriptionNotPaid();
        _;
    }

    /// @dev Function to pay the subscription
    /// @param _period For how many months the user wants to pay the subscription
    function paySubscription(uint256 _period) external payable virtual returns(bool) { 

        /// @dev Getting the fee and Token information
        uint256 erc20FeeNOW = daxConfig.getBasePrice() * multiplier;
        erc20Token = IERC20Token(daxConfig.getTokenAddress());
        
        if(erc20Token.transferFrom(msg.sender, address(this), _period * erc20FeeNOW) == false) revert FailedErc20Transfer();

        totalPaymentsErc20 = totalPaymentsErc20 + msg.value; // Compute total payments in Eth
        userTotalPaymentsErc20[msg.sender] = userTotalPaymentsErc20[msg.sender] + msg.value; // Compute user's total payments in Eth

        Erc20Payment memory newPayment = Erc20Payment(msg.sender, block.timestamp, block.timestamp + _period * 30 days);
        erc20Payments.push(newPayment); // Push the payment in the payments array
        userPaymentErc20[msg.sender] = newPayment; // User's last payment

        emit UserPaidLicense(msg.sender, erc20FeeNOW * _period, _period);

        return true;
    }

    /// @dev Set the monthly Erc20 fee
    // function setErc20Fee(uint256 _newErc20Fee) external virtual onlyOwner {
    //     erc20Fee = _newErc20Fee;
    // }

    ///@dev Set the multiplier
    function setMultiplier(uint256 _newMultiplier) external virtual onlyOwner {
        multiplier = _newMultiplier;
    }

    /// @dev Set the erc20 token for payments
    // function setErc20TokenForPayments(address _newErc20Token) external virtual onlyOwner {
    //     erc20Token = IERC20Token(_newErc20Token);
    // }

    /// @dev Set a new payment collector
    function setNewPaymentCollector(address _feeCollector) public virtual onlyOwner {
        feeCollector = _feeCollector;
    }

    /// @dev Set the DAXConfig contract
    function setDAXConfig(address _daxConfig) external virtual onlyOwner {
        daxConfig = IDAXConfig(_daxConfig);
    }

    /// @dev Withdraw erc20 tokens
    function withdrawErc20() external virtual onlyOwner {
        if(erc20Token.transferFrom(address(this), feeCollector, erc20Token.balanceOf(address(this))) == false) revert FailedErc20Transfer(); 
    }

    /// @dev Get the last payment of user in Erc20
    function lastPaymentOfUser(address _user) external view virtual returns(uint256) {
        return userPaymentErc20[_user].paymentMoment;
    }

    /// @dev Get the smart contract's balance of tokens
    function paymentsInSmartContract() external view virtual returns(uint256) {
        return erc20Token.balanceOf(address(this));
    } 
}