// File: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
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() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        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 {
        _transferOwnership(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");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: @openzeppelin/contracts/utils/Context.sol



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

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

// File: contracts/MultiSig.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.17;

import "@openzeppelin/contracts/access/Ownable.sol";
import "./VerifyContract.sol";

interface IERC20 {
    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) external returns (bool);

    function transfer(
        address recipient,
        uint256 amount
    ) external returns (bool);

    function decimals() external view returns (uint8);
}

struct Deposit {
    uint256 tokens;
    address receiver;
    address depositor;
    uint256 buyer_fee_bp;
    uint256 sellers_fee_bp;

    bool is_subscription;
    bool is_subscription_approved;
    uint256 subscription_cycle;
    uint256 subscription_start;
    uint256 amount_per_cycle;
    uint256 subscription_cycles_withdrawn;
}

contract MultiSig is VerifySignature, Ownable {
    IERC20 token;
    Deposit[] public deposits;
    address public fee_receiver;
    address public signer;
    bool safety_wheels = true;
    bool is_paused = false;
    bool fee_receiver_consent = false;

    event DepositEvent(uint256 index);

    constructor(address address_token) {
        token = IERC20(address_token);
        fee_receiver = msg.sender;
    }

    function set_fee_receiver(address new_fee_receiver) external {
        require(msg.sender == fee_receiver, "Only fee receiver can set fee receiver");
        fee_receiver = new_fee_receiver;
    }

    function set_signer(address new_signer) external onlyOwner() {
        signer = new_signer;
    }

    function deactivate_safety_wheels() external onlyOwner() {
        safety_wheels = false;
    }

    function flip_pause() external onlyOwner() {
        is_paused = !is_paused;
    }

    function set_fee_receiver_consent(bool new_consent) external {
        require(msg.sender == fee_receiver, "Only fee receiver can set fee receiver consent");
        fee_receiver_consent = new_consent;
    }

    function withdraw_owner(uint256 amount) external onlyOwner() {
        require(safety_wheels, "This feature is only available while safety wheels are on");
        require(fee_receiver_consent, "This feature requires consent by the fee receiver");
        token.transfer(fee_receiver, amount);
    }

    function deposit(
        address receiver,
        uint256 amount,
        uint256 buyer_fee_bp,
        bool is_subscription,
        uint256 subscription_cycle,
        uint256 amount_per_cycle
    ) external {
        require(!is_paused, "Contract is paused");
        uint256 buyer_fee = buyer_fee_bp == 0 ? 0 : amount * 1000 / (1000-buyer_fee_bp) - amount;
        token.transferFrom(msg.sender, address(this), amount+buyer_fee);
        deposits.push(Deposit(amount, receiver, msg.sender, buyer_fee_bp, 0,
            is_subscription, false, subscription_cycle, block.timestamp, amount_per_cycle, 0));
        emit DepositEvent(deposits.length - 1);
    }

    function _strings_equal(string memory str1, string memory str2) pure private returns(bool) {
        return keccak256(abi.encode(str1)) == keccak256(abi.encode(str2));
    }

    function withdraw(uint256 deposit_index, uint256 sellers_fee_bp, string memory message, bytes memory signature) public {
        require(!is_paused, "Contract is paused");
        Deposit memory this_deposit = deposits[deposit_index];
        require(
            this_deposit.tokens > 0,
            "This deposit has already been withdrawn"
        );

        bytes32 message_hash = keccak256(abi.encodePacked(deposit_index, sellers_fee_bp, message));
        bool is_signature_valid = verify(message_hash, signature, signer);

        if(_strings_equal(message, "refund")) {
            if(!is_signature_valid) {
                is_signature_valid = verify(message_hash, signature, this_deposit.receiver);
            }
            require(is_signature_valid, "Invalid signature");

            uint256 amount = this_deposit.tokens;
            uint256 buyer_fee = calculate_buyer_fee(this_deposit.buyer_fee_bp, amount);
            deposits[deposit_index].tokens = 0;

            token.transfer(this_deposit.depositor, this_deposit.tokens + buyer_fee);
        }

        if(_strings_equal(message, "payout")) {
            if(!is_signature_valid) {
                is_signature_valid = verify(message_hash, signature, this_deposit.depositor);
            }
            require(is_signature_valid, "Invalid signature");

            uint256 amount = this_deposit.is_subscription ? this_deposit.amount_per_cycle : this_deposit.tokens;
            uint256 buyer_fee = calculate_buyer_fee(this_deposit.buyer_fee_bp, amount);
            uint256 sellers_fee = amount * (sellers_fee_bp) / 1000;

            if(this_deposit.is_subscription) {
                deposits[deposit_index].is_subscription_approved = true;
                deposits[deposit_index].subscription_cycles_withdrawn++;
                deposits[deposit_index].sellers_fee_bp = sellers_fee_bp;
            }

            deposits[deposit_index].tokens -= amount;

            token.transfer(fee_receiver, sellers_fee + buyer_fee);
            token.transfer(this_deposit.receiver, amount-sellers_fee); 
        }
    }

    function withdraw_subscription(uint256 deposit_index) public {
        require(!is_paused, "Contract is paused");
        Deposit memory this_deposit = deposits[deposit_index];
        require(this_deposit.is_subscription, "This is not a subscription");
        require(this_deposit.is_subscription_approved, "This subscription has not been approved");

        uint256 cycles_completed = uint256((block.timestamp - this_deposit.subscription_start) / this_deposit.subscription_cycle);
        
        uint256 cycles_to_withdraw = (cycles_completed - this_deposit.subscription_cycles_withdrawn);
        uint256 amount = this_deposit.amount_per_cycle * cycles_to_withdraw;

        uint256 buyer_fee = calculate_buyer_fee(this_deposit.buyer_fee_bp, amount);
        uint256 sellers_fee = amount * (this_deposit.sellers_fee_bp) / 1000;

        require(amount > 0, "nothing to withdraw");

        deposits[deposit_index].tokens -= amount;
        deposits[deposit_index].subscription_cycles_withdrawn += cycles_to_withdraw;


        token.transfer(fee_receiver, sellers_fee + buyer_fee);
        token.transfer(this_deposit.receiver, amount-sellers_fee);
    }

    function cancel_subscription(uint256 deposit_index) public {
        require(!is_paused, "Contract is paused");
        Deposit memory this_deposit = deposits[deposit_index];
        require(this_deposit.is_subscription, "This is not a subscription");
        require(this_deposit.is_subscription_approved, "This subscription has not been approved");
        require(this_deposit.depositor == msg.sender, "This is not your subscription");

        uint256 to_withdraw = deposits[deposit_index].tokens- this_deposit.amount_per_cycle;
        uint256 buyer_fee = calculate_buyer_fee(this_deposit.buyer_fee_bp, to_withdraw);

        require(to_withdraw > 0, "nothing to withdraw");

        deposits[deposit_index].tokens -= to_withdraw;

        token.transfer(this_deposit.depositor, to_withdraw + buyer_fee);
    }

    function calculate_buyer_fee(uint256 buyer_fee_bp, uint256 amount) internal pure returns(uint256) {
        return buyer_fee_bp == 0 ? 0 : amount * 1000 / (1000-buyer_fee_bp) - amount;
    }
}

// File: contracts/VerifyContract.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.17;

abstract contract VerifySignature {

    function getEthSignedMessageHash(
        bytes32 _messageHash
    ) public pure returns (bytes32) {
        return
            keccak256(
                abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash)
            );
    }

    function verify(
        bytes32 message_hash,
        bytes memory signature,
        address signer
    ) public pure returns (bool) {
        bytes32 ethSignedMessageHash = getEthSignedMessageHash(message_hash);
        return recoverSigner(ethSignedMessageHash, signature) == signer;
    }

    function recoverSigner(
        bytes32 _ethSignedMessageHash,
        bytes memory _signature
    ) public pure returns (address) {
        (bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature);

        return ecrecover(_ethSignedMessageHash, v, r, s);
    }

    function splitSignature(
        bytes memory sig
    ) public pure returns (bytes32 r, bytes32 s, uint8 v) {
        require(sig.length == 65, "invalid signature length");

        assembly {
            r := mload(add(sig, 32))
            s := mload(add(sig, 64))
            v := byte(0, mload(add(sig, 96)))
        }

    }
}