// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.13;

import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";



contract Contract {

    using ECDSA for bytes32;
    using MessageHashUtils for bytes32;

    address public owner;

    struct userDataStruct{
        uint256 startingDate;
        uint256 endingDate;
        uint256 amount;
        bool done;
    }

    mapping(address=>userDataStruct)public userAccounts;

    constructor(){
        owner = msg.sender;
    }

    function createAccount()external payable returns (string memory){

        require(msg.value>=0.001 ether , "Not Enough Ether");

        uint256 date_Now = block.timestamp;
        userAccounts[msg.sender] = userDataStruct({
            startingDate:date_Now,
            // For now the testing purpose i am gonna change it to 2 min
            // But if u are using my smart contract then please sure you change it to any duration
            endingDate:date_Now + 120 seconds,
            amount:msg.value,
            done: false
        });

        return "User Account Created";

    }

   

    
    function investigateAccount(bool doneCommit,uint256 mytimestamp,bytes memory signature)public returns (string memory){


        bytes32 messageHash = keccak256(
            abi.encodePacked(msg.sender, doneCommit, mytimestamp)
        );

        address signer = messageHash
            .toEthSignedMessageHash()
            .recover(signature);

       require(signer == owner , "Signature is not verified");

      

       uint256 date_Now = block.timestamp;
       userDataStruct storage acc = userAccounts[msg.sender];
       if(date_Now >= acc.startingDate && date_Now <= acc.endingDate && doneCommit && acc.done == false){
        return "User is Active on Clockb , his money is safe";
       }

       else if(date_Now >= acc.startingDate && date_Now <= acc.endingDate && !doneCommit && acc.done == false){
        acc.done = true;
        uint256 totalAmount = acc.amount;
        acc.amount = 0;
        payable(owner).transfer(totalAmount);
        return "User forgot to commit on Clockb so lost the money";
       }

       else if(date_Now>acc.endingDate && acc.done == false){
        acc.done = true;
        uint256 totalAmount = acc.amount;
        acc.amount = 0;
        payable(msg.sender).transfer(totalAmount);
        return "Contract Completed for this user";
       }

       return "Contract Completed for this user";
    }

 }
