
ALTER PROCEDURE PROC_EASYREMIT(
@flag             VARCHAR(50), 
@Country          VARCHAR(50) = NULL, 
@NativeCountry    VARCHAR(50) = NULL, 
@Id               INT = NULL, 
@Name             VARCHAR(200) = NULL, 
@Password         VARCHAR(50) = NULL, 
@Gender           VARCHAR(50) = NULL, 
@DOB              VARCHAR(50) = NULL, 
@cusType          VARCHAR(50) = NULL, 
@MobileNumber     VARCHAR(50) = NULL, 
@isKftcOnly       VARCHAR(2) = NULL, 
@TelephoneNo      VARCHAR(50) = NULL, 
@Email            VARCHAR(50) = NULL, 
@Customeremail    VARCHAR(50) = NULL, 
@CustomerBankName VARCHAR(100) = NULL, 
@City             VARCHAR(50) = NULL, 
@Address          VARCHAR(50) = NULL, 
@Occupation       VARCHAR(50) = NULL, 
@SOF              VARCHAR(50) = NULL, 
@IdType           VARCHAR(50) = NULL, 
@IdNumber         VARCHAR(50) = NULL, 
@accountNumber    VARCHAR(30) = NULL, 
@IssueDate        VARCHAR(150) = NULL, 
@IdExpireDate     VARCHAR(150) = NULL, 
@IdCardFront      VARCHAR(150) = NULL, 
@IdCardBack       VARCHAR(150) = NULL, 
@ReferelCode      VARCHAR(50) = NULL, 
@createdBy        VARCHAR(50) = NULL, 
@HasDeclare       VARCHAR(1) = NULL, 
@createdDate      VARCHAR(50) = NULL, 
@user             VARCHAR(50) = NULL, 
@sortBy           VARCHAR(50) = NULL, 
@sortOrder        VARCHAR(5) = NULL, 
@pageSize         INT = NULL, 
@pageNumber       INT = NULL) 
AS 
    SET nocount ON; 
    SET xact_abort ON; 

  BEGIN try 
      DECLARE @table             VARCHAR(max), 
              @select_field_list VARCHAR(max), 
              @extra_field_list  VARCHAR(max), 
              @sql_filter        VARCHAR(max), 
              @modType           VARCHAR(6), 
              @errorMsg          VARCHAR(max), 
              @bankName          VARCHAR(100), 
              @userType          VARCHAR(5), 
              @custIdNumber      VARCHAR(50), 
              @customerGuid      VARCHAR(50) 

      IF @flag = 'customer-list' 
        BEGIN 
            IF @sortBy IS NULL 
              SET @sortBy = 'createdDate' 

            IF @sortOrder IS NULL 
              SET @sortOrder = 'DESC' 

            SET @table = 
            '(    SELECT     customerId as Id     ,fullName = ISNULL(firstName, '''') + ISNULL('' '' + middleName, '''') + ISNULL('' '' + lastName1, '''') + ISNULL('' '' + lastName2, '''')      
			,sd.detailTitle as idType     ,ISNULL(cm.idNumber,'''') as idNumber     ,com.countryName     ,cm.city     ,ISNULL(cm.email,'''') as email     ,ISNULL(cm.mobile,'''') as mobile     
			,cm.createdDate     ,accountName =cm.bankAccountNo     ,bankName = bl.bankName    FROM dbo.customerMaster cm(nolock)    
			LEFT JOIN dbo.staticDataValue sd(nolock) ON sd.valueId=cm.idType    
			INNER JOIN dbo.countryMaster com(nolock) ON com.countryId = cm.nativeCountry    
			LEFT JOIN vwBankLists bl (NOLOCK) ON cm.bankName = bl.rowId    
			WHERE customerType =11048  and cm.approvedDate is null ' 

            IF @createdDate IS NOT NULL 
              SET @table = @table + '  AND cm.createdDate between ''' + CONVERT(VARCHAR, @createdDate, 101) + ''' AND ''' + CONVERT(VARCHAR, @createdDate, 101) + ' 23:59:59'''; 

            SET @table=@table + ')x' 
            SET @sql_filter = '' 

            IF @MobileNumber IS NOT NULL 
              SET @sql_filter = @sql_filter 
                                + '  AND REPLACE(idNumber, ''-'', '''') =''' + Replace(@MobileNumber, '-', '') + ''''; 

            IF @email IS NOT NULL 
              SET @sql_filter += ' AND  email like ''' + @email + '%'''; 

            IF @NativeCountry IS NOT NULL 
              SET @sql_filter += ' AND  countryName = ''' + @NativeCountry + ''''; 

            SET @select_field_list = 'id,fullName,idType,idNumber,countryName,city,email,mobile,createdDate,accountName,bankName' 

    EXEC dbo.Proc_paging 
      @table, 
      @sql_filter, 
      @select_field_list, 
      @extra_field_list, 
    @sortBy, 
      @sortOrder, 
      @pageSize, 
      @pageNumber 

    RETURN 
END 

    IF @flag = 'i' 
      BEGIN 
          IF EXISTS(SELECT 'X' FROM   customermaster WITH (nolock) WHERE  email = @Email) 
            BEGIN 
                SELECT @errorMsg = 'Customer with email ' + @Email + ' already exist.' 

                EXEC Proc_errorhandler  1,@errorMsg, @Id 
                RETURN 
            END 

          IF EXISTS(SELECT 'x'  FROM   customermaster (nolock) WHERE  Replace(idnumber, '-', '') = Replace(@IdNumber, '-', '')) 
            BEGIN 
                SELECT @errorMsg = 'Customer with idnumber ' + @IdNumber + ' already exist.' 

                EXEC Proc_errorhandler 1, @errorMsg,@Id 
                RETURN 
            END 

          IF EXISTS(SELECT 'X' FROM   customermaster WITH (nolock) 
                    WHERE  mobile = @MobileNumber 
                    AND Isnull(onlineuser, 'N') = 'Y' 
                    AND Isnull(isdeleted, 'N') = 'N') 
            BEGIN 
                SELECT @errorMsg = 'Customer with mobile number ' + @MobileNumber + ' already exist.' 

                EXEC Proc_errorhandler  1,@errorMsg,@Id 

                RETURN 
            END 

          INSERT INTO customermaster 
                (country,nativecountry, fullname, customerpassword, email, gender, dob, mobile, homephone, customeremail, city, address, occupation, 
				sourceoffund, idtype, idnumber, idissuedate, verifydoc1, verifydoc2, referelcode, createdby, createddate, 
				branchid, isactive, isforcedpwdchange, customertype, 
				firstname,idexpirydate, onlineuser,bankName) 
          VALUES     
			( 118, @NativeCountry,@Name, dbo.Fnaencryptstring(@Password), @Email, @Gender, CONVERT(DATETIME, @DOB, 103),@MobileNumber, @IdNumber, @Customeremail, @City, @Address, @Occupation, 
				@SOF, @IdType,@IdNumber, CONVERT(DATETIME, @IssueDate, 103), @IdCardFront, @IdCardBack, @ReferelCode, @createdBy, Getdate(), 
				(SELECT agentid FROM   applicationusers(nolock) WHERE  username = @user), 'Y', 1, 11048 --'Easy Remit'  
				, @Name, CONVERT(DATETIME, @IdExpireDate, 103), 'Y',27 ) 

          SET @Id = @@IDENTITY 

          INSERT INTO tblcustomerbankverification (customerid, action,reqdate, certdate, certnumber, certlimitcount) 
          SELECT @Id, 'SUCCESS', Getdate(),Getdate(), '', 0 

          EXEC Proc_errorhandler 0, 'Record Save successfully', NULL 
          RETURN 
      END 

    IF @flag = 'U' 
      BEGIN 
          SELECT @userType = usertype FROM   applicationusers (nolock) 
          WHERE  username = @user 

        IF EXISTS (SELECT 'a' FROM   dbo.customermaster (nolock) 
                     WHERE  customerid = @Id AND approvedby IS NOT NULL AND @userType <> 'HO') 
        BEGIN 
            SELECT '1' ErrorCode , 'Customer is already approved, you can not modify this customer data.' Msg , @Id id 
			RETURN 
        END 

          --LOG FOR CUSTOMER UPDATE   
          EXEC Proc_customermodifylog 
            @flag = 'i', 
            @email = @Email, 
            @idNumber = @IdNumber, 
            @bank = NULL, 
            @accNumber = @accountNumber, 
            @customerId = @Id, 
            @mobileNumber = @MobileNumber, 
            @user = @user, 
            @idType = @IdType, 
            @dob = @DOB, 
            @issueDate = @IssueDate, 
            @expiryDate =@IdExpireDate 

          UPDATE customermaster 
          SET    nativecountry		= @NativeCountry, 
                 fullname			= @Name, 
                 customerpassword	= [REDACTED] 
                 email				= @Email, 
                 gender				= @Gender, 
                 dob				= CONVERT(DATETIME, @DOB, 103), 
                 mobile				= @MobileNumber, 
                 customeremail		= @Customeremail, 
                 city				= @City, 
				 address			= @Address, 
                 occupation			= @Occupation, 
                 sourceoffund		= @SOF, 
                 idtype				= @IdType, 
                 idnumber			= @IdNumber, 
                 idissuedate		= CONVERT(DATETIME, @IssueDate, 103), 
                 verifydoc1			= @IdCardFront, 
                 verifydoc2			= @IdCardBack, 
                 firstname			= @Name, 
                 idexpirydate		= CONVERT(DATETIME, @IdExpireDate, 103), 
                 hasdeclare			= @HasDeclare, 
                 modifiedby			= @user, 
                 modifieddate		= Getdate() 
          WHERE  customerid = @Id 

          EXEC Proc_errorhandler 0,'Record Update successfully',NULL 
          RETURN 
      END 

    IF @flag = 'customer-details' 
      BEGIN 
          SELECT customerid,cu.walletaccountno,cu.membershipid, isTxnMade = 'N', firstname, middlename, lastname1, lastname2, country, address, zipcode, city, email, 
				mobile = Replace(mobile, '+', ''), nativecountry, homephone, occupation,address2, fullname, postalcode, idtype, idnumber, telno, companyname, gender, 
				ipaddress, verifydoc1, verifydoc2, verifiedby, verifieddate, bankaccountno,isApproved = CASE WHEN approvedby IS NULL THEN 'N' ELSE 'Y' END, 
				CONVERT(VARCHAR, dob, 101)          AS dob, CONVERT(VARCHAR, idissuedate, 101)  AS idIssueDate, CONVERT(VARCHAR, idexpirydate, 101) AS idExpiryDate, 
				membershipid, Isnull(cu.bonuspoint, 0)  AS RewardPoint 
				,cu.sourceOfFund AS sourceOfFund
          FROM   customermaster cu WITH(nolock) 
          WHERE  customerid = @Id AND customertype = 11048 
          RETURN 
      END 

    IF @flag = 'approve-pending' 
    BEGIN 
          SELECT @custIdNumber = idnumber FROM   dbo.customermaster (nolock) 
          WHERE  customerid = @Id 

          SELECT @cusType = usertype FROM   applicationusers(nolock) 
          WHERE  username = @user 

          IF EXISTS (SELECT 'X' FROM   dbo.customermaster (nolock) 
                     WHERE  Replace(idnumber, '-', '') = Replace(@IdNumber, '-', '') 
                     GROUP  BY Replace(idnumber, '-', '') 
                     HAVING Count(1) > 1) 
            BEGIN 
                SELECT '1' ErrorCode, 'Duplicate id number found for customer' Msg, NULL 
                RETURN 
            END 

          IF EXISTS (SELECT 'X' FROM   dbo.customermaster (nolock) 
                     WHERE  Replace(idnumber, '-', '') = Replace(@IdNumber, '-', '') 
                    AND approvedby IS NOT NULL) 
            BEGIN 
                SELECT '1' ErrorCode,'Customer with same id number already approved.' Msg,NULL 
                RETURN 
            END 

          --IF NOT EXISTS ( SELECT TOP 1 virtualAccNumber from WSBWalletList  WITH (NOLOCK) )   
          --BEGIN   
          --SELECT '1' ErrorCode , 'No stock Virtual account found, please upload  ! Warning ' Msg ,null   
          --RETURN   
          --END   
          IF EXISTS(SELECT 'A' FROM   customermaster(nolock) 
                    WHERE  customerid = @Id AND walletaccountno IS NULL) 
            BEGIN 
                SELECT TOP 1 @accountNumber = virtualaccnumber 
                FROM   wsbwalletlist WITH (nolock) 
                WHERE  customerid IS NULL 

                UPDATE wsbwalletlist 
                SET    customerid = @Id, 
                       createdby = @user, 
                       createddate = Getdate() 
                WHERE  virtualaccnumber = @accountNumber 

                UPDATE dbo.customermaster 
                SET    walletaccountno = @accountNumber, 
                       customerbankname = @CustomerBankName, 
                       dob = CASE WHEN dob IS NULL AND idtype IN( 1302, 8008 ) THEN dbo.Fnagetdob_from_aliencard(LEFT(@custIdNumber, 6), RIGHT( LEFT(@custIdNumber, 8), 1)) ELSE dob END, 
					   iskftconly = @isKftcOnly 
				WHERE  customerid = @Id 
	END 

	DECLARE @newPassword VARCHAR(20) = RIGHT('0000000' + Cast(Checksum(Newid()) AS VARCHAR), 7) 

	IF EXISTS(SELECT 'A' FROM   customermaster(nolock) WHERE  customerid = @Id AND customerpassword IS NOT NULL) 
		SELECT @newPassword = [REDACTED] FROM   customermaster(nolock) WHERE  customerid = @Id AND customerpassword IS NOT NULL 
	ELSE 
	BEGIN 
		UPDATE dbo.customermaster 
		SET    customerpassword = [REDACTED] 
		WHERE  customerid = @Id 
	END 

	DECLARE @tlgSeqNo VARCHAR(10), @NewValue VARCHAR(10) 

	SET @NewValue= next value FOR dbo.wsb_sequence SET @tlgSeqNo=(SELECT CONVERT(VARCHAR(6), Getdate(), 12)) + @NewValue 

	SELECT dataLen =400, orgtId='GME', srvcDs='VT0401', trxTypeCd='0200',rspsCd='0000', tlgSeqNo=@tlgSeqNo, tlgSendHur=(SELECT Format(Getdate(), 'yyyyMMddHHmmss')), 
		filler=NULL, username = Isnull(cm.email, ''), [password] = dbo.Fnadecryptstring(cm.customerpassword), 
		[channel] = 'registration', [account] = Isnull(cm.membershipid, ''), walletaccountno, bankaccountno, fullname, customerbankname, bankCode =NULL, cm.idtype, 
		Replace(cm.idnumber, ' ', '')   AS [idNumber], CONVERT(VARCHAR(6), cm.dob, 12) AS [dobYMD], CASE WHEN cm.gender = '97' THEN '7' WHEN cm.gender = '98' THEN '8' END AS [genderCode], 
		CASE WHEN cm.nativecountry = '238' THEN '1' WHEN cm.nativecountry = '113' THEN '2' WHEN cm.nativecountry = '45' THEN '3' ELSE '4' END AS [nativeCountryCode],customerid 
	FROM   dbo.customermaster cm(nolock) 
	--INNER JOIN  KoreanBankList k (nolock) on k.rowId = cm.bankName   
	WHERE  cm.customerid = @Id 

	SELECT '0' ErrorCode, 'Customer verified successfully.' Msg, @Id  id 

	RETURN 
	END 

    IF @flag = 'verify-customer-details' 
      BEGIN 
          DECLARE @duplicateCustomer VARCHAR(100) 

          SELECT @duplicateCustomer ='Suspicious customer detail match with Old Id number :'  + m.idnumber 
          FROM   suspiciousregisteredcustomer c(nolock) 
          INNER JOIN customermaster m(nolock) ON c.matchedcustomerid = m.customerid 
          WHERE  orgcustomerid = @Id 

          SELECT cm.walletaccountno                  AS [walletNumber], 
                 cm.customerid, 
                 email, 
                 membershipid                        AS [goldcardnumber], 
                 cm.fullname, 
                 sdg.detailtitle                     AS [gender], 
                 cmb.countryname                     AS [country], 
                 cmn.countryname                     AS [nativeCountry], 
                 cm.homephone, 
                 cm.postalcode, 
                 cm.[address], 
                 cm.city, 
                 cm.telno, 
                 cm.mobile, 
                 sdo.detailtitle                     AS [occupation], 
                 sdi.detailtitle                     AS [idType], 
                 cm.idtype                           AS [idTypeCode], 
                 cm.idnumber, 
                 cm.verifydoc1, 
                 cm.verifydoc2, 
                 cm.verifydoc3, 
                 CONVERT(VARCHAR, dob, 101)          AS [dob], 
                 CONVERT(VARCHAR, idissuedate, 101)  AS [idIssueDate], 
                 CONVERT(VARCHAR, idexpirydate, 101) AS [idExpiryDate], 
                 bl.bankname, 
                 bl.bankcode, 
                 cm.bankaccountno, 
                 cm.walletaccountno, 
                 cm.homephone, 
                 cm.availablebalance, 
                 verifyDoc4 = selfiedoc, 
                 cm.obpid, 
                 cm.auditdate, 
                 SuspCust = CASE 
                              WHEN cm.customerstatus = 'V' THEN 
                              'Face to Face Customer Verified At GME Branch' 
                              ELSE @duplicateCustomer 
                            END, 
                 CustomerStatus = CASE 
                                    WHEN cm.hasdeclare = 1 THEN 'S' 
                                  ELSE cm.customerstatus 
                                END, 
                 CONVERT(VARCHAR(6), cm.dob, 12)     AS [dobYMD], 
                 CASE 
                   WHEN gender = '97' THEN '7' 
                   WHEN gender = '98' THEN '8' 
                 END                                 AS [genderCode], 
                 CASE 
                   WHEN nativecountry = '238' THEN '1' 
                   WHEN nativecountry = '113' THEN '2' 
                   WHEN nativecountry = '45' THEN '3' 
                   ELSE '4' 
                 END                                 AS [nativeCountryCode], 
                 CM.approvedby, 
                 cm.approveddate, 
                 Isnull(CM.bonuspoint, 0)            AS RewardPoint 
          FROM   customermaster cm (nolock) 
                 LEFT JOIN staticdatavalue sdg (nolock) ON sdg.valueid = cm.gender 
                 LEFT JOIN dbo.countrymaster cmb (nolock) ON cmb.countryid = cm.country 
                 LEFT JOIN dbo.countrymaster cmn (nolock) ON cmn.countryid = cm.nativecountry 
                 LEFT JOIN staticdatavalue sdo (nolock) ON sdo.valueid = cm.occupation 
                 LEFT JOIN staticdatavalue sdi (nolock) ON sdi.valueid = cm.idtype 
                 LEFT JOIN koreanbanklist bl (nolock) ON cm.bankname = bl.rowid 
          WHERE  customerid = @Id AND cm.customertype = 11048 

          RETURN 
      END 

    IF @Flag = 'CUSTOMERINFO' 
    BEGIN 
        SELECT TOP 1 '0' ErrorCode,walletaccountno AS vtulAccNo,firstname       AS custNm 
        FROM   dbo.customermaster(nolock) 
        WHERE  customertype = '11048' 

        RETURN 
    END 
END try 

  BEGIN CATCH 
      IF @@TRANCOUNT > 0 
        ROLLBACK TRANSACTION 

      DECLARE @errorMessage VARCHAR(max) 

      SET @errorMessage = Error_message() 

      EXEC Proc_errorhandler 1,@errorMessage,NULL 
  END CATCH