// File: @openzeppelin/contracts/security/ReentrancyGuard.sol


// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}

// File: contracts/lotterypot2.sol


pragma solidity ^0.8.0;


contract Lottery is ReentrancyGuard {
    address public owner;
    address[] public participants;
    mapping(address => bool) public hasParticipated;
    address public winner; // State variable to store winner's address
    uint256 public ticketPrice = 0.1 ether;
    uint256 public maxTickets = 10;
    uint256 public lotteryEndTime;
    bool public lotteryEnded = false;

    // Events
    event TicketPurchased(address indexed participant);
    event LotteryWon(address indexed winner, uint256 prize);
    event PrizeWithdrawn(address indexed winner, uint256 prize);
    event LotteryReset();

    constructor(uint256 _duration) {
        owner = msg.sender;
        lotteryEndTime = block.timestamp + _duration;
    }

    modifier onlyOwner() {
        require(msg.sender == owner, "Only owner can perform this action");
        _;
    }

    function buyTicket() external payable {
        require(!lotteryEnded, "Lottery has ended");
        require(msg.value == ticketPrice, "Incorrect Ether sent");
        require(participants.length < maxTickets, "Maximum tickets sold");
        require(!hasParticipated[msg.sender], "You have already participated");

        participants.push(msg.sender);
        hasParticipated[msg.sender] = true;

        emit TicketPurchased(msg.sender);
        
        if (participants.length == maxTickets) {
            endLottery();
        }
    }

    function endLottery() internal {
        require(!lotteryEnded, "Lottery already ended");
        require(block.timestamp >= lotteryEndTime || participants.length == maxTickets, "Lottery not yet over");

        lotteryEnded = true;
        uint256 randomIndex = randomMod(participants.length);
        winner = participants[randomIndex]; // Set the winner's address
        
        uint256 prize = (address(this).balance * 9) / 10;
        payable(winner).transfer(prize); // Automatically send prize to winner
        
        // Transfer remaining balance to the owner
        payable(owner).transfer(address(this).balance);

        emit LotteryWon(winner, prize);
    }

    function randomMod(uint _modulus) internal view returns(uint256) {
        // Be aware that this is not a secure form of randomness and is vulnerable to attack in a production environment.
        return uint256(keccak256(abi.encodePacked(block.difficulty, block.timestamp, participants))) % _modulus;
    }

    function manualEndLottery() external onlyOwner {
        endLottery();
    }

    function resetLottery(uint256 _duration) external onlyOwner {
        require(lotteryEnded, "Previous lottery hasn't ended yet");

        // Resetting state
        for (uint i = 0; i < participants.length; i++) {
            hasParticipated[participants[i]] = false;
        }
        participants = new address[](0);
        lotteryEnded = false;
        lotteryEndTime = block.timestamp + _duration;
        winner = address(0); // Reset the winner address

        emit LotteryReset();
    }

    function getWinner() public view returns (address) {
        require(lotteryEnded, "Lottery has not ended yet");
        return winner;
    }

    // Removed withdrawPrize() as winnings are now sent automatically

    // Additional getter function if you want to return all participants
    function getParticipants() public view returns (address[] memory) {
        return participants;
    }
}