// File: src/PrivateSale.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "./Vesting.sol";
import "openzeppelin/access/Ownable.sol";
import "openzeppelin/security/Pausable.sol";

contract PrivateSale is Ownable, Pausable {

    Vesting public vestingContract;
    bool public isSaleEnd;

    uint256 public maxTokensToSell;
    uint256 public remainingTokens;

    mapping(address => uint256) public vestedAmount;

    event TokensPurchased(address buyer, uint256 amount);
    event TokensClaimed(address beneficiary, uint256 amount);

    constructor(address _vestingContract, uint256 _maxTokensToSell) Ownable(msg.sender) {
        vestingContract = Vesting(_vestingContract);
        maxTokensToSell = _maxTokensToSell;
        remainingTokens = _maxTokensToSell;
    }

    modifier onlySaleEnd() {
        require(isSaleEnd, "Sale has not ended");
        _;
    }

    modifier onlySaleNotEnd() {
        require(!isSaleEnd, "Sale has ended");
        _;
    }

    function purchaseTokensFor(address[] calldata recipients, uint256[] calldata amounts, uint8[] calldata durations, uint256[] calldata startTimes, uint256[] calldata lockDurations)
        external
        onlyOwner
        onlySaleNotEnd
    {
        require(recipients.length == amounts.length, "Recipients and amounts do not match");
        require(recipients.length == durations.length, "Recipients and durations do not match");
        require(recipients.length == startTimes.length, "Recipients and startTimes do not match");
        require(recipients.length == lockDurations.length, "Recipients and lockDurations do not match");
        uint256 amountVested;
        for (uint256 i = 0; i < recipients.length; i++) {
            address recipient = recipients[i];
            uint256 amount = amounts[i];
            uint8 duration = durations[i];
            uint256 startTime = startTimes[i];
            uint256 lockDuration = lockDurations[i];
            amountVested = amountVested + amount;
            require(amount > 0, "Amount must be greater than zero");
            require(remainingTokens >= amountVested, "Insufficient tokens available for sale");
            require(duration > 0, "Duration must be greater than zero");

            vestedAmount[recipient] = vestedAmount[recipient] + amount;

            vestingContract.createVestingSchedule(
                recipient,
                amount,
                duration, // Number of months for the release period
                startTime, // Start time of the vesting schedule
                lockDuration // Number of months before vesting period begins
            );
            emit TokensPurchased(recipient, amount);
        }
        remainingTokens = remainingTokens - amountVested;
    }

    function claimVestedTokens() external onlySaleEnd {
        uint256 userVestedAmount = vestedAmount[msg.sender];
        require(userVestedAmount > 0, "No tokens available to claim");

        uint256 releasableTokens = vestingContract.getReleasableTokens(address(this), msg.sender);
        require(releasableTokens > 0, "No tokens available for release");

        vestingContract.releaseTokens(address(this), msg.sender);

        emit TokensClaimed(msg.sender, releasableTokens);
    }

    function setSaleEnd() external onlyOwner {
        isSaleEnd = !isSaleEnd;
    }

    function seeClaimableTokens() external view returns (uint256 releasableTokens) {
        releasableTokens = vestingContract.getReleasableTokens(address(this), msg.sender);
    }

    function updateVestingAddress(address vestingAddr) external onlyOwner {
        require(vestingAddr != address(0), "Vesting address cannot be Zero");
        vestingContract = Vesting(vestingAddr);
    }
}

// File: src/Vesting.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "openzeppelin/token/ERC20/IERC20.sol";
import "openzeppelin/access/Ownable.sol";
import "openzeppelin/security/Pausable.sol";

contract Vesting is Ownable, Pausable {

    // Number of seconds in 365 days, divided by 12:
    uint256 public constant SECONDS_PER_MONTH = 2628000;

    // Mapping of plan id to start date. All beneficiaries of a specific plan would have the same start time
    mapping(uint256 => uint256) public startDates;
    struct VestingSchedule {
        uint256 totalTokens; // amount of tokens for a recipient
        uint256 releasePeriod; // Number of months for the release period
        uint256 startDate; // The plan number for the start time of the vesting schedule
        uint256 releasedTokens; // Number of tokens released so far
        uint256 lockDuration; // Number of months for the release period
    }
    uint256 public tokensVested;

    // privatesale addr => (user addr => schedule)
    mapping(address => mapping(address => VestingSchedule)) public vestingSchedules;

    // privatesale addr => bool
    mapping(address => bool) public vestingSchedulesActive;
    mapping(address => bool) public whitelist;

    IERC20 public token;

    event TokensReleased(address beneficiary, uint256 amount);
    event VestingScheduleCreated(address beneficiary, uint256 totalTokens, uint256 startDate, uint256 lockDuration);
    event VestingScheduleUpdated(address beneficiary, uint256 totalTokens);

    constructor(address _token) Ownable(msg.sender) {
        token = IERC20(_token);
    }

    function createVestingSchedule(address beneficiary, uint256 totalTokens, uint256 releasePeriod, uint256 startDate, uint256 lockDuration)
        external
        onlyWhitelisted
        whenNotPaused
    {
        require(totalTokens > 0, "Total tokens must be greater than zero");
        require(releasePeriod > 0, "Release period must be greater than zero");
        require((totalTokens + tokensVested) <= token.balanceOf(address(this)), "Not enough tokens for vesting");
        require(
            vestingSchedules[msg.sender][beneficiary].releasedTokens == 0,
            "Vesting schedule already in use, for the beneficiary"
        );
        VestingSchedule storage schedule = vestingSchedules[msg.sender][beneficiary];
        if(vestingSchedules[msg.sender][beneficiary].totalTokens == 0) {
            schedule.totalTokens = totalTokens;
            schedule.releasePeriod = releasePeriod;
            schedule.startDate = startDate;
            schedule.lockDuration = lockDuration;
            emit VestingScheduleCreated(beneficiary, schedule.totalTokens, startDates[schedule.startDate], schedule.lockDuration);
        } else {
            schedule.totalTokens = schedule.totalTokens + totalTokens;
            emit VestingScheduleUpdated(beneficiary, totalTokens);
        }
        tokensVested = tokensVested + totalTokens;
    }

    function removeVestingSchedule(address contractAddress, address beneficiary)
        external
        whenNotPaused
        onlyWhitelisted
    {
        VestingSchedule storage schedule = vestingSchedules[contractAddress][beneficiary];
        uint256 tokensLeft = schedule.totalTokens - schedule.releasedTokens;
        tokensVested = tokensVested - tokensLeft;
        delete vestingSchedules[contractAddress][beneficiary];
    }

    function releaseTokens(address contractAddress, address beneficiary) external whenNotPaused onlyWhitelisted {
        require(vestingSchedulesActive[contractAddress] == true, "Vesting schedule not active");
        uint256 releasableTokens = getReleasableTokens(contractAddress, beneficiary);
        require(releasableTokens > 0, "No tokens available for release");
        VestingSchedule storage schedule = vestingSchedules[contractAddress][beneficiary];
        schedule.releasedTokens = schedule.releasedTokens + releasableTokens;
        tokensVested = tokensVested - releasableTokens;
        token.transfer(beneficiary, releasableTokens);
        emit TokensReleased(beneficiary, releasableTokens);
    }

    function getReleasableTokens(address contractAddress, address beneficiary) public view returns (uint256) {
        VestingSchedule storage schedule = vestingSchedules[contractAddress][beneficiary];
        require(schedule.totalTokens > 0, "No vesting schedule found for the beneficiary");
        uint256 tokensToClaim;
        uint256 claimingStartTime = startDates[schedule.startDate] + (schedule.lockDuration * SECONDS_PER_MONTH);
        if(block.timestamp <= claimingStartTime) {
            tokensToClaim = 0;
        } else {
            uint256 elapsedTime = block.timestamp - claimingStartTime;
            uint256 totalReleasePeriods = schedule.releasePeriod;
            uint256 totalTokens = schedule.totalTokens;
            uint256 tokensPerPeriod = totalTokens / totalReleasePeriods;
            uint256 passedMonths = (elapsedTime / SECONDS_PER_MONTH) >= totalReleasePeriods
                ? totalReleasePeriods
                : elapsedTime / SECONDS_PER_MONTH;
            uint256 tokensToRelease = passedMonths * (tokensPerPeriod);

            if(passedMonths == 0) {
                tokensToClaim = 0;
            } else {
                tokensToClaim = passedMonths == totalReleasePeriods
                    ? totalTokens - schedule.releasedTokens
                    : tokensToRelease - schedule.releasedTokens;
            }
        }
        return tokensToClaim;
    }

    function getNextClaimableTime(address contractAddress, address beneficiary, uint256 dateID) external view returns (uint256) {
        VestingSchedule storage schedule = vestingSchedules[contractAddress][beneficiary];
        uint256 current_time = block.timestamp;
        uint256 timeRemaining;
        uint256 claimingStartTime = startDates[dateID] + (schedule.lockDuration * SECONDS_PER_MONTH);
        if(current_time > ((schedule.releasePeriod * SECONDS_PER_MONTH) + claimingStartTime)) {
            timeRemaining = 0;
        } else {
            if(current_time >= claimingStartTime) {
                uint256 diff = current_time - claimingStartTime;
                uint256 current_multiple = diff / SECONDS_PER_MONTH;
                uint256 timer_start = (current_multiple * SECONDS_PER_MONTH) + claimingStartTime;
                uint256 current_progress_in_month = current_time - timer_start;
                timeRemaining = SECONDS_PER_MONTH - current_progress_in_month;
            } else {
                timeRemaining = claimingStartTime - current_time;
            }
        }
        return timeRemaining;
    }

    modifier onlyWhitelisted() {
        require(whitelist[msg.sender], "Sender is not whitelisted");
        _;
    }

    function updateStartDate(uint256 dateId, uint256 startDate) external onlyOwner {
        startDates[dateId] = startDate;
    }

    function addToWhitelist(address[] calldata addresses) external onlyOwner {
        for (uint256 i = 0; i < addresses.length; i++) {
            address addr = addresses[i];
            whitelist[addr] = true;
        }
    }

    function removeFromWhitelist(address[] calldata addresses) external onlyOwner {
        for (uint256 i = 0; i < addresses.length; i++) {
            address addr = addresses[i];
            whitelist[addr] = false;
        }
    }

    function setVestingSchedulesActive(address contractAddress, bool active) external onlyOwner {
        vestingSchedulesActive[contractAddress] = active;
    }

    function updateTokenAddress(address tokenAddr) external onlyOwner {
        require(tokenAddr != address(0), "Token address cannot be Zero");
        token = IERC20(tokenAddr);
    }

    function pause() external onlyOwner {
        _pause();
    }

    function unpause() external onlyOwner {
        _unpause();
    }
}

// File: lib/openzeppelin-contracts/contracts/access/Ownable.sol



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

pragma solidity ^0.8.20;

import {Context} from "../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.
 *
 * The initial owner is set to the address provided by the deployer. 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;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        _transferOwnership(initialOwner);
    }

    /**
     * @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 {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling 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 {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _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: lib/openzeppelin-contracts/contracts/security/Pausable.sol



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

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

// File: lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @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);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) 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 a `value` amount of tokens 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 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

// File: lib/openzeppelin-contracts/contracts/utils/Context.sol



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

pragma solidity ^0.8.20;

/**
 * @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;
    }
}