contract GlobalGoats is ERC721Enumerable, Ownable {

    using SafeMath for uint256;
    using Strings for uint256;

    uint256 public constant collection_Supply = 2323;

    uint256 public constant MAX_PURCHASE = 20;

    uint256 public constant MAX_MintedForPromotion = 25;

    uint256 public goatsMintedForPromotion;

    uint256 public preSaleGoatsMinted;

    uint256 public constant MAX_MintedGoldenGoats = 100;

    uint256 public constant MAX_PreSaleMintedGoats = 350;

    uint256 public constant PRICE_PER_GOAT = 150000000000000000 wei;  //0.15 ETH

    uint256 public constant PreSale_PRICE_PER_GOAT = 110000000000000000 wei;  //0.11 ETH

    bool private _saleIsActive;

    mapping(uint256 => uint256) private _tokenPriceWei;

    mapping (uint256 => address) private _tokenListOwner;

    bool private _preSaleIsActive;

    string private _metaBaseUri = "https://assets.globalgoats.io/";


//Index of Golden Goats
    uint[] GoldenGoats = [283, 107, 44, 344, 9, 23, 40, 218, 349, 165, 74, 2, 19, 227, 215, 315, 4, 303, 237, 209, 27, 199, 336, 256, 280, 312, 7, 317, 89, 169, 37, 204, 144, 133, 342, 156, 201, 196, 101, 164, 265, 275, 173, 228, 79, 277, 41, 292, 230, 337, 1619, 480, 1551, 1400, 1678, 1658, 2222, 1461, 2323, 2125, 981, 1639, 712, 1230, 1645, 1083, 976, 2244, 939, 786, 1223, 2022, 585, 2261, 926, 1985, 893, 1571, 1098, 792, 1944, 1754, 1352, 821, 1771, 931, 2018, 432, 1901, 1919, 867, 1295, 1697, 667, 2175, 1926, 1100, 1166, 1978, 2085];

    uint[] getOnSale;
    //Alternative Option 
    struct GoldenGoat {
        address userAddress;
        uint tokenId;
    }
    

    constructor() ERC721("GlobalGoats", "GOAT") {

        _saleIsActive = true;
        _preSaleIsActive = true;
        goatsMintedForPromotion = 0;
    }

    //public mint
    function mint(uint16 numberOfTokens) public payable {
        require(saleIsActive(), "Sale is not active");
        require(numberOfTokens <= MAX_PURCHASE, "Can only mint max 20 tokens per transaction");
        require(PRICE_PER_GOAT.mul(numberOfTokens) == msg.value, "Ether value sent is incorrect.Need 0.15 ETH for each GOAT");
        require(totalSupply() < collection_Supply, "collection sold out");
        require(totalSupply().add(numberOfTokens) < collection_Supply, "Insufficient supply");

        _mintTokens(numberOfTokens,msg.sender);

    }

    //Pre-Sale Mint
    function preSalemint(uint16 numberOfTokens) public payable {
        require(saleIsActive(), "Sale is not active");
        require(numberOfTokens <= MAX_PURCHASE, "Can only mint max 20 tokens per transaction");
        require(preSaleGoatsMinted.add(numberOfTokens) <= MAX_PreSaleMintedGoats, "Cannot mint more Pre-sale mintgoats for promotion");
        require(PreSale_PRICE_PER_GOAT.mul(numberOfTokens) == msg.value, "Ether value sent is incorrect.Need 0.11 ETH For Presale for each GOAT");
        require(totalSupply().add(numberOfTokens) < collection_Supply, "Insufficient supply");
        preSaleGoatsMinted += numberOfTokens;

        _mintTokens(numberOfTokens,msg.sender);

    }


    /* Owner functions */

    /**
     * Reserve a few Goats e.g. for giveaways
     */
    function reserveMint(uint16 numberOfTokens , address _to) external onlyOwner {
        require(goatsMintedForPromotion.add(numberOfTokens) <= MAX_MintedForPromotion, "Cannot mint more goats for promotion");
        require(totalSupply().add(numberOfTokens) < collection_Supply, "Insufficient supply");
        goatsMintedForPromotion += numberOfTokens;
        _mintTokens(numberOfTokens,_to);
    }

    
    function setSaleIsActive(bool active) external onlyOwner {
        _saleIsActive = active;
    }

    function setPreSaleIsActive(bool active) external onlyOwner {
        _preSaleIsActive = active;
    }


    function setMetaBaseURI(string memory baseURI) external onlyOwner {
        _metaBaseUri = baseURI;
    }

    function withdraw(uint256 amount) external onlyOwner {
        require(amount <= address(this).balance, 'Insufficient balance');
        payable(msg.sender).transfer(amount);
    }

    function withdrawAll() external onlyOwner {
        payable(msg.sender).transfer(address(this).balance);
    }

    /* View functions */
    function saleIsActive() public view returns(bool) {
        return _saleIsActive;
    }

    function presaleIsActive() public view returns(bool) {
        return _preSaleIsActive;
    }
    //get array of golden goats TokenIds
    function _getGGTokens() external view returns(uint[] memory) {

        uint[] memory goats = new uint[](GoldenGoats.length);
        
        for (uint j = 0; j < GoldenGoats.length; j++) {
        
            goats[j] = GoldenGoats[j];
        }

        return goats;
    }


 function _getOnSalePlatformTokens() external view returns(uint[] memory) {

        uint[] memory goats = new uint[](getOnSale.length);
        uint256 tokenId;

        for (uint j = 0; j < getOnSale.length; j++) {
            tokenId = getOnSale[j];
        if (_exists(tokenId)) {
        address listowneraddress = _tokenListOwner[tokenId];
        address currentOnweraddress = ownerOf(tokenId);

         if( listowneraddress == currentOnweraddress) {   // if else statement
         goats[j] = getOnSale[j];
         } 
        }
        }

        return goats;
    }


    function IsGGToken(uint256 tokenId) public view returns(bool status) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
        status = false;
        for (uint l = 0; l < GoldenGoats.length; l++) {
            
            if (GoldenGoats[l] == tokenId) {
                status = true;
                break;
            }
        }
         return status;

    }

 function IsonSaleToken(uint256 tokenId) public view returns(bool status) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
        status = false;
        for (uint k = 0; k < getOnSale.length; k++) {
            if (getOnSale[k] == tokenId) {
                status = true;
                break;
            }
        }
        return status;

    }


    function getCurrentPriceOfToken(uint256 tokenId) public view virtual returns(uint256) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
        require(_tokenListOwner[tokenId] == ownerOf(tokenId) , "Not For Sale Currently on GlobalGoats.io");
        uint256 Price = _tokenPriceWei[tokenId];

        return Price;
    }

    function tokenURI(uint256 tokenId) override public view returns(string memory) {
        require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
        return string(abi.encodePacked(_baseURI(), "tokens/", uint256(tokenId).toString(), "/metadata.json"));
    }

    /* Internal functions */
    function _mintTokens(uint16 numberOfTokens , address _to) internal {
        for (uint16 i = 0; i < numberOfTokens; i++) {
            uint256 tokenId = totalSupply() + 1;
            //uint256 tokenId = _tokenIdTracker.current();
            _safeMint(_to, tokenId);
        }
    }


    function approve(uint256 _tokenId, address _from) internal virtual {
        require(ownerOf(_tokenId) == msg.sender, "NOT OWNER");
        isApprovedForAll(_from, address(this));
    }


    //send Price in wei
    function _setTokenPrice(uint256 tokenId, uint256 tokenPrice) external  {
        require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");

        _tokenPriceWei[tokenId] = tokenPrice;
        getOnSale.push(tokenId);
        _tokenListOwner[tokenId] = msg.sender;
        approve(tokenId, msg.sender);

    }

    /* Only for Global Goats Platform */
    function transfergg(uint256 tokenId) external payable{
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
        require(msg.value > 0, "Price must be greater than zero");
        require(_tokenListOwner[tokenId] == ownerOf(tokenId) , "Not For Sale Currently on GlobalGoats.io");
        uint256 amountReceived = (msg.value * 1000000000000000000);

        require(amountReceived >= _tokenPriceWei[tokenId], "Invalid amount sent up");
    
        uint256 Platformpercentage = 8;

        //Give royalties to original contract owner
        uint256 ownerCut = (msg.value * Platformpercentage) / 100;
        
        address owner = owner();
        payable(owner).transfer(ownerCut);

        //Give royalties to NPort (2%)
        uint256 nportCut = (msg.value * 2) / 100;

        //token Current Owner
        address tokencurrentOwner = ownerOf(tokenId);

        //send royalty to 100 GG 
        uint256 ggtokenId;
        //divide nportcut by GG Lengths
        uint pricepergoat = nportCut / GoldenGoats.length;
        if (GoldenGoats.length > 0) {
            for (uint j = 0; j < GoldenGoats.length; j++) {
                ggtokenId = GoldenGoats[j];
                if (_exists(ggtokenId)) {
                   address GGtokenowner = ownerOf(ggtokenId);
                    payable(GGtokenowner).transfer(pricepergoat);
                }
            }
        }

        //Give current owner the rest
        payable(tokencurrentOwner).transfer(msg.value - ownerCut - nportCut);
        _transfer(tokencurrentOwner, msg.sender, tokenId);
        _tokenPriceWei[tokenId] = 0;

        if (getOnSale.length > 0) {
            for (uint j = 0; j < getOnSale.length; j++) {
                ggtokenId = getOnSale[j];
                if (ggtokenId == tokenId) {
                    delete getOnSale[j];
                }
            }
        }
    }


    function _baseURI() override internal view returns(string memory) {
        return _metaBaseUri;
    }

}
//Global Goats Main Contract
function _mintTokens(uint16 numberOfTokens , address _to) internal {
    for (uint16 i = 0; i < numberOfTokens; i++) {
        uint256 tokenId = totalSupply() + 1;
        //uint256 tokenId = _tokenIdTracker.current();
        _safeMint(_to, tokenId);
    }
}

/* Internal functions */