// Contract: LuminalUniverse
// Target function: function tokenURI(uint256 _tokenId) external view returns (string memory)
:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {
        require(
            ERC721.ownerOf(tokenId) == from,
            "ERC721: transfer of token that is not own"
        );
        require(to != address(0), "ERC721: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId);

        // Clear approvals from the previous owner
        _approve(address(0), tokenId);
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits a {Approval} event.
     */
    function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
    }

    /**
     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
     * The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param _data bytes optional data to send along with the call
     * @return bool whether the call correctly returned the expected magic value
     */
    function _checkOnERC721Received(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) private returns (bool) {
        if (to.isContract()) {
            try
                IERC721Receiver(to).onERC721Received(
                    _msgSender(),
                    from,
                    tokenId,
                    _data
                )
            returns (bytes4 retval) {
                return retval == IERC721Receiver.onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert(
                        "ERC721: transfer to non ERC721Receiver implementer"
                    );
                } else {
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting
     * and burning.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``s `tokenId` will be
     * transferred to `to`.
     * - When `from` is zero, `tokenId` will be minted for `to`.
     * - When `to` is zero, ``from``s `tokenId` will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {}
}

pragma solidity ^0.8.7;

/**
 * @dev This implements an optional extension of {ERC721} defined in the EIP that adds
 * enumerability of all the token ids in the contract as well as all token ids owned by each
 * account but rips out the core of the gas-wasting processing that comes from OpenZeppelin.
 */
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId)
        public
        view
        virtual
        override(IERC165, ERC721)
        returns (bool)
    {
        return
            interfaceId == type(IERC721Enumerable).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721Enumerable-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _owners.length;
    }

    /**
     * @dev See {IERC721Enumerable-tokenByIndex}.
     */
    function tokenByIndex(uint256 index)
        public
        view
        virtual
        override
        returns (uint256)
    {
        require(
            index < _owners.length,
            "ERC721Enumerable: global index out of bounds"
        );
        return index;
    }

    /**
     * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index)
        public
        view
        virtual
        override
        returns (uint256 tokenId)
    {
        require(
            index < balanceOf(owner),
            "ERC721Enumerable: owner index out of bounds"
        );

        uint count;
        for (uint i; i < _owners.length; i++) {
            if (owner == _owners[i]) {
                if (count == index) return i;
                else count++;
            }
        }

        revert("ERC721Enumerable: owner index out of bounds");
    }
}

// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)

pragma solidity ^0.8.0;

/**
 * @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 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 {
        _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);
    }
}

// OpenZeppelin Contracts v4.4.0 (utils/cryptography/MerkleProof.sol)

pragma solidity ^0.8.0;

/**
 * @dev These functions deal with verification of Merkle Trees proofs.
 *
 * The proofs can be generated using the JavaScript library
 * https://github.com/miguelmota/merkletreejs[merkletreejs].
 * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
 *
 * See `test/utils/cryptography/MerkleProof.test.js` for some examples.
 */
library MerkleProof {
    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     */
    function verify(
        bytes32[] memory proof,
        bytes32 root,
        bytes32 leaf
    ) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leafs & pre-images are assumed to be sorted.
     *
     * _Available since v4.4._
     */
    function processProof(bytes32[] memory proof, bytes32 leaf)
        internal
        pure
        returns (bytes32)
    {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            bytes32 proofElement = proof[i];
            if (computedHash <= proofElement) {
                // Hash(current computed hash + current element of the proof)
                computedHash = keccak256(
                    abi.encodePacked(computedHash, proofElement)
                );
            } else {
                // Hash(current element of the proof + current computed hash)
                computedHash = keccak256(
                    abi.encodePacked(proofElement, computedHash)
                );
            }
        }
        return computedHash;
    }
}

pragma solidity ^0.8.11;
pragma abicoder v2;

contract LuminalUniverse is ERC721Enumerable, Ownable {
    using MerkleProof for bytes32[];
    string public baseURI;

    mapping(address => bool) public whitelistAllowance;
    mapping(address => uint256)public  genesisFreeClaimed;
    mapping(address => uint256) public genesisAllowance;
    mapping(address => uint256) public publicAllowance;

    bytes32 public allowlistMerkleRoot;
    bytes32 public genesisMerkleRoot;

    bool public whitelistSaleIsActive;
    bool public genesisSaleIsActive;
    bool public publicSaleIsActive;

    uint public constant MAX_TOKENS = 1445;
    uint public constant MAX_TOKEN_PER_TXN = 2;
    uint public constant TOKEN_PRICE = 0.04 ether;

    uint public constant maxAllowListSupply = 1001;
    uint public constant maxGenesisSupply = 445;
    uint public allowListMinted = 0;
    uint public genesisClaimMinted = 0;

    modifier blockContracts() {
        require(tx.origin == msg.sender, "No smart contracts are allowed");
        _;
    }

    constructor() ERC721("Luminal Universe", "LUMINALUNIVERSE") {
        setAllowListRoot(
            0x3435f0bb641e0f7bce96bd6096693a5e349d7ed4f3afe056f686639b0ecdfbea
        );
        setGenesisRoot(
            0xfe4954196fa78174190adcdc10c6d6bac285a4a4edefbd1823c878e174512264
        );
        setBaseURI(
          "ipfs://QmfYtu5ASZnfYdghiJTqYYN3maCVpuJPrvJRHbu3ZbkvZL/"
        );
    }

    //withdraw function
    function withdraw() external onlyOwner {
        uint256 balance = address(this).balance;
        require(balance > 0, "Your balance is zero");
        address localOwner = payable(msg.sender);
        (bool ownerSuccess, ) = localOwner.call{value: balance}("");
        require(ownerSuccess, "Failed to send to Owner");
    }

    //setBaseURI
    function setBaseURI(string memory _baseURI) public onlyOwner {
        baseURI = _baseURI;
    }

    //flipWhitelistSale
    function flipWhiteListSaleState() external onlyOwner {
        whitelistSaleIsActive = !whitelistSaleIsActive;
    }

    //flipGenesisSale
    function flipGenesisSaleState() external onlyOwner {
        genesisSaleIsActive = !genesisSaleIsActive;
    }

    //flipPublicSale
    function flipPublicSaleState() external onlyOwner {
        publicSaleIsActive = !publicSaleIsActive;
    }

    //setAllowListRoot for allowlist
    function setAllowListRoot(bytes32 _root) public onlyOwner {
        allowlistMerkleRoot = _root;
    }

    //setGenesisRoot for genesis holder
    function setGenesisRoot(bytes32 _root) public onlyOwner {
        genesisMerkleRoot = _root;
    }

    //leaf for allowlist merkle root
    function _allowlistLeaf(address account) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(account));
    }

    //leaf for genesis merkle root
    function _genesisLeaf(address account, uint numberOfFreeClaims)
        internal
        pure
        returns (bytes32)
    {
        return keccak256(abi.encodePacked(account, numberOfFreeClaims));
    }

    //verify function for merkle root
    function _verify(
        bytes32 _leaf,
        bytes32[] memory _proof,
        bytes32 root
    ) internal pure returns (bool) {
        return MerkleProof.verify(_proof, root, _leaf);
    }

    //airdrop
    function airdrop(address _to, uint256 numberOfTokens) external onlyOwner {
        uint256 supply = totalSupply();
        require(
            supply + numberOfTokens < MAX_TOKENS,
            "Purchase would exceed the max supply"
        );
        for (uint256 i; i < numberOfTokens; i++) {
            _safeMint(_to, supply + i);
        }
    }

    //whitelistMint
    function whitelistMint(bytes32[] memory _proof)
        external
        payable
        blockContracts
    {
        uint supply = totalSupply();
        require(whitelistSaleIsActive, "Whitelist sale is not active");
        require(
            _verify(_allowlistLeaf(msg.sender), _proof, allowlistMerkleRoot),
            "You are not whitelisted"
        );
        require(
            !whitelistAllowance[msg.sender],
            "You can only mint one for WL"
        );
        require(allowListMinted + 1 < maxAllowListSupply, "Exceeds allowlist supply");
        require(msg.value == TOKEN_PRICE, "Ether sent is not correct");
        allowListMinted += 1;
        whitelistAllowance[msg.sender] = true;
        _mint(msg.sender, supply);
    }

    function genesisFreeClaim(
        uint _numberOfTokens,
        uint _numberOfFreeClaims,
        bytes32[] memory _proof
    ) external blockContracts {
        uint supply = totalSupply();
        require(
            whitelistSaleIsActive,
            "Free uinverse claim for genesis is not active"
        );
        require(
            _verify(
                _genesisLeaf(msg.sender, _numberOfFreeClaims),
                _proof,
                genesisMerkleRoot
            ),
            "You are not allowed to claim free universe"
        );
        require(
            genesisFreeClaimed[msg.sender] + _numberOfTokens <=
                _numberOfFreeClaims,
            "Exceeds claim allowance"
        );
        require(
            genesisClaimMinted + _numberOfTokens < maxGenesisSupply,
            "Claim would exceed max supply"
        );
        genesisClaimMinted += _numberOfTokens;
        genesisFreeClaimed[msg.sender] += _numberOfTokens;
        for (uint i; i < _numberOfTokens; i++) {
            _mint(msg.sender, supply + i);
        }
    }

    function genesisMint(
        uint _numberOfTokens,
        uint _numberOfFreeClaims,
        bytes32[] memory _proof
    ) external payable blockContracts {
        uint supply = totalSupply();
        require(
            genesisSaleIsActive,
            "Genesis sale to mint universe is not active"
        );
        require(
            _verify(
                _genesisLeaf(msg.sender, _numberOfFreeClaims),
                _proof,
                genesisMerkleRoot
            ),
            "You are not allowed to mint for Stage 2"
        );
        require(
            genesisAllowance[msg.sender] + _numberOfTokens <= MAX_TOKEN_PER_TXN,
            "Genesis holder can only mint 2 Universe per address"
        );
        require(
            supply + _numberOfTokens < MAX_TOKENS,
            "Purchase would exceed max supply"
        );
        require(
            msg.value == TOKEN_PRICE * _numberOfTokens,
            "Ether sent is not correct"
        );
        genesisAllowance[msg.sender] += _numberOfTokens;
        for (uint i; i < _numberOfTokens; i++) {
            _mint(msg.sender, supply + i);
        }
    }

    function publicMint(uint _numberOfTokens) external payable blockContracts {
        uint supply = totalSupply();
        require(
            publicSaleIsActive,
            "Public sale to mint uinverse is not active"
        );
        require(
            _numberOfTokens <= MAX_TOKEN_PER_TXN,
            "For public mint only 2 token per transaction are allowed"
        );
        require(
            publicAllowance[msg.sender] < MAX_TOKEN_PER_TXN,
            "You can only mint 2 max per wallet per address"
        );
        require(
            supply + _numberOfTokens < MAX_TOKENS,
            "Purchase would exceed max supply"
        );
        require(
            msg.value == TOKEN_PRICE * _numberOfTokens,
            "Ether sent is not correct"
        );
        publicAllowance[msg.sender] += _numberOfTokens;
        for (uint i; i < _numberOfTokens; i++) {
            _mint(msg.sender, supply + i);
        }
    }