// Contract: RadioactiveFuturePunks
// Target function: function isValidSignature(address _address, bytes memory signature) public view returns (bool)
 {
            _removeTokenFromOwnerEnumeration(from, tokenId);
        }
        if (to == address(0)) {
            _removeTokenFromAllTokensEnumeration(tokenId);
        } else if (to != from) {
            _addTokenToOwnerEnumeration(to, tokenId);
        }
    }

    /**
     * @dev Private function to add a token to this extension's ownership-tracking data structures.
     * @param to address representing the new owner of the given token ID
     * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
     */
    function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
        uint256 length = ERC721.balanceOf(to);
        _ownedTokens[to][length] = tokenId;
        _ownedTokensIndex[tokenId] = length;
    }

    /**
     * @dev Private function to add a token to this extension's token tracking data structures.
     * @param tokenId uint256 ID of the token to be added to the tokens list
     */
    function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
        _allTokensIndex[tokenId] = _allTokens.length;
        _allTokens.push(tokenId);
    }

    /**
     * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
     * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
     * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
     * This has O(1) time complexity, but alters the order of the _ownedTokens array.
     * @param from address representing the previous owner of the given token ID
     * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
     */
    function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
        // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
        uint256 tokenIndex = _ownedTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary
        if (tokenIndex != lastTokenIndex) {
            uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];

            _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
            _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
        }

        // This also deletes the contents at the last position of the array
        delete _ownedTokensIndex[tokenId];
        delete _ownedTokens[from][lastTokenIndex];
    }

    /**
     * @dev Private function to remove a token from this extension's token tracking data structures.
     * This has O(1) time complexity, but alters the order of the _allTokens array.
     * @param tokenId uint256 ID of the token to be removed from the tokens list
     */
    function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
        // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = _allTokens.length - 1;
        uint256 tokenIndex = _allTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
        // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
        // an 'if' statement (like in _removeTokenFromOwnerEnumeration)
        uint256 lastTokenId = _allTokens[lastTokenIndex];

        _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
        _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index

        // This also deletes the contents at the last position of the array
        delete _allTokensIndex[tokenId];
        _allTokens.pop();
    }
}

/**
 * @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() {
        _setOwner(_msgSender());
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        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 {
        _setOwner(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");
        _setOwner(newOwner);
    }

    function _setOwner(address newOwner) private {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}

/**
* 
* ______          _ _                  _   _          ______     _                 ______            _        
* | ___ \        | (_)                | | (_)         |  ___|   | |                | ___ \          | |       
* | |_/ /__ _  __| |_  ___   __ _  ___| |_ ___   _____| |_ _   _| |_ _   _ _ __ ___| |_/ /   _ _ __ | | _____ 
* |    // _` |/ _` | |/ _ \ / _` |/ __| __| \ \ / / _ \  _| | | | __| | | | '__/ _ \  __/ | | | '_ \| |/ / __|
* | |\ \ (_| | (_| | | (_) | (_| | (__| |_| |\ V /  __/ | | |_| | |_| |_| | | |  __/ |  | |_| | | | |   <\__ \
* \_| \_\__,_|\__,_|_|\___/ \__,_|\___|\__|_| \_/ \___\_|  \__,_|\__|\__,_|_|  \___\_|   \__,_|_| |_|_|\_\___/
*                                                                                                             
*                                                                                                         
**/
                                                          
contract RadioactiveFuturePunks is ERC721Enumerable, Ownable, ReentrancyGuard { 
    using Strings for uint256;

    /** 
    * variables definitions 
    **/

    // 8888 unique Punks
    uint256 public constant MAX_NFT_SUPPLY = 8888; 

    // max amount of Punks that can be minted at once
    uint256 public maxPurchase = 20;

    // number of reserved Punks in total; 
    uint256 public remainingReserveTokens = 1000; 

    // Control Wallets
    address private constant AKWallet = 0x6cAc11381fc6C517cb0287a1CCD342ECD4c2e043; 
    address private constant RMWallet = 0xd54712C47B11EE4D4B85Be6bf5067d1093eD5716; 
    address private signerAddress = 0x4B1274E16226c6DD187b77Ee08390F8eB3Bc6227; 

    // Price per Punk
    uint256 public tokenPrice = 77700000000000000; // 0.0777 ETH 

    // number of tokens an address can buy during each presale phase 
    uint256 public presaleLimit = 5;

    // Allows to lock any further metada changes
    bool public metadataLocked = false;

    // Controls minting state
    bool public saleIsActive = false;

    // denotes the current salePhase
    uint8 public salePhase = 0;

    // mapping to keep count of how many tokens an address has bought during each phase
    mapping(address => uint256) public _firstPresaleCounter;
    mapping(address => uint256) public _secondPresaleCounter;

    // counter for the current token id - starts at 1
    uint256 public _currentTokenId = 1;

    // whether the tokenURI link needs ".json" after the tokenId
    bool internal tokenURIDotJson = true;
    
    /** 
    /* Funtions 
    **/
    constructor() ERC721("Radioactive Future Punks", "RFPA") {} 

    function mintFuturePunks(uint256 numberOfTokens, bytes memory sig) external payable {
        require(saleIsActive, "Sale must be active to mint");
        require(salePhase != 0, "no sale phase is active");
        require(numberOfTokens > 0 && numberOfTokens <= maxPurchase, "Not within the range of maxPurchase");
        require((totalSupply() + numberOfTokens) <= MAX_NFT_SUPPLY - remainingReserveTokens, "Purchase would exceed max supply of FuturePunks");
        require(msg.value >= tokenPrice * numberOfTokens, "Ether value sent is not correct");

        if (salePhase == 1) {
            require(isValidSignature(_msgSender(), sig), "wallet not whitelisted");
            require(_firstPresaleCounter[msg.sender] + numberOfTokens <= presaleLimit, "max NFT per address exceeded");
        } else if (salePhase == 2) {
            require(isValidSignature(_msgSender(), sig), "wallet not whitelisted");
            require(_secondPresaleCounter[msg.sender] + numberOfTokens <= presaleLimit, "max NFT per address exceeded");
        }

        for (uint256 i = 0; i < numberOfTokens; i++) {
            _safeMint(msg.sender, _currentTokenId++);
        }

        if (salePhase == 1) {
            _firstPresaleCounter[msg.sender] += numberOfTokens;
        } else if (salePhase == 2) {
            _secondPresaleCounter[msg.sender] += numberOfTokens;
        }
    }

    function tokensOfOwner(address _owner) external view returns (uint256[] memory ) {
        uint256 tokenCount = balanceOf(_owner);
        if (tokenCount == 0) {
            // Return an empty array
            return new uint256[](0);
        } else {
            uint256[] memory result = new uint256[](tokenCount);
            uint256 index;
            for (index = 0; index < tokenCount; index++) {
                result[index] = tokenOfOwnerByIndex(_owner, index);
            }
            return result;
        }
    }

    function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
        if (tokenURIDotJson == true) {
            return string(abi.encodePacked(baseURI(), _tokenId.toString(), ".json"));
        } else {
            return string(abi.encodePacked(baseURI(), _tokenId.toString()));
        }
    }

    /** 
    * modifiers 
    **/

    modifier onlyRM() {
        require(RMWallet == _msgSender(), "caller is not RM");
        _;
    }

    modifier onlyAK() {
        require(AKWallet == _msgSender(), "caller is not AK");
        _;
    }

    /** 
    * onlyOwner Functions 
    **/


    // change token price
    function changeTokenPrice(uint256 newPrice) external onlyOwner {
        tokenPrice = newPrice;
    }

    function nextSalePhase() external onlyOwner {
        require(salePhase < 3, "The last phase is already active!");
        salePhase++;
    }

    // change the amount of tokens you can mint during the first presale
    function changePresaleLimit(uint256 amount) external onlyOwner {
        presaleLimit = amount;
    }


    // change the amount of tokens users can buy at once
    function changeMaxPurchase(uint256 amount) external onlyOwner {
        maxPurchase = amount;
    }

    // set baseURI
    function setBaseURI(string memory baseURI) external onlyOwner {
        require(metadataLocked != true, "Metadata has already been locked and cannot be changed anymore!");
        _setBaseURI(baseURI);
    }

    // switches between using and not using the ".json" extension
    function switchDotJson() external onlyOwner {
        require(metadataLocked != true, "Metadata has already been locked and cannot be changed anymore!");
        tokenURIDotJson = !tokenURIDotJson;
    }

    // flip minting switch
    function flipSaleIsActive() external onlyOwner {
        saleIsActive = !saleIsActive;
    }

    function burnThatPunk(uint256 tokenId) public virtual {
		require(_isApprovedOrOwner(_msgSender(), tokenId), "caller is not owner nor approved");
		_burn(tokenId);
	}
    
    function lockMetadata() external onlyOwner {
        require(metadataLocked != true, "FuturePunks: You've already locked the metadata!");
        metadataLocked = true;
    }

    function setSignerAddress(address _newSignerAddress) public onlyOwner { 
        signerAddress = _newSignerAddress;
    }

    /**
    *   onlyRM functions
    **/   

    // RM withdraw function
    function withdrawToAK(uint256 amount) external onlyRM {
        require(amount <= address(this).balance, "Withdrawal amount exceeds contract ballance");
        payable(AKWallet).transfer(amount);
    }

    /**
    *   onlyAK functions
    **/   

    // Mint from the reserves
    function mintReserves(address _to, uint256 amount) external onlyAK {
        require(remainingReserveTokens > 0, "All the reserve tokens have been minted already!");
        require(remainingReserveTokens - amount >= 0, "Amount would exceed the number of reserve tokens");
        require(totalSupply() + amount <= MAX_NFT_SUPPLY, "Amount would exceed max supply of FuturePunks");
        for (uint256 i = 0; i < amount; i++) {
            _safeMint(_to, _currentTokenId++);
        }
        remainingReserveTokens -= amount;
    }

    // AK withdraw function
    function withdrawToRM(uint256 amount) external onlyAK {
        require(amount <= address(this).balance, "Withdrawal amount exceeds contract ballance");
        payable(RMWallet).transfer(amount);
    }