// Contract: Emeejis
// Target function: function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool)
ity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    function _verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) private pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

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);
    }
}

library Strings {
    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0x00";
        }
        uint256 temp = value;
        uint256 length = 0;
        while (temp != 0) {
            length++;
            temp >>= 8;
        }
        return toHexString(value, length);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _HEX_SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }
}

// ******************************************************************************************************************************
// **************************************************  Start of Main Contract ***************************************************
// ******************************************************************************************************************************

contract Emeejis is IERC721, Ownable {

    using Address for address;
    using Strings for uint256;
    
    // Token name
    string private _name;
    // Token symbol
    string private _symbol;
    // URI Root Location for Json Files
    string private _baseURI;

    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;
    // Mapping owner address to token count
    mapping(address => uint256) private _balances;
    // Mapping from token ID to approved address
    mapping(uint256 => address) private _tokenApprovals;
    // Mapping from owner to operator approvals
    mapping(address => mapping(address => bool)) private _operatorApprovals;
    
    //Contract Specific Variables and Mappings
    uint256 public maximumTokens;       //The total number of NFTs to be minted
    uint256 private _reserveTokens;     //Number of tokens reserved for Owner Distribution
    uint256 public tokenPrice;          //Current Sales Price from Contract
    uint256 public purchaseLimit;       //Maximum mints per transaction
    uint256 public numberMinted;        //Total minted so far
    
    //Map user address to payout percentage
    mapping(address => uint256) private percPayout;
    mapping(address => uint256) private payoutAmount;
    address[] private payees;
    
    bool reentrancyLock;                //lockdown fucntions to prevent reentrant attacks
    bool orderLock;                     //Lockup the mint function when not in use

    constructor() {
        _name = "Emeejis";
        _symbol = "EMG";
        _baseURI = "https://emeejis.com/metadata.php?tokenID=";
        
        tokenPrice = 35 * 10 ** 15; // 35 finney or 0.035 ETH
        maximumTokens = 6666;
        _reserveTokens = 200;
        purchaseLimit = 20;
        orderLock = true;
        
        payees.push(0xD15e7ab216AdDB92Bd95d96cb5D0F3f43719C679);  //Jovan
        payees.push(0x7B2a2e3813b7906C4E6573C80Ff73824AB69a4f9);  //Korvis
        payees.push(0x72b5216bd6Ee23a6FfC50340263dc9f8606DFe49);  //Chief
        payees.push(0xC7f02456dD3FC26aAE2CA1d68528CF9764bf5598);  //Squeebo
        payees.push(0x2496286BDB820d40C402802F828ae265b244188A);  //OGG
        payees.push(0xD0A1258f1cf379CB798Eea6776D9855F0B02F49B);  //Community
        payees.push(0x3B4B9283E1049E504e7E76e0A5e5E05630c9Ccd2);  //Charities
		
		percPayout[payees[0]] = 20; //Jovan
		percPayout[payees[1]] = 40;  //Korvis
		percPayout[payees[2]] = 5;  //Chief
		percPayout[payees[3]] = 5;  //Squeebo
		percPayout[payees[4]] = 5;  //OGG
		percPayout[payees[5]] = 10; //community
		percPayout[payees[6]] = 15; //charities
				
    }

    function orderEmeejis(uint256 orderSize) public payable {
        require(msg.value >= orderSize * tokenPrice, "orderEmeejis: Insufficient Funds");
        require(orderSize <= purchaseLimit, "orderEmeejis: Order Size too big");
        require(orderSize < maximumTokens - _reserveTokens - numberMinted, "orderEmeejis: Not enough NFTs remaining to fill order");
        require(!orderLock, "currently closed for business");
        
        require(!reentrancyLock);  //Lock up this whole function just in case
        reentrancyLock = true;
        
        uint256 mintSeedValue = numberMinted; //Store the starting value of the mint batch
        numberMinted += orderSize;
        
        //Handle ETH transactions
        uint256 cashIn = msg.value;
        uint256 cashChange = cashIn - (orderSize * tokenPrice);
        //assign approvals for payouts
        approvePayouts(cashIn);
        
        //send tokens
        for(uint256 i = 0; i < orderSize; i++) {
            _safeMint(msg.sender, mintSeedValue + i);
        }
                
        if (cashChange > 0){
            (bool success, bytes memory data) = msg.sender.call{value: cashChange}("");
            require(success, "orderEmeejis: unable to send change to user");
        }
        reentrancyLock = false;
    }

    function giveawayEmeeji(address _to, uint256 numberToMint) public onlyOwner {
        require(_to != address(0), "giveawayEmeeji: Cannot Send to 0 address");
        require(numberToMint < maximumTokens - numberMinted, "giveawayEmeeji: Not enough Emeejis remaining");
        
        uint256 currentToken = numberMinted;
        for (uint256 i; i < numberToMint; i++) {
            numberMinted++;
            if (_reserveTokens > 0) {
                _reserveTokens --;
            }
            _safeMint(_to, currentToken + i);
        }
    }
    
    function checkMyWallet() view external returns (uint256) {
    	//allows approved team members to check their current payout amount
    	return payoutAmount[_msgSender()];
    }
    
    function checkWallet(address checkAddress) view external onlyOwner returns(uint256) {
        //Checks for funds available to a specific address
        //OwnerOnly for now, mostly for testing purposes
        return payoutAmount[checkAddress];
    }
    
    function approvePayouts(uint256 purchaseAmount) internal {
    	//transaction totals sent here to assign approvals to each account on file
    	for (uint256 i; i < payees.length; i++){
    		payoutAmount[payees[i]] += (purchaseAmount * percPayout[payees[i]]) / 100;
    	}
    }
    
    function withdraw() external {
    	//payout approved amount to sender.
    	uint256 payout = payoutAmount[_msgSender()];
    	payoutAmount[_msgSender()] = 0;
    	
        (bool success, bytes memory data) = msg.sender.call{value: payout}("");
        require(success, "Withdraw: Could not transact funds");
    }

    // ************************************ Setters and Getters
    
    function lockOrders() external onlyOwner {
        orderLock = true;
    }
    
    function unlockOrders() external onlyOwner {
        orderLock = false;
    }

    function setTokenPrice(uint256 amount) public onlyOwner {
        tokenPrice = amount;
    }
    
    function setPurchaseLimit(uint256 amount) public onlyOwner {
        purchaseLimit = amount;
    }
    
    function setBaseURI(string memory uri_) public onlyOwner {
        _baseURI = uri_;
    }
    
    function setReserveTokens(uint amount) public onlyOwner {
        _reserveTokens = amount;
    }
    
    function setTotalTokens(uint256 numTokens) public onlyOwner {
        maximumTokens = numTokens;
    }
    
    function tokensRemaining() public view returns (uint256) {
        return maximumTokens - numberMinted;
    }
    
    function checkOrderLock() public view returns (bool) {
        return orderLock;
    }
    
    function checkReserves() public view returns (uint256) {
        return _reserveTokens;
    }

    // ***********************************************************************************************************************
    // **********************************************  ERC721 Standard Calls  ************************************************
    // ***********************************************************************************************************************