// Contract: AdoreFinanceToken
// Target function: function purchaseTokens(uint256 _incomingEthereum)
pragma solidity ^0.7.0;

contract AdoreFinanceToken {
    // only people with tokens
    modifier onlyBagholders() {
        require(myTokens() > 0);
        _;
    }
    modifier onlyAdministrator(){
        address _customerAddress = msg.sender;
        require(administrators[_customerAddress]);
        _;
    }
    /*==============================
    =            EVENTS            =
    ==============================*/

    event Reward(
       address indexed to,
       uint256 rewardAmount,
       uint256 level
    );
    event RewardWithdraw(
       address indexed from,
       uint256 rewardAmount
    );
    // ERC20
    event Transfer(
        address indexed from,
        address indexed to,
        uint256 tokens
    );
   
    /*=====================================
    =            CONFIGURABLES            =
    =====================================*/
    string public name = "Adore Finance Token";
    string public symbol = "XFA";
    uint8 constant public decimals = 0;
    uint256 public totalSupply_ = 2000000;
    uint256 constant internal tokenPriceInitial_ = 0.00012 ether;
    uint256 constant internal tokenPriceIncremental_ = 25000000;
    uint256 public currentPrice_ = tokenPriceInitial_ + tokenPriceIncremental_;
    uint256 public base = 1;
    uint256 public basePrice = 400;
    uint public percent = 500;
    uint public referralPercent = 1000;
    uint public sellPercent = 1500;
    mapping(address => uint256) internal tokenBalanceLedger_;
    mapping(address => uint256) internal rewardBalanceLedger_;
    address commissionHolder;
    uint256 internal tokenSupply_ = 0;
    mapping(address => bool) internal administrators;
    mapping(address => address) public genTree;
    mapping(address => uint256) public level1Holding_;
    address payable internal creator;
    address payable internal management; //for management funds
    address internal poolFund;
    uint8[] percent_ = [7,2,1];
    uint8[] adminPercent_ = [37,37,16,10];
    address dev1;
    address dev2;
    address dev3;
    address dev4;
   
    constructor()
    {
        creator = msg.sender;
        administrators[creator] = true;
    }
    
    function isContract(address account) public view returns (bool) {
        // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
        // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
        // for accounts without code, i.e. `keccak256('')`
        bytes32 codehash;
        bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
        // solhint-disable-next-line no-inline-assembly
        assembly { codehash := extcodehash(account) }
        return (codehash != accountHash && codehash != 0x0);
    }
   
    function withdrawRewards(address payable _customerAddress, uint256 _amount) onlyAdministrator() public returns(uint256)
    {
        require(rewardBalanceLedger_[_customerAddress]>_amount && _amount > 3000000000000000);
        rewardBalanceLedger_[commissionHolder] += 3000000000000000;
        rewardBalanceLedger_[_customerAddress] -= _amount;
        emit RewardWithdraw(_customerAddress,_amount);
        _amount = SafeMath.sub(_amount, 3000000000000000);
        _customerAddress.transfer(_amount);
    }

    function setDevs(address _dev1, address _dev2, address _dev3, address _dev4) onlyAdministrator() public{
        dev1 = _dev1;
        dev2 = _dev2;
        dev3 = _dev3;
        dev4 = _dev4;
    }
    function distributeCommission() onlyAdministrator() public returns(bool)
    {
        require(rewardBalanceLedger_[management]>100000000000000);
        rewardBalanceLedger_[dev1] += (rewardBalanceLedger_[management]*3700)/10000;
        rewardBalanceLedger_[dev2] += (rewardBalanceLedger_[management]*3700)/10000;
        rewardBalanceLedger_[dev3] += (rewardBalanceLedger_[management]*1600)/10000;
        rewardBalanceLedger_[dev4] += (rewardBalanceLedger_[management]*1000)/10000;
        rewardBalanceLedger_[management] = 0;
        return true;
    }
    
    function withdrawRewards(uint256 _amount) onlyAdministrator() public returns(uint256)
    {
        address payable _customerAddress = msg.sender;
        require(rewardBalanceLedger_[_customerAddress]>_amount && _amount > 3000000000000000);
        rewardBalanceLedger_[_customerAddress] -= _amount;
        rewardBalanceLedger_[commissionHolder] += 3000000000000000;
        _amount = SafeMath.sub(_amount, 3000000000000000);
        _customerAddress.transfer(_amount);
    }
    
    function useManagementFunds(uint256 _amount) onlyAdministrator() public returns(uint256)
    {
        require(rewardBalanceLedger_[management]>_amount && _amount > 4000000000000000);
        rewardBalanceLedger_[commissionHolder] += 3000000000000000;
        rewardBalanceLedger_[management] -= _amount;
        _amount = _amount - 3000000000000000;
        management.transfer(_amount);
    }
   
    function distributeRewards(uint256 _amountToDistribute, address _idToDistribute)
    internal
    {
        uint256 _tempAmountToDistribute = _amountToDistribute;
        for(uint i=0; i<3; i++)
        {
            address referrer = genTree[_idToDistribute];
            if(referrer != address(0x0) && level1Holding_[referrer] > i && i>0)
            {
                rewardBalanceLedger_[referrer] += (_amountToDistribute*percent_[i])/10;
                _idToDistribute = referrer;
                emit Reward(referrer,(_amountToDistribute*percent_[i])/10,i);
                _tempAmountToDistribute -= (_amountToDistribute*percent_[i])/10;
            }
            else if(i == 0)
            {
                 rewardBalanceLedger_[referrer] += (_amountToDistribute*percent_[i])/10;
                _idToDistribute = referrer;
                emit Reward(referrer,(_amountToDistribute*percent_[i])/10,i);
                _tempAmountToDistribute -= (_amountToDistribute*percent_[i])/10;
            }
            else
            {
                
            }
        }
        rewardBalanceLedger_[commissionHolder] += _tempAmountToDistribute;
    }
   
   function setBasePrice(uint256 _price)
    onlyAdministrator()
    public
    returns(bool) {
        basePrice = _price;
    }
   
    function buy(address _referredBy)
        public
        payable
        returns(uint256)
    {
        require(!isContract(msg.sender),"Buy from contract is not allowed");
        require(_referredBy != msg.sender,"Self Referral Not Allowed");
        if(genTree[msg.sender]!=_referredBy)
            level1Holding_[_referredBy] +=1;
        genTree[msg.sender] = _referredBy;
        purchaseTokens(msg.value);
    }
   
    receive() external payable
    {
        require(msg.value > currentPrice_, "Very Low Amount");
        purchaseTokens(msg.value);
    }
    
    fallback() external payable
    {
        require(msg.value > currentPrice_, "Very Low Amount");
        purchaseTokens(msg.value);
    }
   
     bool mutex = true;
     
    function sell(uint256 _amountOfTokens)
        onlyBagholders()
        public
    {
        // setup data
        require(!isContract(msg.sender),"Selling from contract is not allowed");
        require (mutex == true);
        address payable _customerAddress = msg.sender;
        require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
        uint256 _tokens = _amountOfTokens;
        uint256 _ethereum = tokensToEthereum_(_tokens,true);
        uint256 _dividends = _ethereum * (sellPercent)/10000;
        // burn the sold tokens
        tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
        tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
        rewardBalanceLedger_[management] += _dividends;
        rewardBalanceLedger_[commissionHolder] += 3000000000000000;
        _dividends = _dividends + 3000000000000000;
        _ethereum = SafeMath.sub(_ethereum,_dividends);
        _customerAddress.transfer(_ethereum);
        emit Transfer(_customerAddress, address(this), _tokens);
    }
   
    function rewardOf(address _toCheck)
        public view
        returns(uint256)
    {
        return rewardBalanceLedger_[_toCheck];    
    }
   
    function transfer(address _toAddress, uint256 _amountOfTokens)
        onlyAdministrator()
        public
        returns(bool)
    {
        // setup
        address _customerAddress = msg.sender;
        // exchange tokens
        tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
        tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
        emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
        return true;
    }
   
    function destruct() onlyAdministrator() public{
        selfdestruct(creator);
    }
   
    function setName(string memory _name)
        onlyAdministrator()
        public
    {
        name = _name;
    }
   
    function setSymbol(string memory _symbol)
        onlyAdministrator()
        public
    {
        symbol = _symbol;
    }

    function setupWallets(address _commissionHolder, address payable _management, address _poolFunds)
    onlyAdministrator()
    public
    {
        commissionHolder = _commissionHolder;
        management = _management;
        poolFund = _poolFunds;
    }
    

    function totalEthereumBalance()
        public
        view
        returns(uint)
    {
        return address(this).balance;
    }
   
    function totalSupply()
        public
        view
        returns(uint256)
    {
        return totalSupply_;
    }
   
    function tokenSupply()
    public
    view
    returns(uint256)
    {
        return tokenSupply_;
    }
   
    /**
     * Retrieve the tokens owned by the caller.
     */
    function myTokens()
        public
        view
        returns(uint256)
    {
        address _customerAddress = msg.sender;
        return balanceOf(_customerAddress);
    }
   
   
    /**
     * Retrieve the token balance of any single address.
     */
    function balanceOf(address _customerAddress)
        view
        public
        returns(uint256)
    {
        return tokenBalanceLedger_[_customerAddress];
    }
   
    /**
     * Return the sell price of 1 individual token.
     */
    function buyPrice()
        public
        view
        returns(uint256)
    {
        return currentPrice_;
    }