// File: @openzeppelin/contracts/token/ERC20/IERC20.sol


// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) external returns (bool);
}

// File: contracts/BTE_Contracts/BlogToEarnICO.sol


pragma solidity 0.8.7;


contract BlogToEarnICO {
    //Administration Details
    address public admin;
    address payable public ICOWallet;

    //Token
    IERC20 public token;
    IERC20 public usdt;

    //ICO Details
    uint256 public btePrice = 200000; //price in USDT (6 decimals)
    uint256 public raisedAmount;
    uint256 public bteSold;
    uint256 public minInvestment = 200000000;
    uint256 public maxInvestment = 5000000000000;
    uint256 public icoStartTime;
    uint256 public icoEndTime;

    //Investor
    mapping(address => uint256) public investedAmountOf;

    //ICO State
    enum State {
        BEFORE,
        RUNNING,
        END,
        HALTED
    }
    State public ICOState;

    //Events
    event Invest(
        address indexed from,
        address indexed to,
        uint256 value,
        uint256 tokens
    );
    event TokenWithdrawn(address to, uint256 amount, uint256 time);

    //Initialize Variables
    constructor(
        address payable _icoWallet,
        address _token,
        address _usdt
    ) {
        admin = msg.sender;
        ICOWallet = _icoWallet;
        token = IERC20(_token);
        usdt = IERC20(_usdt);
    }

    //Access Control
    modifier onlyAdmin() {
        require(msg.sender == admin, "Admin Only function");
        _;
    }

    // ICO FUNCTIONS

    //Get ICO State
    function getICOState() external view returns (string memory) {
        if (ICOState == State.BEFORE) {
            return "Not Started";
        } else if (ICOState == State.RUNNING) {
            return "Running";
        } else if (ICOState == State.END) {
            return "End";
        } else {
            return "Halted";
        }
    }

    // ADMIN FUNCTIONS

    //Start, Halt and End ICO
    function startICO() external onlyAdmin {
        require(ICOState == State.BEFORE, "ICO isn't in before state");

        icoStartTime = block.timestamp;
        icoEndTime = icoStartTime + (86400 * 60);
        ICOState = State.RUNNING;
    }

    function haltICO() external onlyAdmin {
        require(ICOState == State.RUNNING, "ICO isn't running yet");
        ICOState = State.HALTED;
    }

    function resumeICO() external onlyAdmin {
        require(ICOState == State.HALTED, "ICO State isn't halted yet");
        ICOState = State.RUNNING;
    }

    //Change ICO Wallet
    function changeICOWallet(address payable _newICOWallet) external onlyAdmin {
        ICOWallet = _newICOWallet;
    }

    //Change Admin
    function changeAdmin(address _newAdmin) external onlyAdmin {
        admin = _newAdmin;
    }

    /* User Function */

    //Invest
    function invest(uint256 _amount) public returns (bool) {
        require(ICOState == State.RUNNING, "ICO isn't running");
        uint256 amount = _amount * 1e18;
        uint256 totalPrice = _amount * btePrice;
        require(
            totalPrice >= minInvestment && totalPrice <= maxInvestment,
            "Check Min and Max Investment"
        );
        require(
            investedAmountOf[msg.sender] + totalPrice <= maxInvestment,
            "Investor reached maximum Investment Amount"
        );
        require(
            amount <= token.balanceOf(address(this)),
            "Not enough supply available to sell"
        );

        require(
            block.timestamp <= icoEndTime,
            "ICO already Reached Maximum time limit"
        );

        raisedAmount += totalPrice;
        bteSold += amount;
        investedAmountOf[msg.sender] += totalPrice;

        require(
            usdt.transferFrom(msg.sender, ICOWallet, totalPrice),
            "USDT transfer failed"
        );

        bool saleSuccess = token.transfer(msg.sender, amount);
        require(saleSuccess, "Failed to Invest");

        emit Invest(address(this), msg.sender, totalPrice, amount);
        return true;
    }

    //Withdraw remaining Tokens
    function withdrawTokens() external returns (bool) {
        require(ICOState == State.END, "ICO isn't over yet");

        uint256 remainingTokens = token.balanceOf(address(this));
        bool success = token.transfer(admin, remainingTokens);
        require(success, "Failed to withdraw remaining tokens");

        emit TokenWithdrawn(admin, remainingTokens, block.timestamp);
        return true;
    }

    //End ICO After reaching ICO Timelimit
    function endIco() public {
        require(ICOState == State.RUNNING, "ICO Should be in Running State");
        require(block.timestamp > icoEndTime, "ICO timelimit not reached");
        ICOState = State.END;
    }

    //Change ICO End time
    function changeIcoEndTime(uint256 _newTimestamp) external onlyAdmin {
        require(ICOState == State.RUNNING, "ICO isn't running yet");
        icoEndTime = _newTimestamp;
    }

    function changeBTEPrice(uint256 _newPrice) external onlyAdmin {
        require(ICOState == State.HALTED, "ICO isn't on halt yet");
        btePrice = _newPrice;
    }

    //Check ICO Contract Token Balance
    function getICOTokenBalance() external view returns (uint256) {
        return token.balanceOf(address(this));
    }

    //Check ICO Contract Investor Token Balance
    function investorBalanceOf(address _investor)
        external
        view
        returns (uint256)
    {
        return token.balanceOf(_investor);
    }

    // Check the BTE balance of ICO
    function IcoBteBalance() external view returns (uint256) {
        return token.balanceOf(address(this));
    }
}