// 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/token/ERC20/IERC20.sol



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

pragma solidity ^0.8.0;

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

// 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: @openzeppelin/contracts/utils/math/SafeMath.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (utils/math/SafeMath.sol)

pragma solidity ^0.8.0;

// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.

/**
 * @dev Wrappers over Solidity's arithmetic operations.
 *
 * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
 * now has built in overflow checking.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        return a + b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        return a * b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator.
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b <= a, errorMessage);
            return a - b;
        }
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a / b;
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a % b;
        }
    }
}

// File: contracts/EscrowDatabase.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;

import "@openzeppelin/contracts/access/Ownable.sol";

contract EscrowDatabase is Ownable {
    uint256 public escrowCounter = 0;
    address[] private _factoriesContracts;
    address[] private _allEscrowContracts;
    address[] private _goodsEscrowContracts;
    address[] private _servicesEscrowContracts;
    address[] private _nftEscrowContracts;
    address[] private _sourceCodeContracts;
    address[] private _gamblingContracts;
    mapping(address => address[]) private _escrowsOfUser;

    fallback() external payable {}

    receive() external payable {}

    modifier onlyFactoriesContracts() {
        bool _found = false;

        for (uint256 i = 0; i < _factoriesContracts.length; i++) {
            if (_factoriesContracts[i] == msg.sender) {
                _found = true;
            }
        }

        require(_found, "The call is only available from the factory smart contract");
        _;
    }

    modifier factoriesAndAllContracts() {
        bool _foundInFactoriesContracts = false;
        bool _foundInAllContracts = false;

        for (uint256 i = 0; i < _factoriesContracts.length; i++) {
            if (_factoriesContracts[i] == msg.sender) {
                _foundInFactoriesContracts = true;
            }
        }

        for (uint256 i = 0; i < _allEscrowContracts.length; i++) {
            if (_allEscrowContracts[i] == msg.sender) {
                _foundInAllContracts = true;
            }
        }

        require(_foundInFactoriesContracts || _foundInAllContracts, "The call is only available from the factory or escrow smart contract");
        _;
    }

    function increaseEscrowCounter() public onlyFactoriesContracts {
        escrowCounter += 1;
    }

    function addFactoriesContracts(address _factoryAddress) public onlyOwner {
        _factoriesContracts.push(_factoryAddress);
    }

    function addAllEscrowContracts(address _allContractAddress) public onlyFactoriesContracts {
        _allEscrowContracts.push(_allContractAddress);
    }

    function addGoodsEscrowContracts(address _goodsContractAddress) public onlyFactoriesContracts {
        _goodsEscrowContracts.push(_goodsContractAddress);
    }

    function addServicesEscrowContracts(address _servicesContractAddress) public onlyFactoriesContracts {
        _servicesEscrowContracts.push(_servicesContractAddress);
    }

    function addNftEscrowContracts(address _nftContractAddress) public onlyFactoriesContracts {
        _nftEscrowContracts.push(_nftContractAddress);
    }

    function addSourceCodeEscrowContracts(address _sourceCodeContractAddress) public onlyFactoriesContracts {
        _sourceCodeContracts.push(_sourceCodeContractAddress);
    }

    function addGamblingEscrowContracts(address _gamblingContractAddress) public onlyFactoriesContracts {
        _gamblingContracts.push(_gamblingContractAddress);
    }

    function addEscrowsOfUser(address _address, address _escrowContractAddress) public factoriesAndAllContracts {
        _escrowsOfUser[_address].push(_escrowContractAddress);
    }

    function deleteFromEscrowsOfUser(address _address, address _escrowContractAddress) public factoriesAndAllContracts {
        for (uint256 i = 0; i < _escrowsOfUser[_address].length; i++) {
            if (_escrowsOfUser[_address][i] == _escrowContractAddress) {
                _escrowsOfUser[_address][i] = _escrowsOfUser[_address][_escrowsOfUser[_address].length - 1];
                _escrowsOfUser[_address].pop();
            }
        }
    }

    function getEscrowAddressById(uint256 _id) public view returns (address) {
        return _allEscrowContracts[_id - 1];
    }

    function getFactoriesContracts() public onlyOwner view returns (address[] memory) {
        return _factoriesContracts;
    }

    function getAllEscrowContracts() public view returns (address[] memory) {
        return _allEscrowContracts;
    }

    function getGoodsEscrowContracts() public view returns (address[] memory) {
        return _goodsEscrowContracts;
    }

    function getServicesEscrowContracts() public view returns (address[] memory) {
        return _servicesEscrowContracts;
    }

    function getNftEscrowContracts() public view returns (address[] memory) {
        return _nftEscrowContracts;
    }

    function getSourceCodeEscrowContracts() public view returns (address[] memory) {
        return _sourceCodeContracts;
    }

    function getGamblingEscrowContracts() public view returns (address[] memory) {
        return _gamblingContracts;
    }

    function getEscrowsOfUserByAddress(address _address) public view returns (address[] memory) {
        return _escrowsOfUser[_address];
    }
}
// File: contracts/escrows/GoodsEscrow.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;

import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/IEscrowDatabase.sol";
import "../interfaces/IEscrowDispute.sol";

contract GoodsEscrow {
    using SafeMath for uint256;

    IEscrowDatabase private _escrowDatabaseContract;
    IEscrowDispute private _escrowDisputeContract;

    struct Escrow {
        uint256 id;
        string escrowType;
        address seller;
        address buyer;
        address coinAddress;
        bool approvedBySeller;
        bool approvedByBuyer;
        bool active;
        uint256 creationTime;
        uint256 deadlineTime;
        string title;
        string itemName;
        string itemDescription;
        string itemCategory;
        bool feePaidByBuyer;
    }

    struct Milestone {
        string description;
        uint256 price;
        string fileUrl;
        bool completed;
    }

    address public owner;
    IERC20 private _coin;
    uint256 public platformFee = 3; // %
    address feeRecipient = 0x6501644989e8029892792ebeE2DdF276b2A112FD;
    Escrow private _escrow;
    Milestone[] private _milestones;

    constructor(
        address _creator, 
        Escrow memory _createdEscrow, 
        Milestone[] memory _createdMilestones,
        address _escrowDatabaseAddress,
        address _escrowDisputeAddress
    ) {
        owner = _creator;

        _escrowDatabaseContract = IEscrowDatabase(_escrowDatabaseAddress);
        _escrowDisputeContract = IEscrowDispute(_escrowDisputeAddress);

        _escrow = _createdEscrow;

        for (uint256 i = 0; i < _createdMilestones.length; i++) {
            Milestone memory _milestone = Milestone(
                _createdMilestones[i].description,
                _createdMilestones[i].price,
                '',
                false
            );

            _milestones.push(_milestone);
        }

        _coin = IERC20(_createdEscrow.coinAddress);
    }

    fallback() external payable {}

    receive() external payable {}

    modifier isActive() {
        require(_escrow.active == true, "Escrow is not active");
        _;
    }

    modifier onlyForBuyerAndSeller() {
        require(msg.sender == _escrow.buyer || msg.sender == _escrow.seller, "You are neither a seller not a buyer");
        _;
    }
    
    modifier notDisputed(uint256 _milestoneId) {
        bool disputeStatus = _escrowDisputeContract.getDisputeStatusByAddressAndMilestoneId(address(this), _milestoneId);

        require(!disputeStatus, "Milestone in dispute status");
        _;
    }

    function getEscrow() public onlyForBuyerAndSeller view returns (Escrow memory) {
        return _escrow;
    }

    function getMilestones() public onlyForBuyerAndSeller view returns (Milestone[] memory) {
        return _milestones;
    }

    function withdrawFundsFromBuyer() public {
        require(msg.sender == _escrow.buyer, "Not an escrow buyer");

        if (!_escrow.active) {
            _escrow.active = true;
        }

        uint256 _totalFee = 0;

        for (uint256 i = 0; i < _milestones.length; i++) {
            _totalFee = _totalFee.add(_milestones[i].price);
        }

        uint256 _platformFeeAmount = (_totalFee.mul(platformFee)).div(100);

        if (_escrow.feePaidByBuyer) {
            _totalFee = _totalFee.add(_platformFeeAmount);
        }

        _coin.transferFrom(_escrow.buyer, address(this), _totalFee); // Taking money into Escrow with platform fee

        if (_escrow.feePaidByBuyer) {
            _coin.transfer(feeRecipient, _platformFeeAmount); // Transfer fee to Fee Recipient
        }
    }

    function approveEscrow(bool _approvedFromBuyer) public isActive {
        if (_approvedFromBuyer) {
            require(_escrow.buyer == msg.sender, "Not an escrow buyer");
            require(_escrow.approvedByBuyer == false , "Already approved by buyer");

            withdrawFundsFromBuyer();

            _escrow.approvedByBuyer = true;
        } else {
            require(_escrow.seller == msg.sender, "Not an escrow seller");
            require(_escrow.approvedBySeller == false , "Already approved by seller");

            _escrow.approvedBySeller = true;
        }

        _escrowDatabaseContract.addEscrowsOfUser(msg.sender, address(this));

        _escrow.deadlineTime = block.timestamp + _escrow.deadlineTime;
    }

    function sellerReleaseMilestone(
        uint256 _milestoneId, 
        string memory _ipfsUrl
    ) public isActive notDisputed(_milestoneId) returns (Milestone memory) {
        require(msg.sender == _escrow.seller, "Not an escrow seller");
        require(_milestoneId >= 0 && _milestoneId < _milestones.length, "Undefined milstone id");
        require(_escrow.approvedByBuyer, "Escrow not approved by buyer");
        require(_escrow.approvedBySeller, "Escrow not approved by seller");
        require(!_milestones[_milestoneId].completed, "Milestone is completed");

        _milestones[_milestoneId].fileUrl = _ipfsUrl;

        return _milestones[_milestoneId];
    }

    function buyerApproveMilestone(uint256 _milestoneId) public isActive notDisputed(_milestoneId) returns (Milestone memory) {
        require(_escrow.buyer == msg.sender, "Not a buyer of this escrow");
        require(_milestoneId >= 0 && _milestoneId < _milestones.length, "Undefined milstone id");
        require(_escrow.approvedByBuyer, "Escrow not approved by buyer");
        require(_escrow.approvedBySeller, "Escrow not approved by seller");
        require(!_milestones[_milestoneId].completed, "Milestone already approved");

        _milestones[_milestoneId].completed = true;

        uint256 _amountToSeller = _milestones[_milestoneId].price;
        uint256 _platformFee = 0;

        if (!_escrow.feePaidByBuyer) {
            _platformFee = (_amountToSeller.mul(platformFee)).div(100);

            _amountToSeller = _amountToSeller.sub(_platformFee);
        }

        _coin.transfer(_escrow.seller, _amountToSeller); // Giving milestone money to seller

        if (!_escrow.feePaidByBuyer) {
            _coin.transfer(feeRecipient, _platformFee); // Transfer fee to fee recipient
        }

        return _milestones[_milestoneId];
    }

    function raiseDispute(
        uint256 _milestoneId,
        string memory _title,
        string memory _body,
        string[] memory _choices,
        uint64 _start,
        uint64 _end,
        uint256 _refund
    ) public onlyForBuyerAndSeller returns (uint256) {
        require(_testStringForValue(_milestones[_milestoneId].fileUrl), "Milestone was not published by seller");

        bool _raiseByBuyer;

        if (msg.sender == _escrow.buyer) {
            _raiseByBuyer = true;
        } else {
            _raiseByBuyer = false;
        }

        return _escrowDisputeContract.raiseDispute(
            _milestoneId,
            _raiseByBuyer,
            msg.sender,
            _title,
            _body,
            _choices,
            _start,
            _end,
            _refund
        );
    }

    function resolveDispute(uint256 _milestoneId) public returns (bool) {
        uint8 _disputeWinningChoice = _escrowDisputeContract.resolveDispute(_milestoneId, msg.sender);

        if (_disputeWinningChoice == 1) {
            uint256 _amount = (_milestones[_milestoneId].price * _escrowDisputeContract.getRefund(_milestoneId)).div(100);

            _milestones[_milestoneId].price = (_milestones[_milestoneId].price).sub(_amount);

            bool _disputedByBuyer = _escrowDisputeContract.getRaiseByBuyerOfDispute(_milestoneId);

            if (_disputedByBuyer) {
                _coin.transfer(_escrow.buyer, _amount);
            } else {
                _coin.transfer(_escrow.seller, _amount);
                _coin.transfer(_escrow.buyer, _milestones[_milestoneId].price);

                _milestones[_milestoneId].price = 0;
            }

            return true;
        } else {
            return false;
        }
    }

    function cancelEscrow() public isActive {
        require(msg.sender == owner, "You are not the escrow owner");

        bool _callerIsBuyer;

        if (msg.sender == _escrow.buyer) {
            _callerIsBuyer = true;
        } else {
            _callerIsBuyer = false;
        }

        if (_callerIsBuyer) {
            require(!_escrow.approvedBySeller, "Seller approved escrow");

            uint256 _milestonesCoinSum;

            for (uint256 i = 0; i < _milestones.length; i++) {
                _milestonesCoinSum = _milestonesCoinSum.add(_milestones[i].price);
            }

            _coin.transfer(_escrow.buyer, _milestonesCoinSum);
        } else {
            require(!_escrow.approvedByBuyer, "Buyer approved escrow");
        }

        _escrow = Escrow(
            _escrow.id,
            "",
            address(0),
            address(0),
            address(0),
            false,
            false,
            false,
            0,
            0,
            "",
            "",
            "",
            "",
            false
        );

        _escrowDatabaseContract.deleteFromEscrowsOfUser(msg.sender, address(this));
    }

    function _testStringForValue(string memory _string) private pure returns(bool) {
        bytes memory _stringInBytes = bytes(_string);

        if (_stringInBytes.length != 0) {
            return true;
        } else {
            return false;
        }
    }
}
// File: contracts/factories/GoodsFactory.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;

import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/IEscrowDatabase.sol";
import "../interfaces/IEscrowDispute.sol";
import "../escrows/GoodsEscrow.sol";
import "../EscrowDatabase.sol";

contract GoodsFactory is Ownable {
    IEscrowDatabase private _escrowDatabaseContract;
    IEscrowDispute private _escrowDisputeContract;

    fallback() external payable {}

    receive() external payable {}

    function setEscrowDatabaseContract(address _escrowDatabaseAddress) public onlyOwner {
        _escrowDatabaseContract = IEscrowDatabase(_escrowDatabaseAddress);
    }

    function setEscrowDisputeContract(address _escrowDisputeAddress) public onlyOwner {
        _escrowDisputeContract = IEscrowDispute(_escrowDisputeAddress);
    }

    function createGoodsEscrow(
        address _seller,
        address _buyer,
        address _coinAddress,
        uint256 _deadlineTime,
        string memory _title,
        string memory _itemName,
        string memory _itemDescription,
        string memory _itemCategory,
        bool _feePaidByBuyer,
        GoodsEscrow.Milestone[] memory _milestones
    ) public returns (address) {
        bool _approvedBySeller = false;
        bool _approvedByBuyer = false;

        if (msg.sender == _seller) {
            _approvedBySeller = true;
        } else if (msg.sender == _buyer) {
            _approvedByBuyer = true;
        } else {
            require(true == false, "You are neither a seller not a buyer");
        }

        _escrowDatabaseContract.increaseEscrowCounter();

        GoodsEscrow.Escrow memory _escrow = GoodsEscrow.Escrow(
            _escrowDatabaseContract.escrowCounter(),
            "Goods",
            _seller,
            _buyer,
            _coinAddress,
            _approvedBySeller,
            _approvedByBuyer,
            !_approvedByBuyer,
            block.timestamp,
            _deadlineTime,
            _title,
            _itemName,
            _itemDescription,
            _itemCategory,
            _feePaidByBuyer
        );

       GoodsEscrow _newGoodsEscrow = new GoodsEscrow(
            msg.sender, 
            _escrow, 
            _milestones, 
            address(_escrowDatabaseContract),
            address(_escrowDisputeContract)
       );

       _escrowDatabaseContract.addAllEscrowContracts(address(_newGoodsEscrow));

       _escrowDatabaseContract.addGoodsEscrowContracts(address(_newGoodsEscrow));

       _escrowDatabaseContract.addEscrowsOfUser(msg.sender, address(_newGoodsEscrow));

       return address(_newGoodsEscrow);
    }
}
// File: contracts/interfaces/IEscrowDatabase.sol



// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.18;

interface IEscrowDatabase {
    function escrowCounter() external view returns(uint256);

    function increaseEscrowCounter() external;

    function addAllEscrowContracts(address _allContractAddress) external;

    function addGoodsEscrowContracts(address _goodsContractAddress) external;

    function addEscrowsOfUser(address _address, address _escrowContractAddress) external;

    function deleteFromEscrowsOfUser(address _address, address _escrowContractAddress) external;

    function addServicesEscrowContracts(address _servicesContractAddress) external;

    function addNftEscrowContracts(address _nftContractAddress) external;

    function addSourceCodeEscrowContracts(address _sourceCodeContractAddress) external;

    function addGamblingEscrowContracts(address _gamblingContractAddress) external;
    
    function getAllEscrowContracts() external view returns(address[] memory);

    function getGoodsEscrowContracts() external view returns (address[] memory);

    function getServicesEscrowContracts() external view returns (address[] memory);

    function getNftEscrowContracts() external view returns (address[] memory);

    function getSourceCodeEscrowContracts() external view returns (address[] memory);

    function getGamblingEscrowContracts() external view returns (address[] memory);
}
// File: contracts/interfaces/IEscrowDispute.sol



// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.18;

interface IEscrowDispute {
    function getEscrowsInDispute() external view returns (address[] memory);

    function getRefund(uint256 _milestoneId) external view returns(uint256);

    function getRaiseByBuyerOfDispute(uint256 _milestoneId) external view returns(bool);

    function getDisputeStatusByAddressAndMilestoneId(address _escrowAddress, uint256 _milestoneId) external view returns(bool);

    function raiseDispute(
        uint256 _milestoneId,
        bool _raiseByBuyer,
        address _creator,
        string memory _title,
        string memory _body,
        string[] memory _choices,
        uint64 _start,
        uint64 _end,
        uint256 _refund
    ) external returns (uint256);

    function resolveDispute(
        uint256 _milestoneId, 
        address _caller
    ) external returns (uint8);
}