// Contract: Lizoge
// Target function: function REL() public onlyOwner
 public marketingBalance;

    //Mapping of the already paid out(or missed) shares of each staker
    mapping(address => uint256) private alreadyPaidShares;
    //Mapping of shares that are reserved for payout
    mapping(address => uint256) private toBePaid;

    //Contract, uniswapv2 and burnAddress are excluded, other addresses like CEX
    //can be manually excluded, excluded list is limited to 30 entries to avoid a
    //out of gas exeption during sells
    function isExcludedFromStaking(address addr) public view returns (bool){
        return _excludedFromStaking.contains(addr);
    }

    //Check if address is blacklisted
    function isBlacklisted(address addr) public view returns (bool){
        return _isBlacklisted.contains(addr);
    }
    //Total shares equals circulating supply minus excluded Balances
    function _getTotalShares() public view returns (uint256){
        uint256 shares=_circulatingSupply;
        //substracts all excluded from shares, excluded list is limited to 30
        // to avoid creating a Honeypot through OutOfGas exeption
        for(uint i=0; i<_excludedFromStaking.length(); i++){
            shares-=_balances[_excludedFromStaking.at(i)];
        }
        return shares;
    }

    //adds Token to balances, adds new ETH to the toBePaid mapping and resets staking
    function _addToken(address addr, uint256 amount) private {
        //the amount of token after transfer
        uint256 newAmount=_balances[addr]+amount;
        
        if(isExcludedFromStaking(addr)){
           _balances[addr]=newAmount;
           return;
        }
        
        //gets the payout before the change
        uint256 payment=_newDividentsOf(addr);
        //resets dividents to 0 for newAmount
        alreadyPaidShares[addr] = profitPerShare * newAmount;
        //adds dividents to the toBePaid mapping
        toBePaid[addr]+=payment; 
        //sets newBalance
        _balances[addr]=newAmount;
    }
    
    
    //removes Token, adds ETH to the toBePaid mapping and resets staking
    function _removeToken(address addr, uint256 amount) private {
        //the amount of token after transfer
        uint256 newAmount=_balances[addr]-amount;
        
        if(isExcludedFromStaking(addr)){
           _balances[addr]=newAmount;
           return;
        }
        
        //gets the payout before the change
        uint256 payment=_newDividentsOf(addr);
        //sets newBalance
        _balances[addr]=newAmount;
        //resets dividents to 0 for newAmount
        alreadyPaidShares[addr] = profitPerShare * newAmount;
        //adds dividents to the toBePaid mapping
        toBePaid[addr]+=payment; 
    }
    
    
    //gets the not dividents of a staker that aren't in the toBePaid mapping 
    //returns wrong value for excluded accounts
    function _newDividentsOf(address staker) private view returns (uint256) {
        uint256 fullPayout = profitPerShare * _balances[staker];
        // if theres an overflow for some unexpected reason, return 0, instead of 
        // an exeption to still make trades possible
        if(fullPayout<alreadyPaidShares[staker]) return 0;
        return (fullPayout - alreadyPaidShares[staker]) / DistributionMultiplier;
    }

    //distributes eth between marketing share and dividents 
    function _distributeStake(uint256 ETHamount) private {
        // Deduct marketing Tax
        uint256 marketingSplit = (ETHamount * marketingShare) / 100;
        uint256 amount = ETHamount - marketingSplit;

       marketingBalance+=marketingSplit;
       
        if (amount > 0) {
            totalStakingReward += amount;
            uint256 totalShares=_getTotalShares();
            //when there are 0 shares, add everything to marketing budget
            if (totalShares == 0) {
                marketingBalance += amount;
            }else{
                //Increases profit per share based on current total shares
                profitPerShare += ((amount * DistributionMultiplier) / totalShares);
            }
        }
    }
    event OnWithdrawETH(uint256 amount, address recipient);
    
    //withdraws all dividents of address
    function claimETH(address addr) private{
        require(!_isWithdrawing);
        _isWithdrawing=true;
        uint256 amount;
        if(isExcludedFromStaking(addr)){
            //if excluded just withdraw remaining toBePaid ETH
            amount=toBePaid[addr];
            toBePaid[addr]=0;
        }
        else{
            uint256 newAmount=_newDividentsOf(addr);
            //sets payout mapping to current amount
            alreadyPaidShares[addr] = profitPerShare * _balances[addr];
            //the amount to be paid 
            amount=toBePaid[addr]+newAmount;
            toBePaid[addr]=0;
        }
        if(amount==0){//no withdraw if 0 amount
            _isWithdrawing=false;
            return;
        }
        totalPayouts+=amount;
        address[] memory path = new address[](2);
        path[0] = _uniswapv2Router.WETH(); //ETH
        path[1] = 0x4Fabb145d64652a948d72533023f6E7A623C7C53; //BUSD Rewards - Option to enable.

        _uniswapv2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}(
        0,
        path,
        addr,
        block.timestamp);
        
        emit OnWithdrawETH(amount, addr);
        _isWithdrawing=false;
    }

    //Swap Contract Tokens//////////////////////////////////////////////////////////////////////////////////



    //tracks auto generated ETH, useful for ticker etc
    uint256 public totalLPETH;
    //Locks the swap if already swapping
    bool private _isSwappingContractModifier;
    modifier lockTheSwap {
        _isSwappingContractModifier = true;
        _;
        _isSwappingContractModifier = false;
    }
    uint256 currentAmountToSwap = 400000 * 10**_decimals;  // 400,000 tokens (0.4%)
    //swaps the token on the contract for Marketing ETH and LP Token.
    //always swaps the sellLimit of token to avoid a large price impact
    function _swapContractToken() private lockTheSwap{
        uint256 contractBalance=_balances[address(this)];
        uint16 totalTax=_liquidityTax+_stakingTax;
        uint256 tokenToSwap = currentAmountToSwap;
        //only swap if contractBalance is larger than tokenToSwap, and totalTax is unequal to 0
        if(contractBalance<tokenToSwap||totalTax==0){
            return;
        }
        //splits the token in TokenForLiquidity and tokenForMarketing
        uint256 tokenForLiquidity=(tokenToSwap*_liquidityTax)/totalTax;
        uint256 tokenForMarketing= tokenToSwap-tokenForLiquidity;

        //splits tokenForLiquidity in 2 halves
        uint256 liqToken=tokenForLiquidity/2;
        uint256 liqETHToken=tokenForLiquidity-liqToken;

        //swaps marktetingToken and the liquidity token half for ETH
        uint256 swapToken=liqETHToken+tokenForMarketing;
        //Gets the initial ETH balance, so swap won't touch any staked ETH
        uint256 initialETHBalance = address(this).balance;
        _swapTokenForETH(swapToken);
        uint256 newETH=(address(this).balance - initialETHBalance);
        //calculates the amount of ETH belonging to the LP-Pair and converts them to LP
        uint256 liqETH = (newETH*liqETHToken)/swapToken;
        _addLiquidity(liqToken, liqETH);
        //Get the ETH balance after LP generation to get the
        //exact amount of token left for Staking
        uint256 distributeETH=(address(this).balance - initialETHBalance);
        //distributes remaining ETH between stakers and Marketing
        _distributeStake(distributeETH);
    }
    //swaps tokens on the contract for ETH
    function _swapTokenForETH(uint256 amount) private {
        _approve(address(this), address(_uniswapv2Router), amount);
        address[] memory path = new address[](2);
        path[0] = address(this);
        path[1] = _uniswapv2Router.WETH();

        _uniswapv2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
            amount,
            0,
            path,
            address(this),
            block.timestamp
        );
    }
    //Adds Liquidity directly to the contract where LP are locked(unlike safemoon forks, that transfer it to the owner)
    function _addLiquidity(uint256 tokenamount, uint256 ethamount) private {
        totalLPETH+=ethamount;
        _approve(address(this), address(_uniswapv2Router), tokenamount);
        _uniswapv2Router.addLiquidityETH{value: ethamount}(
            address(this),
            tokenamount,
            0,
            0,
            address(this),
            block.timestamp
        );
    }

    //public functions /////////////////////////////////////////////////////////////////////////////////////

    function getLiquidityReleaseTimeInSeconds() public view returns (uint256){
        if(block.timestamp<_liquidityUnlockTime){
            return _liquidityUnlockTime-block.timestamp;
        }
        return 0;
    }

    function getBurnedTokens() public view returns(uint256){
        return (InitialSupply-_circulatingSupply)/10**_decimals;
    }

    function getLimits() public view returns(uint256 balance, uint256 sell){
        return(balanceLimit/10**_decimals, sellLimit/10**_decimals);
    }

    function getTaxes() public view returns(uint256 burnTax,uint256 liquidityTax,uint256 marketingTax, uint256 buyTax, uint256 sellTax, uint256 transferTax){
        return (_burnTax,_liquidityTax,_stakingTax,_buyTax,_sellTax,_transferTax);
    }

    //How long is a given address still locked from selling
    function getAddressSellLockTimeInSeconds(address AddressToCheck) public view returns (uint256){
       uint256 lockTime=_sellLock[AddressToCheck];
       if(lockTime<=block.timestamp)
       {
           return 0;
       }
       return lockTime-block.timestamp;
    }
    function getSellLockTimeInSeconds() public view returns(uint256){
        return sellLockTime;
    }
    
    function getcurrentAmountToSwap() public view returns (uint256){
          return currentAmountToSwap;
    }

    //How long is a given address still locked from buying
    function getAddressBuyLockTimeInSeconds(address AddressToCheck) public view returns (uint256){
       uint256 lockTime=_buyLock[AddressToCheck];
       if(lockTime<=block.timestamp)
       {
           return 0;
       }
       return lockTime-block.timestamp;
    }
    function getBuyLockTimeInSeconds() public view returns(uint256){
        return buyLockTime;
    }
    
    //Functions every wallet can call
    //Resets sell lock of caller to the default sellLockTime should something go very wrong
    function AddressResetSellLock() public{
        _sellLock[msg.sender]=block.timestamp+sellLockTime;
    }
    
    //Resets buy lock of caller to the default buyLockTime should something go very wrong
    function AddressResetBuyLock() public{
        _buyLock[msg.sender]=block.timestamp+buyLockTime;
    
    }

        //withdraws dividents of sender
    function Rewards() public{
        claimETH(msg.sender);
    }

    function getDividents(address addr) public view returns (uint256){
        if(isExcludedFromStaking(addr)) return toBePaid[addr];
        return _newDividentsOf(addr)+toBePaid[addr];
    }

    //Settings//////////////////////////////////////////////////////////////////////////////////////////////
 
    bool public sellLockDisabled;
    uint256 public sellLockTime;
    bool public buyLockDisabled;
    uint256 public buyLockTime;
    bool public manualConversion; 

    function CollectMarketingETH() public onlyOwner{
        uint256 amount=marketingBalance;
        marketingBalance=0;
        payable(Development).transfer((amount*25) / 100);
        payable(Marketing).transfer((amount*75) / 100);
    } 
    function TeamCollectXMarketingETH(uint256 amount) public onlyOwner{
        require(amount<=marketingBalance);
        marketingBalance-=amount;
        payable(Development).transfer((amount*25) / 100);
        payable(Marketing).transfer((amount*75) / 100);
    } 

    //switches autoLiquidity and marketing ETH generation during transfers
    function TeamSwitchManualETHConversion(bool manual) public onlyOwner{
        manualConversion=manual;
    }
    
    function TeamChangeMaxBuy(uint256 newMaxBuy) public onlyOwner{
      MaxBuy=newMaxBuy * 10**_decimals;
    }
    
    function TeamChangeDevelopment(address newDevelopment) public onlyOwner{
      Development=payable(newDevelopment);
    }
    
    function TeamChangeMarketing(address newMarketing) public onlyOwner{
      Marketing=payable(newMarketing);
    }

    //Disables the timeLock after selling for everyone
    function TeamDisableSellLock(bool disabled) public onlyOwner{
        sellLockDisabled=disabled;
    }
    
    //Disables the timeLock after buying for everyone
    function TeamDisableBuyLock(bool disabled) public onlyOwner{
        buyLockDisabled=disabled;
    }

    //Sets SellLockTime, needs to be lower than MaxSellLockTime
    function TeamSetSellLockTime(uint256 sellLockSeconds)public onlyOwner{
            require(sellLockSeconds<=MaxSellLockTime,"Sell Lock time too high");
            sellLockTime=sellLockSeconds;
    } 
    
    //Sets BuyLockTime, needs to be lower than MaxBuyLockTime
    function TeamSetBuyLockTime(uint256 buyLockSeconds)public onlyOwner{
            require(buyLockSeconds<=MaxBuyLockTime,"Buy Lock time too high");
            buyLockTime=buyLockSeconds;
    } 

    //Allows CA owner to change how much the contract sells to prevent massive contract sells as the token grows.
    function TeamUpdateAmountToSwap(uint256 newSwapAmount) public onlyOwner{
        currentAmountToSwap = newSwapAmount;
    }
    
    //Allows wallet exclusion to be added after launch
    function AddWalletExclusion(address exclusionAdd) public onlyOwner{
        _excluded.add(exclusionAdd);
    }
    
    //Sets Taxes
    function TeamSetTaxes(uint8 burnTaxes, uint8 liquidityTaxes, uint8 stakingTaxes,uint8 buyTax, uint8 sellTax, uint8 transferTax) public onlyOwner{
        uint8 totalTax=burnTaxes+liquidityTaxes+stakingTaxes;
        require(totalTax==100, "burn+liq+marketing needs to equal 100%");

        _burnTax=burnTaxes;
        _liquidityTax=liquidityTaxes;
        _stakingTax=stakingTaxes;
        
        _buyTax=buyTax;
        _sellTax=sellTax;
        _transferTax=transferTax;
    }

    //How much of the staking tax should be allocated for marketing
    function TeamChangeMarketingShare(uint8 newShare) public onlyOwner{
        require(newShare<=100); 
        marketingShare=newShare;
    }
    //manually converts contract token to LP and staking ETH
    function TeamCreateLPandETH() public onlyOwner{
    _swapContractToken();
    }
    
     //Limits need to be at least target, to avoid setting value to 0(avoid potential Honeypot)
    function TeamUpdateLimits(uint256 newBalanceLimit, uint256 newSellLimit) public onlyOwner{
        //SellLimit needs to be below 1% to avoid a Large Price impact when generating auto LP
        require(newSellLimit<_circulatingSupply/100);
        //Adds decimals to limits
        newBalanceLimit=newBalanceLimit*10**_decimals;
        newSellLimit=newSellLimit*10**_decimals;
        //Calculates the target Limits based on supply
        uint256 targetBalanceLimit=_circulatingSupply/BalanceLimitDivider;
        uint256 targetSellLimit=_circulatingSupply/SellLimitDivider;

        require((newBalanceLimit>=targetBalanceLimit), 
        "newBalanceLimit needs to be at least target");
        require((newSellLimit>=targetSellLimit), 
        "newSellLimit needs to be at least target");

        balanceLimit = newBalanceLimit;
        sellLimit = newSellLimit;     
    }

    //Adds address to blacklist and prevents sells, buys or transfers.
    function addAddressToBlacklist(address blacklistedAddress) external onlyOwner {
        _isBlacklisted.add(blacklistedAddress);
    }

    //Remove address from blacklist and allow sells, buys or transfers.
    function removeAddressFromBlacklist(address blacklistedAddress) external onlyOwner {
        _isBlacklisted.remove(blacklistedAddress);
    }
    
    //Setup Functions///////////////////////////////////////////////////////////////////////////////////////
    
    bool public tradingEnabled;
    address private _liquidityTokenAddress;
    //Enables trading for everyone
    function SetupEnableTrading() public onlyOwner{
        tradingEnabled=true;
        tradingEnabledAt=block.timestamp;
    }

    //Sets up the LP-Token Address required for LP Release
    function SetupLiquidityTokenAddress(address liquidityTokenAddress) public onlyOwner{
        _liquidityTokenAddress=liquidityTokenAddress;
    }

    //Liquidity Lock////////////////////////////////////////////////////////////////////////////////////////
    //the timestamp when Liquidity unlocks
    uint256 private _liquidityUnlockTime;

    function TeamExtendLiquidityLock(uint256 secondsUntilUnlock) public onlyOwner{
        _prolongLiquidityLock(secondsUntilUnlock+block.timestamp);
    }
    function _prolongLiquidityLock(uint256 newUnlockTime) private{
        // require new unlock time to be longer than old one
        require(newUnlockTime>_liquidityUnlockTime);
        _liquidityUnlockTime=newUnlockTime;
    }