// File: IERC165.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// File: IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) external returns (bool);

    function mint(address to, uint256 amount) external;

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: IERC721.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;
}

// File: IERC721Receiver.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

// File: LDCStakingRewards.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./IERC721.sol";
import "./IERC721Receiver.sol";

contract LDCStakingRewards is IERC721Receiver {

    uint256 public constant ONE_DAY_IN_SECONDS = 86400;
    uint256 public LDCTokensPerDayStaked = 3e18;
    mapping(uint256 => stakingInfo) public nftStakes;
    mapping(address => uint256[]) public stakedNftsByAddress;
    address private owner;
    IERC20 public immutable LDCToken;
    IERC721 public immutable LDCNFT;
    bool public stakingEnabled;

    struct stakingInfo {
        address nftOwner;
        uint64 initTimestamp;
        uint128 rewardsClaimed;
    }

    event Staked(address user, uint256 NFTid);
    event Unstaked(address user, uint256 NFTid);
    event Claimed(address user, uint256 rewardAmount);

    constructor(address _LDCToken, address _LDCNFT) {
        /* 
            Once the contract is deployed, the owner of the LDCToken contract 
            must assign this contract (LDCStakingRewards) the MINTER_ROLE

            MINTER_ROLE is required so users can get their rewards through the claimRewards() function
        */
        owner = msg.sender;
        LDCToken = IERC20(_LDCToken);
        LDCNFT = IERC721(_LDCNFT); // https://etherscan.io/address/0xacc908bbcd7f50f2e07afaec5455b73aea1d4f7d#code
        stakingEnabled = true; // Staking will be enabled as soon as the contract is deployed
    }

    modifier onlyOwner() {
        require(owner == msg.sender, "Caller is not the owner");
        _;
    }

    function transferOwnership(address newOwner) external onlyOwner {
        require(newOwner != address(0), "New owner is the zero address");
        owner = newOwner;
    }

    /*
        @info Used to enable/disable the staking function
        If stakingEnabled users will not be able to stake their NFTs
        Current staked NFTs can still be claimed
    */
    function toggleStaking() external onlyOwner {
        stakingEnabled = !stakingEnabled;
    }

    /*
        @param newRewardsPerDay the new amount of LilDudeClub tokens that will be rewarded per day of stake
    */
    function updateRewardsPerDay(uint256 newRewardsPerDay) external onlyOwner {
        LDCTokensPerDayStaked = newRewardsPerDay;
    }

    /*
        @param NFTid the id of the LDC collection NFT

        @info In order to call this function msg.sender should ERC721.approve this contract address
        as the NFT will be transferred to this smart contract during the staking period
    */

    function stakeLDC(uint256 NFTid) external {
        require(stakingEnabled, "Staking is currently disabled");

        nftStakes[NFTid] = stakingInfo({
            nftOwner: msg.sender,
            initTimestamp: uint64(block.timestamp),
            rewardsClaimed: 0
        });

        stakedNftsByAddress[msg.sender].push(NFTid);

        // Transferring the NFT to this contract
        LDCNFT.safeTransferFrom(
            msg.sender,
            address(this),
            NFTid,
            bytes("stake")
        );

        emit Staked(msg.sender, NFTid);
    }

    /*
        @param NFTid array of ids of the LDC collection NFT

        @info Works the same way as stakeLDC() but allows to stake multiple NFTs at once
        In order to call this function msg.sender should ERC721.approve this contract address
        for each of the NFTs staked
    */
    function stakeMultipleLDC(uint256[] calldata NFTid) external {
        require(stakingEnabled, "Staking is currently disabled");
        
        uint256 len = NFTid.length;
        for (uint256 i; i < len; ++i) {
            nftStakes[NFTid[i]] = stakingInfo({
                nftOwner: msg.sender,
                initTimestamp: uint64(block.timestamp),
                rewardsClaimed: 0
            });

            stakedNftsByAddress[msg.sender].push(NFTid[i]);

            // Transferring the NFT to this contract
            LDCNFT.safeTransferFrom(
                msg.sender,
                address(this),
                NFTid[i],
                bytes("stake")
            );
            emit Staked(msg.sender, NFTid[i]);
        }
    }

    /*
        @param NFTid the id of the LDC collection NFT

        @info Claims the rewards and then unstake the NFTid
    */
    function unstakeLDC(uint256 NFTid) external {
        require(nftStakes[NFTid].nftOwner == msg.sender, "You do not own this NFT");
        
        // Claiming the rewards for this NFT
        uint256 totalDaysStaked = (block.timestamp - nftStakes[NFTid].initTimestamp) / ONE_DAY_IN_SECONDS;
        uint256 tokensToMintAndSend = uint128(totalDaysStaked * LDCTokensPerDayStaked);
        uint256 tokensAlreadyRewarded = uint128(nftStakes[NFTid].rewardsClaimed);
        uint256 finalReward = tokensToMintAndSend - tokensAlreadyRewarded;

        // Updating the stakedNftsByAddress array
        uint256 indexToRemove;
        uint256 arrayLength = stakedNftsByAddress[msg.sender].length;
        for (uint256 i; i < arrayLength; ++i) {
            if (stakedNftsByAddress[msg.sender][i] == NFTid){
                indexToRemove = i;
                break;
            }
        }
        
        if (indexToRemove != arrayLength - 1){
             // Moving the last element of the array to the position that we need to remove, then deleting the last position
            stakedNftsByAddress[msg.sender][indexToRemove] = stakedNftsByAddress[msg.sender][arrayLength - 1];
        }
        stakedNftsByAddress[msg.sender].pop();

        delete nftStakes[NFTid];

        // Transferring the reward tokens
        if (finalReward > 0){
            LDCToken.mint(msg.sender, finalReward);
        }

        // Giving the user back his previously staked NFT
        LDCNFT.safeTransferFrom(
            address(this),
            msg.sender,
            NFTid,
            bytes("unstake")
        );

        emit Unstaked(msg.sender, NFTid);
    }

    /*
        @param NFTid array of ids of the LDC collection NFT to unstake

        @info Claims the rewards and then unstakes the NTFs of the NFTid array
    */
    function unstakeMultipleLDC(uint256[] calldata NFTid) external {
        uint256 len = NFTid.length;
        uint256 totalDaysStaked;
        uint256 tokensToMintAndSend;
        uint256 tokensAlreadyRewarded;
        uint256 indexToRemove;
        uint256 arrayLength;
        for (uint256 i; i < len; ++i) {
            require(nftStakes[NFTid[i]].nftOwner == msg.sender, "You do not own this NFT");
            totalDaysStaked = (block.timestamp - nftStakes[NFTid[i]].initTimestamp) / ONE_DAY_IN_SECONDS;
            tokensToMintAndSend += uint128(totalDaysStaked * LDCTokensPerDayStaked);
            tokensAlreadyRewarded += uint128(nftStakes[NFTid[i]].rewardsClaimed);
            delete nftStakes[NFTid[i]];

            // Updating the stakedNftsByAddress array
            arrayLength = stakedNftsByAddress[msg.sender].length;
            for (uint256 j; j < arrayLength; ++j) {
                if (stakedNftsByAddress[msg.sender][j] == NFTid[i]){
                    indexToRemove = j;
                    break;
                }
            }
            if (indexToRemove != arrayLength - 1){
                // Moving the last element of the array to the position that we need to remove, then deleting the last position
                stakedNftsByAddress[msg.sender][indexToRemove] = stakedNftsByAddress[msg.sender][arrayLength - 1];
            }
            stakedNftsByAddress[msg.sender].pop();
        }

        // Transferring the reward tokens
        uint256 finalReward = tokensToMintAndSend - tokensAlreadyRewarded;
        if(finalReward > 0){
            LDCToken.mint(msg.sender, finalReward);
        }

        // Giving the user back his previously staked NFTs
        for (uint256 i; i < len; ++i) {
            LDCNFT.safeTransferFrom(
                address(this),
                msg.sender,
                NFTid[i],
                bytes("unstake")
            );
            emit Unstaked(msg.sender, NFTid[i]);
        }
    }

    /*
        @param NFTid the id of the LDC collection NFT that was previously staked
    */
    function claimRewards() external {
        uint256[] memory allStakedTokens = getCurrentStakedTokensByUser(msg.sender);
        uint256 len = allStakedTokens.length;
        require(len > 0, "No NFTs currently staked");
        uint128 tokensToMintAndSend;
        uint128 tokensAlreadyRewarded;
        uint256 totalDaysStaked;
        for (uint256 i; i < len; ++i) {
            totalDaysStaked = (block.timestamp - nftStakes[allStakedTokens[i]].initTimestamp) / ONE_DAY_IN_SECONDS;
            // 3 tokens per day and per NFT staked
            tokensToMintAndSend += uint128(totalDaysStaked * LDCTokensPerDayStaked);
            tokensAlreadyRewarded += uint128(nftStakes[allStakedTokens[i]].rewardsClaimed);
            nftStakes[allStakedTokens[i]].rewardsClaimed = uint128(totalDaysStaked * LDCTokensPerDayStaked);
        }

        uint256 finalReward = tokensToMintAndSend - tokensAlreadyRewarded;
        require(finalReward > 0, "No rewards available yet");
        LDCToken.mint(msg.sender, finalReward);
        emit Claimed(msg.sender, finalReward);
    }

    /*
        Number of NFTs currently staked in the contract
    */
    function getCurrentTotalStakedTokens() public view returns (uint256)
    {
        return LDCNFT.balanceOf(address(this));
    }

    /*
        Allows the users to check the token IDs they have currently staked in the contract
    */
    function getCurrentStakedTokensByUser(address user) public view returns (uint256[] memory)
    {
        return stakedNftsByAddress[user];
    }

    /*
        Allows the users to see their total pending rewards
    */
    function getPendingRewards(address user) public view returns (uint256)
    {
        uint256[] memory allStakedTokens = getCurrentStakedTokensByUser(user);
        uint256 len = allStakedTokens.length;
        require(len > 0, "No NFTs currently staked");
        uint128 tokensToMintAndSend;
        uint128 tokensAlreadyRewarded;
        uint256 totalDaysStaked;
        for (uint256 i; i < len; ++i) {
            totalDaysStaked = (block.timestamp - nftStakes[allStakedTokens[i]].initTimestamp) / ONE_DAY_IN_SECONDS;
            // 3 tokens per day and per NFT staked
            tokensToMintAndSend += uint128(totalDaysStaked * LDCTokensPerDayStaked);
            tokensAlreadyRewarded += uint128(nftStakes[allStakedTokens[i]].rewardsClaimed);
        }
        uint256 finalReward = tokensToMintAndSend - tokensAlreadyRewarded;
        return finalReward;
    }

    /*
        Allows the users to see their total pending rewards
    */
    function getPendingRewardsByNFT(uint256 NFTid) public view returns (uint256)
    {
        uint256 totalDaysStaked = (block.timestamp - nftStakes[NFTid].initTimestamp) / ONE_DAY_IN_SECONDS;
        uint256 tokensToMintAndSend = uint128(totalDaysStaked * LDCTokensPerDayStaked);
        uint256 tokensAlreadyRewarded = uint128(nftStakes[NFTid].rewardsClaimed);
        return tokensToMintAndSend - tokensAlreadyRewarded;
    }

    function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {
        return this.onERC721Received.selector;
    }
}